]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Add HTTP Referer: tracking.
[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 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
889 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
890 @end
891 /* }}} */
892
893 /* Status Delegation {{{ */
894 class Status :
895 public pkgAcquireStatus
896 {
897 private:
898 _transient NSObject<ProgressDelegate> *delegate_;
899 bool cancelled_;
900
901 public:
902 Status() :
903 delegate_(nil),
904 cancelled_(false)
905 {
906 }
907
908 void setDelegate(NSObject<ProgressDelegate> *delegate) {
909 delegate_ = delegate;
910 }
911
912 NSObject<ProgressDelegate> *getDelegate() const {
913 return delegate_;
914 }
915
916 virtual bool MediaChange(std::string media, std::string drive) {
917 return false;
918 }
919
920 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
921 Done(item);
922 }
923
924 virtual void Fetch(pkgAcquire::ItemDesc &item) {
925 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
926 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
927 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
928 }
929
930 virtual void Done(pkgAcquire::ItemDesc &item) {
931 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
932 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
933 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
934 }
935
936 virtual void Fail(pkgAcquire::ItemDesc &item) {
937 if (
938 item.Owner->Status == pkgAcquire::Item::StatIdle ||
939 item.Owner->Status == pkgAcquire::Item::StatDone
940 )
941 return;
942
943 std::string &error(item.Owner->ErrorText);
944 if (error.empty())
945 return;
946
947 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
948 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
949 }
950
951 virtual bool Pulse(pkgAcquire *Owner) {
952 bool value = pkgAcquireStatus::Pulse(Owner);
953
954 double percent(
955 double(CurrentBytes + CurrentItems) /
956 double(TotalBytes + TotalItems)
957 );
958
959 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
960 [NSNumber numberWithDouble:percent], @"Percent",
961
962 [NSNumber numberWithDouble:CurrentBytes], @"Current",
963 [NSNumber numberWithDouble:TotalBytes], @"Total",
964 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
965 nil] waitUntilDone:YES];
966
967 if (value && ![delegate_ isProgressCancelled])
968 return true;
969 else {
970 cancelled_ = true;
971 return false;
972 }
973 }
974
975 _finline bool WasCancelled() const {
976 return cancelled_;
977 }
978
979 virtual void Start() {
980 pkgAcquireStatus::Start();
981 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
982 }
983
984 virtual void Stop() {
985 pkgAcquireStatus::Stop();
986 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
987 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
988 }
989 };
990 /* }}} */
991 /* Database Interface {{{ */
992 typedef std::map< unsigned long, _H<Source> > SourceMap;
993
994 @interface Database : NSObject {
995 NSZone *zone_;
996 apr_pool_t *pool_;
997
998 unsigned era_;
999
1000 pkgCacheFile cache_;
1001 pkgDepCache::Policy *policy_;
1002 pkgRecords *records_;
1003 pkgProblemResolver *resolver_;
1004 pkgAcquire *fetcher_;
1005 FileFd *lock_;
1006 SPtr<pkgPackageManager> manager_;
1007 pkgSourceList *list_;
1008
1009 SourceMap sourceMap_;
1010 _H<NSMutableArray> sourceList_;
1011
1012 CFMutableArrayRef packages_;
1013
1014 _transient NSObject<DatabaseDelegate> *delegate_;
1015 _transient NSObject<ProgressDelegate> *progress_;
1016
1017 Status status_;
1018
1019 int cydiafd_;
1020 int statusfd_;
1021 FILE *input_;
1022
1023 std::map<const char *, _H<NSString> > sections_;
1024 }
1025
1026 + (Database *) sharedInstance;
1027 - (unsigned) era;
1028
1029 - (void) _readCydia:(NSNumber *)fd;
1030 - (void) _readStatus:(NSNumber *)fd;
1031 - (void) _readOutput:(NSNumber *)fd;
1032
1033 - (FILE *) input;
1034
1035 - (Package *) packageWithName:(NSString *)name;
1036
1037 - (pkgCacheFile &) cache;
1038 - (pkgDepCache::Policy *) policy;
1039 - (pkgRecords *) records;
1040 - (pkgProblemResolver *) resolver;
1041 - (pkgAcquire &) fetcher;
1042 - (pkgSourceList &) list;
1043 - (NSArray *) packages;
1044 - (NSArray *) sources;
1045 - (Source *) sourceWithKey:(NSString *)key;
1046 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1047
1048 - (void) configure;
1049 - (bool) prepare;
1050 - (void) perform;
1051 - (bool) upgrade;
1052 - (void) update;
1053
1054 - (void) updateWithStatus:(Status &)status;
1055
1056 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1057
1058 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1059 - (NSObject<ProgressDelegate> *) progressDelegate;
1060
1061 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1062
1063 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1064
1065 @end
1066 /* }}} */
1067 /* ProgressEvent Implementation {{{ */
1068 @implementation CydiaProgressEvent
1069
1070 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1071 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1072 }
1073
1074 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1075 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1076 [event setPackage:package];
1077 return event;
1078 }
1079
1080 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1081 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1082
1083 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1084 NSArray *fields([description componentsSeparatedByString:@" "]);
1085 [event setItem:fields];
1086
1087 if ([fields count] > 3) {
1088 [event setPackage:[fields objectAtIndex:2]];
1089 [event setVersion:[fields objectAtIndex:3]];
1090 }
1091
1092 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1093
1094 return event;
1095 }
1096
1097 + (NSArray *) _attributeKeys {
1098 return [NSArray arrayWithObjects:
1099 @"item",
1100 @"message",
1101 @"package",
1102 @"type",
1103 @"url",
1104 @"version",
1105 nil];
1106 }
1107
1108 - (NSArray *) attributeKeys {
1109 return [[self class] _attributeKeys];
1110 }
1111
1112 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1113 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1114 }
1115
1116 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1117 if ((self = [super init]) != nil) {
1118 message_ = message;
1119 type_ = type;
1120 } return self;
1121 }
1122
1123 - (NSString *) message {
1124 return message_;
1125 }
1126
1127 - (NSString *) type {
1128 return type_;
1129 }
1130
1131 - (NSArray *) item {
1132 return (id) item_ ?: [NSNull null];
1133 }
1134
1135 - (void) setItem:(NSArray *)item {
1136 item_ = item;
1137 }
1138
1139 - (NSString *) package {
1140 return (id) package_ ?: [NSNull null];
1141 }
1142
1143 - (void) setPackage:(NSString *)package {
1144 package_ = package;
1145 }
1146
1147 - (NSString *) url {
1148 return (id) url_ ?: [NSNull null];
1149 }
1150
1151 - (void) setURL:(NSString *)url {
1152 url_ = url;
1153 }
1154
1155 - (void) setVersion:(NSString *)version {
1156 version_ = version;
1157 }
1158
1159 - (NSString *) version {
1160 return (id) version_ ?: [NSNull null];
1161 }
1162
1163 - (NSString *) compound:(NSString *)value {
1164 if (value != nil) {
1165 NSString *mode(nil); {
1166 NSString *type([self type]);
1167 if ([type isEqualToString:kCydiaProgressEventTypeError])
1168 mode = UCLocalize("ERROR");
1169 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1170 mode = UCLocalize("WARNING");
1171 }
1172
1173 if (mode != nil)
1174 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1175 }
1176
1177 return value;
1178 }
1179
1180 - (NSString *) compoundMessage {
1181 return [self compound:[self message]];
1182 }
1183
1184 - (NSString *) compoundTitle {
1185 NSString *title;
1186
1187 if (package_ == nil)
1188 title = nil;
1189 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1190 title = [package name];
1191 else
1192 title = package_;
1193
1194 return [self compound:title];
1195 }
1196
1197 @end
1198 /* }}} */
1199
1200 // Cytore Definitions {{{
1201 struct PackageValue :
1202 Cytore::Block
1203 {
1204 Cytore::Offset<PackageValue> next_;
1205
1206 uint32_t index_ : 23;
1207 uint32_t subscribed_ : 1;
1208 uint32_t : 8;
1209
1210 int32_t first_;
1211 int32_t last_;
1212
1213 uint16_t vhash_;
1214 uint16_t nhash_;
1215
1216 char version_[8];
1217 char name_[];
1218 };
1219
1220 struct MetaValue :
1221 Cytore::Block
1222 {
1223 uint32_t active_;
1224 Cytore::Offset<PackageValue> packages_[1 << 16];
1225 };
1226
1227 static Cytore::File<MetaValue> MetaFile_;
1228 // }}}
1229 // Cytore Helper Functions {{{
1230 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1231 SplitHash nhash = { hashlittle(name, length) };
1232
1233 PackageValue *metadata;
1234
1235 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1236 offset: if (offset->IsNull()) {
1237 *offset = MetaFile_.New<PackageValue>(length + 1);
1238 metadata = &MetaFile_.Get(*offset);
1239
1240 if (metadata == NULL) {
1241 if (fail != NULL)
1242 *fail = true;
1243
1244 metadata = new PackageValue();
1245 memset(metadata, 0, sizeof(*metadata));
1246 }
1247
1248 memcpy(metadata->name_, name, length + 1);
1249 metadata->nhash_ = nhash.u16[1];
1250 } else {
1251 metadata = &MetaFile_.Get(*offset);
1252
1253 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1254 offset = &metadata->next_;
1255 goto offset;
1256 }
1257 }
1258
1259 return metadata;
1260 }
1261
1262 static void PackageImport(const void *key, const void *value, void *context) {
1263 bool &fail(*reinterpret_cast<bool *>(context));
1264
1265 char buffer[1024];
1266 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1267 NSLog(@"failed to import package %@", key);
1268 return;
1269 }
1270
1271 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1272 NSDictionary *package((NSDictionary *) value);
1273
1274 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1275 if ([subscribed boolValue] && !metadata->subscribed_)
1276 metadata->subscribed_ = true;
1277
1278 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1279 time_t time([date timeIntervalSince1970]);
1280 if (metadata->first_ > time || metadata->first_ == 0)
1281 metadata->first_ = time;
1282 }
1283
1284 NSDate *date([package objectForKey:@"LastSeen"]);
1285 NSString *version([package objectForKey:@"LastVersion"]);
1286
1287 if (date != nil && version != nil) {
1288 time_t time([date timeIntervalSince1970]);
1289 if (metadata->last_ < time || metadata->last_ == 0)
1290 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1291 size_t length(strlen(buffer));
1292 uint16_t vhash(hashlittle(buffer, length));
1293
1294 size_t capped(std::min<size_t>(8, length));
1295 char *latest(buffer + length - capped);
1296
1297 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1298 metadata->vhash_ = vhash;
1299
1300 metadata->last_ = time;
1301 }
1302 }
1303 }
1304 // }}}
1305
1306 /* Source Class {{{ */
1307 @interface Source : NSObject {
1308 unsigned era_;
1309 Database *database_;
1310 metaIndex *index_;
1311
1312 CYString depiction_;
1313 CYString description_;
1314 CYString label_;
1315 CYString origin_;
1316 CYString support_;
1317
1318 CYString uri_;
1319 CYString distribution_;
1320 CYString type_;
1321 CYString base_;
1322 CYString version_;
1323
1324 _H<NSString> host_;
1325 _H<NSString> authority_;
1326
1327 CYString defaultIcon_;
1328
1329 _H<NSDictionary> record_;
1330 BOOL trusted_;
1331 }
1332
1333 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1334
1335 - (NSComparisonResult) compareByName:(Source *)source;
1336
1337 - (NSString *) depictionForPackage:(NSString *)package;
1338 - (NSString *) supportForPackage:(NSString *)package;
1339
1340 - (NSDictionary *) record;
1341 - (BOOL) trusted;
1342
1343 - (NSString *) rooturi;
1344 - (NSString *) distribution;
1345 - (NSString *) type;
1346
1347 - (NSString *) key;
1348 - (NSString *) host;
1349
1350 - (NSString *) name;
1351 - (NSString *) shortDescription;
1352 - (NSString *) label;
1353 - (NSString *) origin;
1354 - (NSString *) version;
1355
1356 - (NSString *) defaultIcon;
1357 - (NSURL *) iconURL;
1358
1359 @end
1360
1361 @implementation Source
1362
1363 - (void) _clear {
1364 uri_.clear();
1365 distribution_.clear();
1366 type_.clear();
1367
1368 base_.clear();
1369
1370 description_.clear();
1371 label_.clear();
1372 origin_.clear();
1373 depiction_.clear();
1374 support_.clear();
1375 version_.clear();
1376 defaultIcon_.clear();
1377
1378 record_ = nil;
1379 host_ = nil;
1380 authority_ = nil;
1381 }
1382
1383 + (NSString *) webScriptNameForSelector:(SEL)selector {
1384 if (false);
1385 else if (selector == @selector(addSection:))
1386 return @"addSection";
1387 else if (selector == @selector(getField:))
1388 return @"getField";
1389 else if (selector == @selector(removeSection:))
1390 return @"removeSection";
1391 else if (selector == @selector(remove))
1392 return @"remove";
1393 else
1394 return nil;
1395 }
1396
1397 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1398 return [self webScriptNameForSelector:selector] == nil;
1399 }
1400
1401 + (NSArray *) _attributeKeys {
1402 return [NSArray arrayWithObjects:
1403 @"baseuri",
1404 @"distribution",
1405 @"host",
1406 @"key",
1407 @"iconuri",
1408 @"label",
1409 @"name",
1410 @"origin",
1411 @"rooturi",
1412 @"sections",
1413 @"shortDescription",
1414 @"trusted",
1415 @"type",
1416 @"version",
1417 nil];
1418 }
1419
1420 - (NSArray *) attributeKeys {
1421 return [[self class] _attributeKeys];
1422 }
1423
1424 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1425 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1426 }
1427
1428 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1429 [self _clear];
1430
1431 trusted_ = index->IsTrusted();
1432
1433 uri_.set(pool, index->GetURI());
1434 distribution_.set(pool, index->GetDist());
1435 type_.set(pool, index->GetType());
1436
1437 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1438 if (dindex != NULL) {
1439 base_.set(pool, dindex->MetaIndexURI(""));
1440
1441 FileFd fd;
1442 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1443 _error->Discard();
1444 else {
1445 pkgTagFile tags(&fd);
1446
1447 pkgTagSection section;
1448 tags.Step(section);
1449
1450 struct {
1451 const char *name_;
1452 CYString *value_;
1453 } names[] = {
1454 {"default-icon", &defaultIcon_},
1455 {"depiction", &depiction_},
1456 {"description", &description_},
1457 {"label", &label_},
1458 {"origin", &origin_},
1459 {"support", &support_},
1460 {"version", &version_},
1461 };
1462
1463 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1464 const char *start, *end;
1465
1466 if (section.Find(names[i].name_, start, end)) {
1467 CYString &value(*names[i].value_);
1468 value.set(pool, start, end - start);
1469 }
1470 }
1471 }
1472 }
1473
1474 record_ = [Sources_ objectForKey:[self key]];
1475
1476 NSURL *url([NSURL URLWithString:uri_]);
1477
1478 host_ = [url host];
1479 if (host_ != nil)
1480 host_ = [host_ lowercaseString];
1481
1482 if (host_ != nil)
1483 authority_ = host_;
1484 else
1485 authority_ = [url path];
1486 }
1487
1488 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1489 if ((self = [super init]) != nil) {
1490 era_ = [database era];
1491 database_ = database;
1492 index_ = index;
1493
1494 [self setMetaIndex:index inPool:pool];
1495 } return self;
1496 }
1497
1498 - (NSString *) getField:(NSString *)name {
1499 @synchronized (database_) {
1500 if ([database_ era] != era_ || index_ == NULL)
1501 return nil;
1502
1503 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1504 if (dindex == NULL)
1505 return nil;
1506
1507 FileFd fd;
1508 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1509 _error->Discard();
1510 return nil;
1511 }
1512
1513 pkgTagFile tags(&fd);
1514
1515 pkgTagSection section;
1516 tags.Step(section);
1517
1518 const char *start, *end;
1519 if (!section.Find([name UTF8String], start, end))
1520 return (NSString *) [NSNull null];
1521
1522 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1523 } }
1524
1525 - (NSComparisonResult) compareByName:(Source *)source {
1526 NSString *lhs = [self name];
1527 NSString *rhs = [source name];
1528
1529 if ([lhs length] != 0 && [rhs length] != 0) {
1530 unichar lhc = [lhs characterAtIndex:0];
1531 unichar rhc = [rhs characterAtIndex:0];
1532
1533 if (isalpha(lhc) && !isalpha(rhc))
1534 return NSOrderedAscending;
1535 else if (!isalpha(lhc) && isalpha(rhc))
1536 return NSOrderedDescending;
1537 }
1538
1539 return [lhs compare:rhs options:LaxCompareOptions_];
1540 }
1541
1542 - (NSString *) depictionForPackage:(NSString *)package {
1543 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1544 }
1545
1546 - (NSString *) supportForPackage:(NSString *)package {
1547 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1548 }
1549
1550 - (NSArray *) sections {
1551 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1552 }
1553
1554 - (void) _addSection:(NSString *)section {
1555 if (record_ == nil)
1556 return;
1557 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1558 if (![sections containsObject:section]) {
1559 [sections addObject:section];
1560 Changed_ = true;
1561 }
1562 } else {
1563 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1564 Changed_ = true;
1565 }
1566 }
1567
1568 - (bool) addSection:(NSString *)section {
1569 if (record_ == nil)
1570 return false;
1571
1572 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1573 return true;
1574 }
1575
1576 - (void) _removeSection:(NSString *)section {
1577 if (record_ == nil)
1578 return;
1579
1580 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1581 if ([sections containsObject:section]) {
1582 [sections removeObject:section];
1583 Changed_ = true;
1584 }
1585 }
1586
1587 - (bool) removeSection:(NSString *)section {
1588 if (record_ == nil)
1589 return false;
1590
1591 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1592 return true;
1593 }
1594
1595 - (void) _remove {
1596 [Sources_ removeObjectForKey:[self key]];
1597 Changed_ = true;
1598 }
1599
1600 - (bool) remove {
1601 bool value(record_ != nil);
1602 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1603 return value;
1604 }
1605
1606 - (NSDictionary *) record {
1607 return record_;
1608 }
1609
1610 - (BOOL) trusted {
1611 return trusted_;
1612 }
1613
1614 - (NSString *) rooturi {
1615 return uri_;
1616 }
1617
1618 - (NSString *) distribution {
1619 return distribution_;
1620 }
1621
1622 - (NSString *) type {
1623 return type_;
1624 }
1625
1626 - (NSString *) baseuri {
1627 return base_.empty() ? nil : (id) base_;
1628 }
1629
1630 - (NSString *) iconuri {
1631 if (NSString *base = [self baseuri])
1632 return [base stringByAppendingString:@"CydiaIcon.png"];
1633
1634 return nil;
1635 }
1636
1637 - (NSURL *) iconURL {
1638 if (NSString *uri = [self iconuri])
1639 return [NSURL URLWithString:uri];
1640 return nil;
1641 }
1642
1643 - (NSString *) key {
1644 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1645 }
1646
1647 - (NSString *) host {
1648 return host_;
1649 }
1650
1651 - (NSString *) name {
1652 return origin_.empty() ? (id) authority_ : origin_;
1653 }
1654
1655 - (NSString *) shortDescription {
1656 return description_;
1657 }
1658
1659 - (NSString *) label {
1660 return label_.empty() ? (id) authority_ : label_;
1661 }
1662
1663 - (NSString *) origin {
1664 return origin_;
1665 }
1666
1667 - (NSString *) version {
1668 return version_;
1669 }
1670
1671 - (NSString *) defaultIcon {
1672 return defaultIcon_;
1673 }
1674
1675 @end
1676 /* }}} */
1677 /* CydiaOperation Class {{{ */
1678 @interface CydiaOperation : NSObject {
1679 _H<NSString> operator_;
1680 _H<NSString> value_;
1681 }
1682
1683 - (NSString *) operator;
1684 - (NSString *) value;
1685
1686 @end
1687
1688 @implementation CydiaOperation
1689
1690 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1691 if ((self = [super init]) != nil) {
1692 operator_ = [NSString stringWithUTF8String:_operator];
1693 value_ = [NSString stringWithUTF8String:value];
1694 } return self;
1695 }
1696
1697 + (NSArray *) _attributeKeys {
1698 return [NSArray arrayWithObjects:
1699 @"operator",
1700 @"value",
1701 nil];
1702 }
1703
1704 - (NSArray *) attributeKeys {
1705 return [[self class] _attributeKeys];
1706 }
1707
1708 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1709 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1710 }
1711
1712 - (NSString *) operator {
1713 return operator_;
1714 }
1715
1716 - (NSString *) value {
1717 return value_;
1718 }
1719
1720 @end
1721 /* }}} */
1722 /* CydiaClause Class {{{ */
1723 @interface CydiaClause : NSObject {
1724 _H<NSString> package_;
1725 _H<CydiaOperation> version_;
1726 }
1727
1728 - (NSString *) package;
1729 - (CydiaOperation *) version;
1730
1731 @end
1732
1733 @implementation CydiaClause
1734
1735 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1736 if ((self = [super init]) != nil) {
1737 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1738
1739 if (const char *version = dep.TargetVer())
1740 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1741 else
1742 version_ = (id) [NSNull null];
1743 } return self;
1744 }
1745
1746 + (NSArray *) _attributeKeys {
1747 return [NSArray arrayWithObjects:
1748 @"package",
1749 @"version",
1750 nil];
1751 }
1752
1753 - (NSArray *) attributeKeys {
1754 return [[self class] _attributeKeys];
1755 }
1756
1757 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1758 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1759 }
1760
1761 - (NSString *) package {
1762 return package_;
1763 }
1764
1765 - (CydiaOperation *) version {
1766 return version_;
1767 }
1768
1769 @end
1770 /* }}} */
1771 /* CydiaRelation Class {{{ */
1772 @interface CydiaRelation : NSObject {
1773 _H<NSString> relationship_;
1774 _H<NSMutableArray> clauses_;
1775 }
1776
1777 - (NSString *) relationship;
1778 - (NSArray *) clauses;
1779
1780 @end
1781
1782 @implementation CydiaRelation
1783
1784 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1785 if ((self = [super init]) != nil) {
1786 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1787 clauses_ = [NSMutableArray arrayWithCapacity:8];
1788
1789 pkgCache::DepIterator start;
1790 pkgCache::DepIterator end;
1791 dep.GlobOr(start, end); // ++dep
1792
1793 _forever {
1794 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1795
1796 // yes, seriously. (wtf?)
1797 if (start == end)
1798 break;
1799 ++start;
1800 }
1801 } return self;
1802 }
1803
1804 + (NSArray *) _attributeKeys {
1805 return [NSArray arrayWithObjects:
1806 @"clauses",
1807 @"relationship",
1808 nil];
1809 }
1810
1811 - (NSArray *) attributeKeys {
1812 return [[self class] _attributeKeys];
1813 }
1814
1815 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1816 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1817 }
1818
1819 - (NSString *) relationship {
1820 return relationship_;
1821 }
1822
1823 - (NSArray *) clauses {
1824 return clauses_;
1825 }
1826
1827 - (void) addClause:(CydiaClause *)clause {
1828 [clauses_ addObject:clause];
1829 }
1830
1831 @end
1832 /* }}} */
1833 /* Package Class {{{ */
1834 struct ParsedPackage {
1835 CYString md5sum_;
1836 CYString tagline_;
1837
1838 CYString architecture_;
1839 CYString icon_;
1840
1841 CYString depiction_;
1842 CYString homepage_;
1843
1844 CYString sponsor_;
1845 CYString author_;
1846
1847 CYString bugs_;
1848 CYString support_;
1849 };
1850
1851 @interface Package : NSObject {
1852 uint32_t era_ : 25;
1853 uint32_t role_ : 3;
1854 uint32_t essential_ : 1;
1855 uint32_t obsolete_ : 1;
1856 uint32_t ignored_ : 1;
1857 uint32_t pooled_ : 1;
1858
1859 apr_pool_t *pool_;
1860
1861 uint32_t rank_;
1862
1863 _transient Database *database_;
1864
1865 pkgCache::VerIterator version_;
1866 pkgCache::PkgIterator iterator_;
1867 pkgCache::VerFileIterator file_;
1868
1869 CYString id_;
1870 CYString name_;
1871
1872 CYString latest_;
1873 CYString installed_;
1874
1875 const char *section_;
1876 _transient NSString *section$_;
1877
1878 _H<Source> source_;
1879
1880 PackageValue *metadata_;
1881 ParsedPackage *parsed_;
1882
1883 _H<NSMutableArray> tags_;
1884 }
1885
1886 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1887 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1888
1889 - (pkgCache::PkgIterator) iterator;
1890 - (void) parse;
1891
1892 - (NSString *) section;
1893 - (NSString *) simpleSection;
1894
1895 - (NSString *) longSection;
1896 - (NSString *) shortSection;
1897
1898 - (NSString *) uri;
1899
1900 - (MIMEAddress *) maintainer;
1901 - (size_t) size;
1902 - (NSString *) longDescription;
1903 - (NSString *) shortDescription;
1904 - (unichar) index;
1905
1906 - (PackageValue *) metadata;
1907 - (time_t) seen;
1908
1909 - (bool) subscribed;
1910 - (bool) setSubscribed:(bool)subscribed;
1911
1912 - (BOOL) ignored;
1913
1914 - (NSString *) latest;
1915 - (NSString *) installed;
1916 - (BOOL) uninstalled;
1917
1918 - (BOOL) valid;
1919 - (BOOL) upgradableAndEssential:(BOOL)essential;
1920 - (BOOL) essential;
1921 - (BOOL) broken;
1922 - (BOOL) unfiltered;
1923 - (BOOL) visible;
1924
1925 - (BOOL) half;
1926 - (BOOL) halfConfigured;
1927 - (BOOL) halfInstalled;
1928 - (BOOL) hasMode;
1929 - (NSString *) mode;
1930
1931 - (NSString *) id;
1932 - (NSString *) name;
1933 - (UIImage *) icon;
1934 - (NSString *) homepage;
1935 - (NSString *) depiction;
1936 - (MIMEAddress *) author;
1937
1938 - (NSString *) support;
1939
1940 - (NSArray *) files;
1941 - (NSArray *) warnings;
1942 - (NSArray *) applications;
1943
1944 - (Source *) source;
1945
1946 - (uint32_t) rank;
1947 - (BOOL) matches:(NSArray *)query;
1948
1949 - (bool) hasSupportingRole;
1950 - (BOOL) hasTag:(NSString *)tag;
1951 - (NSString *) primaryPurpose;
1952 - (NSArray *) purposes;
1953 - (bool) isCommercial;
1954
1955 - (void) setIndex:(size_t)index;
1956
1957 - (CYString &) cyname;
1958
1959 - (uint32_t) compareBySection:(NSArray *)sections;
1960
1961 - (void) install;
1962 - (void) remove;
1963
1964 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1965 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1966 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1967 - (bool) isVisibleInSection:(NSString *)section;
1968 - (bool) isVisibleInSource:(Source *)source;
1969
1970 @end
1971
1972 uint32_t PackageChangesRadix(Package *self, void *) {
1973 union {
1974 uint32_t key;
1975
1976 struct {
1977 uint32_t timestamp : 30;
1978 uint32_t ignored : 1;
1979 uint32_t upgradable : 1;
1980 } bits;
1981 } value;
1982
1983 bool upgradable([self upgradableAndEssential:YES]);
1984 value.bits.upgradable = upgradable ? 1 : 0;
1985
1986 if (upgradable) {
1987 value.bits.timestamp = 0;
1988 value.bits.ignored = [self ignored] ? 0 : 1;
1989 value.bits.upgradable = 1;
1990 } else {
1991 value.bits.timestamp = [self seen] >> 2;
1992 value.bits.ignored = 0;
1993 value.bits.upgradable = 0;
1994 }
1995
1996 return _not(uint32_t) - value.key;
1997 }
1998
1999 uint32_t PackagePrefixRadix(Package *self, void *context) {
2000 size_t offset(reinterpret_cast<size_t>(context));
2001 CYString &name([self cyname]);
2002
2003 size_t size(name.size());
2004 if (size == 0)
2005 return 0;
2006 char *text(name.data());
2007
2008 size_t zeros;
2009 if (!isdigit(text[0]))
2010 zeros = 0;
2011 else {
2012 size_t digits(1);
2013 while (size != digits && isdigit(text[digits]))
2014 if (++digits == 4)
2015 break;
2016 zeros = 4 - digits;
2017 }
2018
2019 uint8_t data[4];
2020
2021 if (offset == 0 && zeros != 0) {
2022 memset(data, '0', zeros);
2023 memcpy(data + zeros, text, 4 - zeros);
2024 } else {
2025 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2026 if (size <= offset - zeros)
2027 return 0;
2028
2029 text += offset - zeros;
2030 size -= offset - zeros;
2031
2032 if (size >= 4)
2033 memcpy(data, text, 4);
2034 else {
2035 memcpy(data, text, size);
2036 memset(data + size, 0, 4 - size);
2037 }
2038
2039 for (size_t i(0); i != 4; ++i)
2040 if (isalpha(data[i]))
2041 data[i] |= 0x20;
2042 }
2043
2044 if (offset == 0)
2045 if (data[0] == '@')
2046 data[0] = 0x7f;
2047 else
2048 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2049
2050 /* XXX: ntohl may be more honest */
2051 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2052 }
2053
2054 CYString &(*PackageName)(Package *self, SEL sel);
2055
2056 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2057 _profile(PackageNameCompare)
2058 CYString &lhi(PackageName(lhs, @selector(cyname)));
2059 CYString &rhi(PackageName(rhs, @selector(cyname)));
2060 CFStringRef lhn(lhi), rhn(rhi);
2061
2062 if (lhn == NULL)
2063 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2064 else if (rhn == NULL)
2065 return NSOrderedDescending;
2066
2067 _profile(PackageNameCompare$NumbersLast)
2068 if (!lhi.empty() && !rhi.empty()) {
2069 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2070 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2071 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2072 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2073 return lha ? NSOrderedAscending : NSOrderedDescending;
2074 }
2075 _end
2076
2077 CFIndex length = CFStringGetLength(lhn);
2078
2079 _profile(PackageNameCompare$Compare)
2080 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2081 _end
2082 _end
2083 }
2084
2085 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2086 return PackageNameCompare(*lhs, *rhs, context);
2087 }
2088
2089 struct PackageNameOrdering :
2090 std::binary_function<Package *, Package *, bool>
2091 {
2092 _finline bool operator ()(Package *lhs, Package *rhs) const {
2093 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2094 }
2095 };
2096
2097 @implementation Package
2098
2099 - (NSString *) description {
2100 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2101 }
2102
2103 - (void) dealloc {
2104 if (!pooled_)
2105 apr_pool_destroy(pool_);
2106 if (parsed_ != NULL)
2107 delete parsed_;
2108 [super dealloc];
2109 }
2110
2111 + (NSString *) webScriptNameForSelector:(SEL)selector {
2112 if (false);
2113 else if (selector == @selector(clear))
2114 return @"clear";
2115 else if (selector == @selector(getField:))
2116 return @"getField";
2117 else if (selector == @selector(hasTag:))
2118 return @"hasTag";
2119 else if (selector == @selector(install))
2120 return @"install";
2121 else if (selector == @selector(remove))
2122 return @"remove";
2123 else
2124 return nil;
2125 }
2126
2127 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2128 return [self webScriptNameForSelector:selector] == nil;
2129 }
2130
2131 + (NSArray *) _attributeKeys {
2132 return [NSArray arrayWithObjects:
2133 @"applications",
2134 @"architecture",
2135 @"author",
2136 @"depiction",
2137 @"essential",
2138 @"homepage",
2139 @"icon",
2140 @"id",
2141 @"installed",
2142 @"latest",
2143 @"longDescription",
2144 @"longSection",
2145 @"maintainer",
2146 @"md5sum",
2147 @"mode",
2148 @"name",
2149 @"purposes",
2150 @"relations",
2151 @"section",
2152 @"selection",
2153 @"shortDescription",
2154 @"shortSection",
2155 @"simpleSection",
2156 @"size",
2157 @"source",
2158 @"sponsor",
2159 @"state",
2160 @"support",
2161 @"tags",
2162 @"warnings",
2163 nil];
2164 }
2165
2166 - (NSArray *) attributeKeys {
2167 return [[self class] _attributeKeys];
2168 }
2169
2170 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2171 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2172 }
2173
2174 - (NSArray *) relations {
2175 @synchronized (database_) {
2176 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2177 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2178 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2179 return relations;
2180 } }
2181
2182 - (NSString *) architecture {
2183 [self parse];
2184 @synchronized (database_) {
2185 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2186 } }
2187
2188 - (NSString *) getField:(NSString *)name {
2189 @synchronized (database_) {
2190 if ([database_ era] != era_ || file_.end())
2191 return nil;
2192
2193 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2194
2195 const char *start, *end;
2196 if (!parser.Find([name UTF8String], start, end))
2197 return (NSString *) [NSNull null];
2198
2199 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2200 } }
2201
2202 - (void) parse {
2203 if (parsed_ != NULL)
2204 return;
2205 @synchronized (database_) {
2206 if ([database_ era] != era_ || file_.end())
2207 return;
2208
2209 ParsedPackage *parsed(new ParsedPackage);
2210 parsed_ = parsed;
2211
2212 _profile(Package$parse)
2213 pkgRecords::Parser *parser;
2214
2215 _profile(Package$parse$Lookup)
2216 parser = &[database_ records]->Lookup(file_);
2217 _end
2218
2219 CYString website;
2220
2221 _profile(Package$parse$Find)
2222 struct {
2223 const char *name_;
2224 CYString *value_;
2225 } names[] = {
2226 {"architecture", &parsed->architecture_},
2227 {"icon", &parsed->icon_},
2228 {"depiction", &parsed->depiction_},
2229 {"homepage", &parsed->homepage_},
2230 {"website", &website},
2231 {"bugs", &parsed->bugs_},
2232 {"support", &parsed->support_},
2233 {"sponsor", &parsed->sponsor_},
2234 {"author", &parsed->author_},
2235 {"md5sum", &parsed->md5sum_},
2236 };
2237
2238 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2239 const char *start, *end;
2240
2241 if (parser->Find(names[i].name_, start, end)) {
2242 CYString &value(*names[i].value_);
2243 _profile(Package$parse$Value)
2244 value.set(pool_, start, end - start);
2245 _end
2246 }
2247 }
2248 _end
2249
2250 _profile(Package$parse$Tagline)
2251 const char *start, *end;
2252 if (parser->ShortDesc(start, end)) {
2253 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2254 if (stop == NULL)
2255 stop = end;
2256 while (stop != start && stop[-1] == '\r')
2257 --stop;
2258 parsed->tagline_.set(pool_, start, stop - start);
2259 }
2260 _end
2261
2262 _profile(Package$parse$Retain)
2263 if (parsed->homepage_.empty())
2264 parsed->homepage_ = website;
2265 if (parsed->homepage_ == parsed->depiction_)
2266 parsed->homepage_.clear();
2267 _end
2268 _end
2269 } }
2270
2271 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2272 if ((self = [super init]) != nil) {
2273 _profile(Package$initWithVersion)
2274 if (pool == NULL)
2275 apr_pool_create(&pool_, NULL);
2276 else {
2277 pool_ = pool;
2278 pooled_ = true;
2279 }
2280
2281 database_ = database;
2282 era_ = [database era];
2283
2284 version_ = version;
2285
2286 pkgCache::PkgIterator iterator(version.ParentPkg());
2287 iterator_ = iterator;
2288
2289 _profile(Package$initWithVersion$Version)
2290 if (!version_.end())
2291 file_ = version_.FileList();
2292 else {
2293 pkgCache &cache([database_ cache]);
2294 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2295 }
2296 _end
2297
2298 _profile(Package$initWithVersion$Cache)
2299 name_.set(NULL, iterator.Display());
2300
2301 latest_.set(NULL, StripVersion_(version_.VerStr()));
2302
2303 pkgCache::VerIterator current(iterator.CurrentVer());
2304 if (!current.end())
2305 installed_.set(NULL, StripVersion_(current.VerStr()));
2306 _end
2307
2308 _profile(Package$initWithVersion$Tags)
2309 pkgCache::TagIterator tag(iterator.TagList());
2310 if (!tag.end()) {
2311 tags_ = [NSMutableArray arrayWithCapacity:8];
2312 do {
2313 const char *name(tag.Name());
2314 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2315
2316 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2317 if (strcmp(name + 6, "enduser") == 0)
2318 role_ = 1;
2319 else if (strcmp(name + 6, "hacker") == 0)
2320 role_ = 2;
2321 else if (strcmp(name + 6, "developer") == 0)
2322 role_ = 3;
2323 else if (strcmp(name + 6, "cydia") == 0)
2324 role_ = 7;
2325 else
2326 role_ = 4;
2327 }
2328
2329 if (strncmp(name, "cydia::", 7) == 0) {
2330 if (strcmp(name + 7, "essential") == 0)
2331 essential_ = true;
2332 else if (strcmp(name + 7, "obsolete") == 0)
2333 obsolete_ = true;
2334 }
2335
2336 ++tag;
2337 } while (!tag.end());
2338 }
2339 _end
2340
2341 _profile(Package$initWithVersion$Metadata)
2342 const char *mixed(iterator.Name());
2343 size_t size(strlen(mixed));
2344 char lower[size + 1];
2345
2346 for (size_t i(0); i != size; ++i)
2347 lower[i] = mixed[i] | 0x20;
2348 lower[size] = '\0';
2349
2350 PackageValue *metadata(PackageFind(lower, size));
2351 metadata_ = metadata;
2352
2353 id_.set(NULL, metadata->name_, size);
2354
2355 const char *latest(version_.VerStr());
2356 size_t length(strlen(latest));
2357
2358 uint16_t vhash(hashlittle(latest, length));
2359
2360 size_t capped(std::min<size_t>(8, length));
2361 latest = latest + length - capped;
2362
2363 if (metadata->first_ == 0)
2364 metadata->first_ = now_;
2365
2366 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2367 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2368 metadata->vhash_ = vhash;
2369 metadata->last_ = now_;
2370 } else if (metadata->last_ == 0)
2371 metadata->last_ = metadata->first_;
2372 _end
2373
2374 _profile(Package$initWithVersion$Section)
2375 section_ = iterator.Section();
2376 _end
2377
2378 _profile(Package$initWithVersion$Flags)
2379 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2380 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2381 _end
2382 _end } return self;
2383 }
2384
2385 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2386 pkgCache::VerIterator version;
2387
2388 _profile(Package$packageWithIterator$GetCandidateVer)
2389 version = [database policy]->GetCandidateVer(iterator);
2390 _end
2391
2392 if (version.end())
2393 return nil;
2394
2395 Package *package;
2396
2397 _profile(Package$packageWithIterator$Allocate)
2398 package = [Package allocWithZone:zone];
2399 _end
2400
2401 _profile(Package$packageWithIterator$Initialize)
2402 package = [package
2403 initWithVersion:version
2404 withZone:zone
2405 inPool:pool
2406 database:database
2407 ];
2408 _end
2409
2410 _profile(Package$packageWithIterator$Autorelease)
2411 package = [package autorelease];
2412 _end
2413
2414 return package;
2415 }
2416
2417 - (pkgCache::PkgIterator) iterator {
2418 return iterator_;
2419 }
2420
2421 - (NSString *) section {
2422 if (section$_ == nil) {
2423 if (section_ == NULL)
2424 return nil;
2425
2426 _profile(Package$section$mappedSectionForPointer)
2427 section$_ = [database_ mappedSectionForPointer:section_];
2428 _end
2429 } return section$_;
2430 }
2431
2432 - (NSString *) simpleSection {
2433 if (NSString *section = [self section])
2434 return Simplify(section);
2435 else
2436 return nil;
2437 }
2438
2439 - (NSString *) longSection {
2440 return LocalizeSection([self section]);
2441 }
2442
2443 - (NSString *) shortSection {
2444 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2445 }
2446
2447 - (NSString *) uri {
2448 return nil;
2449 #if 0
2450 pkgIndexFile *index;
2451 pkgCache::PkgFileIterator file(file_.File());
2452 if (![database_ list].FindIndex(file, index))
2453 return nil;
2454 return [NSString stringWithUTF8String:iterator_->Path];
2455 //return [NSString stringWithUTF8String:file.Site()];
2456 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2457 #endif
2458 }
2459
2460 - (MIMEAddress *) maintainer {
2461 @synchronized (database_) {
2462 if ([database_ era] != era_ || file_.end())
2463 return nil;
2464
2465 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2466 const std::string &maintainer(parser->Maintainer());
2467 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2468 } }
2469
2470 - (NSString *) md5sum {
2471 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2472 }
2473
2474 - (size_t) size {
2475 @synchronized (database_) {
2476 if ([database_ era] != era_ || version_.end())
2477 return 0;
2478
2479 return version_->InstalledSize;
2480 } }
2481
2482 - (NSString *) longDescription {
2483 @synchronized (database_) {
2484 if ([database_ era] != era_ || file_.end())
2485 return nil;
2486
2487 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2488 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2489
2490 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2491 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2492 if ([lines count] < 2)
2493 return nil;
2494
2495 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2496 for (size_t i(1), e([lines count]); i != e; ++i) {
2497 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2498 [trimmed addObject:trim];
2499 }
2500
2501 return [trimmed componentsJoinedByString:@"\n"];
2502 } }
2503
2504 - (NSString *) shortDescription {
2505 if (parsed_ != NULL)
2506 return static_cast<NSString *>(parsed_->tagline_);
2507
2508 @synchronized (database_) {
2509 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2510
2511 const char *start, *end;
2512 if (!parser.ShortDesc(start, end))
2513 return nil;
2514
2515 if (end - start > 200)
2516 end = start + 200;
2517
2518 /*
2519 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2520 end = stop;
2521
2522 while (end != start && end[-1] == '\r')
2523 --end;
2524 */
2525
2526 return [(id) CYStringCreate(start, end - start) autorelease];
2527 } }
2528
2529 - (unichar) index {
2530 _profile(Package$index)
2531 CFStringRef name((CFStringRef) [self name]);
2532 if (CFStringGetLength(name) == 0)
2533 return '#';
2534 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2535 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2536 return '#';
2537 return toupper(character);
2538 _end
2539 }
2540
2541 - (PackageValue *) metadata {
2542 return metadata_;
2543 }
2544
2545 - (time_t) seen {
2546 PackageValue *metadata([self metadata]);
2547 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2548 }
2549
2550 - (bool) subscribed {
2551 return [self metadata]->subscribed_;
2552 }
2553
2554 - (bool) setSubscribed:(bool)subscribed {
2555 PackageValue *metadata([self metadata]);
2556 if (metadata->subscribed_ == subscribed)
2557 return false;
2558 metadata->subscribed_ = subscribed;
2559 return true;
2560 }
2561
2562 - (BOOL) ignored {
2563 return ignored_;
2564 }
2565
2566 - (NSString *) latest {
2567 return latest_;
2568 }
2569
2570 - (NSString *) installed {
2571 return installed_;
2572 }
2573
2574 - (BOOL) uninstalled {
2575 return installed_.empty();
2576 }
2577
2578 - (BOOL) valid {
2579 return !version_.end();
2580 }
2581
2582 - (BOOL) upgradableAndEssential:(BOOL)essential {
2583 _profile(Package$upgradableAndEssential)
2584 pkgCache::VerIterator current(iterator_.CurrentVer());
2585 if (current.end())
2586 return essential && essential_;
2587 else
2588 return !version_.end() && version_ != current;
2589 _end
2590 }
2591
2592 - (BOOL) essential {
2593 return essential_;
2594 }
2595
2596 - (BOOL) broken {
2597 return [database_ cache][iterator_].InstBroken();
2598 }
2599
2600 - (BOOL) unfiltered {
2601 _profile(Package$unfiltered$obsolete)
2602 if (_unlikely(obsolete_))
2603 return false;
2604 _end
2605
2606 _profile(Package$unfiltered$hasSupportingRole)
2607 if (_unlikely(![self hasSupportingRole]))
2608 return false;
2609 _end
2610
2611 return true;
2612 }
2613
2614 - (BOOL) visible {
2615 if (![self unfiltered])
2616 return false;
2617
2618 NSString *section;
2619
2620 _profile(Package$visible$section)
2621 section = [self section];
2622 _end
2623
2624 _profile(Package$visible$isSectionVisible)
2625 if (!isSectionVisible(section))
2626 return false;
2627 _end
2628
2629 return true;
2630 }
2631
2632 - (BOOL) half {
2633 unsigned char current(iterator_->CurrentState);
2634 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2635 }
2636
2637 - (BOOL) halfConfigured {
2638 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2639 }
2640
2641 - (BOOL) halfInstalled {
2642 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2643 }
2644
2645 - (BOOL) hasMode {
2646 @synchronized (database_) {
2647 if ([database_ era] != era_ || iterator_.end())
2648 return nil;
2649
2650 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2651 return state.Mode != pkgDepCache::ModeKeep;
2652 } }
2653
2654 - (NSString *) mode {
2655 @synchronized (database_) {
2656 if ([database_ era] != era_ || iterator_.end())
2657 return nil;
2658
2659 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2660
2661 switch (state.Mode) {
2662 case pkgDepCache::ModeDelete:
2663 if ((state.iFlags & pkgDepCache::Purge) != 0)
2664 return @"PURGE";
2665 else
2666 return @"REMOVE";
2667 case pkgDepCache::ModeKeep:
2668 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2669 return @"REINSTALL";
2670 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2671 return nil;*/
2672 else
2673 return nil;
2674 case pkgDepCache::ModeInstall:
2675 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2676 return @"REINSTALL";
2677 else*/ switch (state.Status) {
2678 case -1:
2679 return @"DOWNGRADE";
2680 case 0:
2681 return @"INSTALL";
2682 case 1:
2683 return @"UPGRADE";
2684 case 2:
2685 return @"NEW_INSTALL";
2686 _nodefault
2687 }
2688 _nodefault
2689 }
2690 } }
2691
2692 - (NSString *) id {
2693 return id_;
2694 }
2695
2696 - (NSString *) name {
2697 return name_.empty() ? id_ : name_;
2698 }
2699
2700 - (UIImage *) icon {
2701 NSString *section = [self simpleSection];
2702
2703 UIImage *icon(nil);
2704 if (parsed_ != NULL)
2705 if (NSString *href = parsed_->icon_)
2706 if ([href hasPrefix:@"file:///"])
2707 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2708 if (icon == nil) if (section != nil)
2709 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2710 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2711 if ([dicon hasPrefix:@"file:///"])
2712 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2713 if (icon == nil)
2714 icon = [UIImage applicationImageNamed:@"unknown.png"];
2715 return icon;
2716 }
2717
2718 - (NSString *) homepage {
2719 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2720 }
2721
2722 - (NSString *) depiction {
2723 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2724 }
2725
2726 - (MIMEAddress *) sponsor {
2727 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2728 }
2729
2730 - (MIMEAddress *) author {
2731 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2732 }
2733
2734 - (NSString *) support {
2735 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2736 }
2737
2738 - (NSArray *) files {
2739 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2740 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2741
2742 std::ifstream fin;
2743 fin.open([path UTF8String]);
2744 if (!fin.is_open())
2745 return nil;
2746
2747 std::string line;
2748 while (std::getline(fin, line))
2749 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2750
2751 return files;
2752 }
2753
2754 - (NSString *) state {
2755 @synchronized (database_) {
2756 if ([database_ era] != era_ || file_.end())
2757 return nil;
2758
2759 switch (iterator_->CurrentState) {
2760 case pkgCache::State::NotInstalled:
2761 return @"NotInstalled";
2762 case pkgCache::State::UnPacked:
2763 return @"UnPacked";
2764 case pkgCache::State::HalfConfigured:
2765 return @"HalfConfigured";
2766 case pkgCache::State::HalfInstalled:
2767 return @"HalfInstalled";
2768 case pkgCache::State::ConfigFiles:
2769 return @"ConfigFiles";
2770 case pkgCache::State::Installed:
2771 return @"Installed";
2772 case pkgCache::State::TriggersAwaited:
2773 return @"TriggersAwaited";
2774 case pkgCache::State::TriggersPending:
2775 return @"TriggersPending";
2776 }
2777
2778 return (NSString *) [NSNull null];
2779 } }
2780
2781 - (NSString *) selection {
2782 @synchronized (database_) {
2783 if ([database_ era] != era_ || file_.end())
2784 return nil;
2785
2786 switch (iterator_->SelectedState) {
2787 case pkgCache::State::Unknown:
2788 return @"Unknown";
2789 case pkgCache::State::Install:
2790 return @"Install";
2791 case pkgCache::State::Hold:
2792 return @"Hold";
2793 case pkgCache::State::DeInstall:
2794 return @"DeInstall";
2795 case pkgCache::State::Purge:
2796 return @"Purge";
2797 }
2798
2799 return (NSString *) [NSNull null];
2800 } }
2801
2802 - (NSArray *) warnings {
2803 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2804 const char *name(iterator_.Name());
2805
2806 size_t length(strlen(name));
2807 if (length < 2) invalid:
2808 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2809 else for (size_t i(0); i != length; ++i)
2810 if (
2811 /* XXX: technically this is not allowed */
2812 (name[i] < 'A' || name[i] > 'Z') &&
2813 (name[i] < 'a' || name[i] > 'z') &&
2814 (name[i] < '0' || name[i] > '9') &&
2815 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2816 ) goto invalid;
2817
2818 if (strcmp(name, "cydia") != 0) {
2819 bool cydia = false;
2820 bool user = false;
2821 bool _private = false;
2822 bool stash = false;
2823
2824 bool repository = [[self section] isEqualToString:@"Repositories"];
2825
2826 if (NSArray *files = [self files])
2827 for (NSString *file in files)
2828 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2829 cydia = true;
2830 else if (!user && [file isEqualToString:@"/User"])
2831 user = true;
2832 else if (!_private && [file isEqualToString:@"/private"])
2833 _private = true;
2834 else if (!stash && [file isEqualToString:@"/var/stash"])
2835 stash = true;
2836
2837 /* XXX: this is not sensitive enough. only some folders are valid. */
2838 if (cydia && !repository)
2839 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2840 if (user)
2841 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2842 if (_private)
2843 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2844 if (stash)
2845 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2846 }
2847
2848 return [warnings count] == 0 ? nil : warnings;
2849 }
2850
2851 - (NSArray *) applications {
2852 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2853
2854 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2855
2856 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2857 if (NSArray *files = [self files])
2858 for (NSString *file in files)
2859 if (application_r(file)) {
2860 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2861 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2862 if ([id isEqualToString:me])
2863 continue;
2864
2865 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2866 if (display == nil)
2867 display = application_r[1];
2868
2869 NSString *bundle([file stringByDeletingLastPathComponent]);
2870 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2871 if (icon == nil || [icon length] == 0)
2872 icon = @"icon.png";
2873 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2874
2875 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2876 [applications addObject:application];
2877
2878 [application addObject:id];
2879 [application addObject:display];
2880 [application addObject:url];
2881 }
2882
2883 return [applications count] == 0 ? nil : applications;
2884 }
2885
2886 - (Source *) source {
2887 if (source_ == nil) {
2888 @synchronized (database_) {
2889 if ([database_ era] != era_ || file_.end())
2890 source_ = (Source *) [NSNull null];
2891 else
2892 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2893 }
2894 }
2895
2896 return source_ == (Source *) [NSNull null] ? nil : source_;
2897 }
2898
2899 - (uint32_t) rank {
2900 return rank_;
2901 }
2902
2903 - (BOOL) matches:(NSArray *)query {
2904 if (query == nil || [query count] == 0)
2905 return NO;
2906
2907 rank_ = 0;
2908
2909 NSString *string;
2910 NSRange range;
2911 NSUInteger length;
2912
2913 string = [self name];
2914 length = [string length];
2915
2916 for (NSString *term in query) {
2917 range = [string rangeOfString:term options:MatchCompareOptions_];
2918 if (range.location != NSNotFound)
2919 rank_ -= 6 * 1000000 / length;
2920 }
2921
2922 if (rank_ == 0) {
2923 string = [self id];
2924 length = [string length];
2925
2926 for (NSString *term in query) {
2927 range = [string rangeOfString:term options:MatchCompareOptions_];
2928 if (range.location != NSNotFound)
2929 rank_ -= 6 * 1000000 / length;
2930 }
2931 }
2932
2933 string = [self shortDescription];
2934 length = [string length];
2935 NSUInteger stop(std::min<NSUInteger>(length, 200));
2936
2937 for (NSString *term in query) {
2938 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2939 if (range.location != NSNotFound)
2940 rank_ -= 2 * 100000;
2941 }
2942
2943 return rank_ != 0;
2944 }
2945
2946 - (bool) hasSupportingRole {
2947 if (role_ == 0)
2948 return true;
2949 if (role_ == 1)
2950 return true;
2951 if ([Role_ isEqualToString:@"User"])
2952 return false;
2953 if (role_ == 2)
2954 return true;
2955 if ([Role_ isEqualToString:@"Hacker"])
2956 return false;
2957 if (role_ == 3)
2958 return true;
2959 if ([Role_ isEqualToString:@"Developer"])
2960 return false;
2961 _assert(false);
2962 }
2963
2964 - (NSArray *) tags {
2965 return tags_;
2966 }
2967
2968 - (BOOL) hasTag:(NSString *)tag {
2969 return tags_ == nil ? NO : [tags_ containsObject:tag];
2970 }
2971
2972 - (NSString *) primaryPurpose {
2973 for (NSString *tag in (NSArray *) tags_)
2974 if ([tag hasPrefix:@"purpose::"])
2975 return [tag substringFromIndex:9];
2976 return nil;
2977 }
2978
2979 - (NSArray *) purposes {
2980 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2981 for (NSString *tag in (NSArray *) tags_)
2982 if ([tag hasPrefix:@"purpose::"])
2983 [purposes addObject:[tag substringFromIndex:9]];
2984 return [purposes count] == 0 ? nil : purposes;
2985 }
2986
2987 - (bool) isCommercial {
2988 return [self hasTag:@"cydia::commercial"];
2989 }
2990
2991 - (void) setIndex:(size_t)index {
2992 if (metadata_->index_ != index)
2993 metadata_->index_ = index;
2994 }
2995
2996 - (CYString &) cyname {
2997 return name_.empty() ? id_ : name_;
2998 }
2999
3000 - (uint32_t) compareBySection:(NSArray *)sections {
3001 NSString *section([self section]);
3002 for (size_t i(0), e([sections count]); i != e; ++i) {
3003 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3004 return i;
3005 }
3006
3007 return _not(uint32_t);
3008 }
3009
3010 - (void) clear {
3011 @synchronized (database_) {
3012 pkgProblemResolver *resolver = [database_ resolver];
3013 resolver->Clear(iterator_);
3014
3015 pkgCacheFile &cache([database_ cache]);
3016 cache->SetReInstall(iterator_, false);
3017 cache->MarkKeep(iterator_, false);
3018 } }
3019
3020 - (void) install {
3021 @synchronized (database_) {
3022 pkgProblemResolver *resolver = [database_ resolver];
3023 resolver->Clear(iterator_);
3024 resolver->Protect(iterator_);
3025
3026 pkgCacheFile &cache([database_ cache]);
3027 cache->SetReInstall(iterator_, false);
3028 cache->MarkInstall(iterator_, false);
3029
3030 pkgDepCache::StateCache &state((*cache)[iterator_]);
3031 if (!state.Install())
3032 cache->SetReInstall(iterator_, true);
3033 } }
3034
3035 - (void) remove {
3036 @synchronized (database_) {
3037 pkgProblemResolver *resolver = [database_ resolver];
3038 resolver->Clear(iterator_);
3039 resolver->Remove(iterator_);
3040 resolver->Protect(iterator_);
3041
3042 pkgCacheFile &cache([database_ cache]);
3043 cache->SetReInstall(iterator_, false);
3044 cache->MarkDelete(iterator_, true);
3045 } }
3046
3047 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3048 _profile(Package$isUnfilteredAndSearchedForBy)
3049 bool value(true);
3050
3051 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3052 value &= [self unfiltered];
3053 _end
3054
3055 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3056 value &= [self matches:query];
3057 _end
3058
3059 return value;
3060 _end
3061 }
3062
3063 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3064 if ([search length] == 0)
3065 return false;
3066
3067 _profile(Package$isUnfilteredAndSelectedForBy)
3068 bool value(true);
3069
3070 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3071 value &= [self unfiltered];
3072 _end
3073
3074 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3075 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3076 _end
3077
3078 return value;
3079 _end
3080 }
3081
3082 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3083 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3084 }
3085
3086 - (bool) isVisibleInSection:(NSString *)name {
3087 NSString *section([self section]);
3088
3089 return (
3090 name == nil ||
3091 section == nil && [name length] == 0 ||
3092 [name isEqualToString:section]
3093 ) && [self visible];
3094 }
3095
3096 - (bool) isVisibleInSource:(Source *)source {
3097 return [self source] == source && [self visible];
3098 }
3099
3100 @end
3101 /* }}} */
3102 /* Section Class {{{ */
3103 @interface Section : NSObject {
3104 _H<NSString> name_;
3105 unichar index_;
3106 size_t row_;
3107 size_t count_;
3108 _H<NSString> localized_;
3109 }
3110
3111 - (NSComparisonResult) compareByLocalized:(Section *)section;
3112 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3113 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3114 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3115 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3116 - (NSString *) name;
3117 - (unichar) index;
3118
3119 - (size_t) row;
3120 - (size_t) count;
3121
3122 - (void) addToRow;
3123 - (void) addToCount;
3124
3125 - (void) setCount:(size_t)count;
3126 - (NSString *) localized;
3127
3128 @end
3129
3130 @implementation Section
3131
3132 - (NSComparisonResult) compareByLocalized:(Section *)section {
3133 NSString *lhs(localized_);
3134 NSString *rhs([section localized]);
3135
3136 /*if ([lhs length] != 0 && [rhs length] != 0) {
3137 unichar lhc = [lhs characterAtIndex:0];
3138 unichar rhc = [rhs characterAtIndex:0];
3139
3140 if (isalpha(lhc) && !isalpha(rhc))
3141 return NSOrderedAscending;
3142 else if (!isalpha(lhc) && isalpha(rhc))
3143 return NSOrderedDescending;
3144 }*/
3145
3146 return [lhs compare:rhs options:LaxCompareOptions_];
3147 }
3148
3149 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3150 if ((self = [self initWithName:name localize:NO]) != nil) {
3151 if (localized != nil)
3152 localized_ = localized;
3153 } return self;
3154 }
3155
3156 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3157 return [self initWithName:name row:0 localize:localize];
3158 }
3159
3160 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3161 if ((self = [super init]) != nil) {
3162 name_ = name;
3163 index_ = '\0';
3164 row_ = row;
3165 if (localize)
3166 localized_ = LocalizeSection(name_);
3167 } return self;
3168 }
3169
3170 /* XXX: localize the index thingees */
3171 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3172 if ((self = [super init]) != nil) {
3173 name_ = [NSString stringWithCharacters:&index length:1];
3174 index_ = index;
3175 row_ = row;
3176 } return self;
3177 }
3178
3179 - (NSString *) name {
3180 return name_;
3181 }
3182
3183 - (unichar) index {
3184 return index_;
3185 }
3186
3187 - (size_t) row {
3188 return row_;
3189 }
3190
3191 - (size_t) count {
3192 return count_;
3193 }
3194
3195 - (void) addToRow {
3196 ++row_;
3197 }
3198
3199 - (void) addToCount {
3200 ++count_;
3201 }
3202
3203 - (void) setCount:(size_t)count {
3204 count_ = count;
3205 }
3206
3207 - (NSString *) localized {
3208 return localized_;
3209 }
3210
3211 @end
3212 /* }}} */
3213
3214 class CydiaLogCleaner :
3215 public pkgArchiveCleaner
3216 {
3217 protected:
3218 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3219 unlink(File);
3220 }
3221 };
3222
3223 /* Database Implementation {{{ */
3224 @implementation Database
3225
3226 + (Database *) sharedInstance {
3227 static _H<Database> instance;
3228 if (instance == nil)
3229 instance = [[[Database alloc] init] autorelease];
3230 return instance;
3231 }
3232
3233 - (unsigned) era {
3234 return era_;
3235 }
3236
3237 - (void) releasePackages {
3238 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3239 CFArrayRemoveAllValues(packages_);
3240 }
3241
3242 - (void) dealloc {
3243 // XXX: actually implement this thing
3244 _assert(false);
3245 [self releasePackages];
3246 apr_pool_destroy(pool_);
3247 NSRecycleZone(zone_);
3248 [super dealloc];
3249 }
3250
3251 - (void) _readCydia:(NSNumber *)fd {
3252 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3253 std::istream is(&ib);
3254 std::string line;
3255
3256 static Pcre finish_r("^finish:([^:]*)$");
3257
3258 while (std::getline(is, line)) {
3259 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3260
3261 const char *data(line.c_str());
3262 size_t size = line.size();
3263 lprintf("C:%s\n", data);
3264
3265 if (finish_r(data, size)) {
3266 NSString *finish = finish_r[1];
3267 int index = [Finishes_ indexOfObject:finish];
3268 if (index != INT_MAX && index > Finish_)
3269 Finish_ = index;
3270 }
3271
3272 [pool release];
3273 }
3274
3275 _assume(false);
3276 }
3277
3278 - (void) _readStatus:(NSNumber *)fd {
3279 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3280 std::istream is(&ib);
3281 std::string line;
3282
3283 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3284 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3285
3286 while (std::getline(is, line)) {
3287 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3288
3289 const char *data(line.c_str());
3290 size_t size(line.size());
3291 lprintf("S:%s\n", data);
3292
3293 if (conffile_r(data, size)) {
3294 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3295 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3296 } else if (strncmp(data, "status: ", 8) == 0) {
3297 // status: <package>: {unpacked,half-configured,installed}
3298 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3299 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3300 } else if (strncmp(data, "processing: ", 12) == 0) {
3301 // processing: configure: config-test
3302 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3303 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3304 } else if (pmstatus_r(data, size)) {
3305 std::string type([pmstatus_r[1] UTF8String]);
3306
3307 NSString *package = pmstatus_r[2];
3308 if ([package isEqualToString:@"dpkg-exec"])
3309 package = nil;
3310
3311 float percent([pmstatus_r[3] floatValue]);
3312 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3313
3314 NSString *string = pmstatus_r[4];
3315
3316 if (type == "pmerror") {
3317 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3318 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3319 } else if (type == "pmstatus") {
3320 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3321 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3322 } else if (type == "pmconffile")
3323 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3324 else
3325 lprintf("E:unknown pmstatus\n");
3326 } else
3327 lprintf("E:unknown status\n");
3328
3329 [pool release];
3330 }
3331
3332 _assume(false);
3333 }
3334
3335 - (void) _readOutput:(NSNumber *)fd {
3336 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3337 std::istream is(&ib);
3338 std::string line;
3339
3340 while (std::getline(is, line)) {
3341 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3342
3343 lprintf("O:%s\n", line.c_str());
3344
3345 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3346 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3347
3348 [pool release];
3349 }
3350
3351 _assume(false);
3352 }
3353
3354 - (FILE *) input {
3355 return input_;
3356 }
3357
3358 - (Package *) packageWithName:(NSString *)name {
3359 if (name == nil)
3360 return nil;
3361 @synchronized (self) {
3362 if (static_cast<pkgDepCache *>(cache_) == NULL)
3363 return nil;
3364 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3365 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3366 } }
3367
3368 - (id) init {
3369 if ((self = [super init]) != nil) {
3370 policy_ = NULL;
3371 records_ = NULL;
3372 resolver_ = NULL;
3373 fetcher_ = NULL;
3374 lock_ = NULL;
3375
3376 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3377 apr_pool_create(&pool_, NULL);
3378
3379 size_t capacity(MetaFile_->active_);
3380 if (capacity == 0)
3381 capacity = 16384;
3382 else
3383 capacity += 1024;
3384
3385 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3386 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3387
3388 int fds[2];
3389
3390 _assert(pipe(fds) != -1);
3391 cydiafd_ = fds[1];
3392
3393 _config->Set("APT::Keep-Fds::", cydiafd_);
3394 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3395
3396 [NSThread
3397 detachNewThreadSelector:@selector(_readCydia:)
3398 toTarget:self
3399 withObject:[NSNumber numberWithInt:fds[0]]
3400 ];
3401
3402 _assert(pipe(fds) != -1);
3403 statusfd_ = fds[1];
3404
3405 [NSThread
3406 detachNewThreadSelector:@selector(_readStatus:)
3407 toTarget:self
3408 withObject:[NSNumber numberWithInt:fds[0]]
3409 ];
3410
3411 _assert(pipe(fds) != -1);
3412 _assert(dup2(fds[0], 0) != -1);
3413 _assert(close(fds[0]) != -1);
3414
3415 input_ = fdopen(fds[1], "a");
3416
3417 _assert(pipe(fds) != -1);
3418 _assert(dup2(fds[1], 1) != -1);
3419 _assert(close(fds[1]) != -1);
3420
3421 [NSThread
3422 detachNewThreadSelector:@selector(_readOutput:)
3423 toTarget:self
3424 withObject:[NSNumber numberWithInt:fds[0]]
3425 ];
3426 } return self;
3427 }
3428
3429 - (pkgCacheFile &) cache {
3430 return cache_;
3431 }
3432
3433 - (pkgDepCache::Policy *) policy {
3434 return policy_;
3435 }
3436
3437 - (pkgRecords *) records {
3438 return records_;
3439 }
3440
3441 - (pkgProblemResolver *) resolver {
3442 return resolver_;
3443 }
3444
3445 - (pkgAcquire &) fetcher {
3446 return *fetcher_;
3447 }
3448
3449 - (pkgSourceList &) list {
3450 return *list_;
3451 }
3452
3453 - (NSArray *) packages {
3454 return (NSArray *) packages_;
3455 }
3456
3457 - (NSArray *) sources {
3458 return sourceList_;
3459 }
3460
3461 - (Source *) sourceWithKey:(NSString *)key {
3462 for (Source *source in [self sources]) {
3463 if ([[source key] isEqualToString:key])
3464 return source;
3465 } return nil;
3466 }
3467
3468 - (bool) popErrorWithTitle:(NSString *)title {
3469 bool fatal(false);
3470
3471 while (!_error->empty()) {
3472 std::string error;
3473 bool warning(!_error->PopMessage(error));
3474 if (!warning)
3475 fatal = true;
3476
3477 for (;;) {
3478 size_t size(error.size());
3479 if (size == 0 || error[size - 1] != '\n')
3480 break;
3481 error.resize(size - 1);
3482 }
3483
3484 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3485
3486 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3487 if (warning && no_pubkey(error.c_str()))
3488 continue;
3489
3490 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3491 }
3492
3493 return fatal;
3494 }
3495
3496 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3497 return [self popErrorWithTitle:title] || !success;
3498 }
3499
3500 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3501 @synchronized (self) {
3502 ++era_;
3503
3504 [self releasePackages];
3505
3506 sourceMap_.clear();
3507 [sourceList_ removeAllObjects];
3508
3509 _error->Discard();
3510
3511 delete list_;
3512 list_ = NULL;
3513 manager_ = NULL;
3514 delete lock_;
3515 lock_ = NULL;
3516 delete fetcher_;
3517 fetcher_ = NULL;
3518 delete resolver_;
3519 resolver_ = NULL;
3520 delete records_;
3521 records_ = NULL;
3522 delete policy_;
3523 policy_ = NULL;
3524
3525 cache_.Close();
3526
3527 apr_pool_clear(pool_);
3528
3529 NSRecycleZone(zone_);
3530 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3531
3532 int chk(creat("/tmp/cydia.chk", 0644));
3533 if (chk != -1)
3534 close(chk);
3535
3536 if (invocation != nil)
3537 [invocation invoke];
3538
3539 NSString *title(UCLocalize("DATABASE"));
3540
3541 _trace();
3542 OpProgress progress;
3543 while (!cache_.Open(progress, true)) { pop:
3544 std::string error;
3545 bool warning(!_error->PopMessage(error));
3546 lprintf("cache_.Open():[%s]\n", error.c_str());
3547
3548 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3549 [delegate_ repairWithSelector:@selector(configure)];
3550 else if (error == "The package lists or status file could not be parsed or opened.")
3551 [delegate_ repairWithSelector:@selector(update)];
3552 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3553 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3554 // else if (error == "Malformed Status line")
3555 // else if (error == "The list of sources could not be read.")
3556 else {
3557 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3558 return;
3559 }
3560
3561 if (warning)
3562 goto pop;
3563 _error->Discard();
3564 }
3565 _trace();
3566
3567 unlink("/tmp/cydia.chk");
3568
3569 now_ = [[NSDate date] timeIntervalSince1970];
3570
3571 policy_ = new pkgDepCache::Policy();
3572 records_ = new pkgRecords(cache_);
3573 resolver_ = new pkgProblemResolver(cache_);
3574 fetcher_ = new pkgAcquire(&status_);
3575 lock_ = NULL;
3576
3577 list_ = new pkgSourceList();
3578 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3579 return;
3580
3581 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3582 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3583 return;
3584 }
3585
3586 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3587 return;
3588
3589 if (cache_->BrokenCount() != 0) {
3590 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3591 return;
3592
3593 if (cache_->BrokenCount() != 0) {
3594 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3595 return;
3596 }
3597
3598 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3599 return;
3600 }
3601
3602 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3603 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3604 [sourceList_ addObject:object];
3605
3606 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3607 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3608 // XXX: this could be more intelligent
3609 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3610 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3611 if (!cached.end())
3612 sourceMap_[cached->ID] = object;
3613 }
3614 }
3615
3616 {
3617 /*std::vector<Package *> packages;
3618 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3619 packages_ = nil;*/
3620
3621 _trace();
3622
3623 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3624 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3625 //packages.push_back(package);
3626 CFArrayAppendValue(packages_, CFRetain(package));
3627
3628 _trace();
3629
3630 /*if (packages.empty())
3631 packages_ = [[NSArray alloc] init];
3632 else
3633 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3634 _trace();*/
3635
3636 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3637 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3638 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3639
3640 /*_trace();
3641 PrintTimes();
3642 _trace();*/
3643
3644 _trace();
3645
3646 /*if (!packages.empty())
3647 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3648 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3649
3650 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3651
3652 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3653
3654 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3655
3656 _trace();
3657
3658 size_t count(CFArrayGetCount(packages_));
3659 MetaFile_->active_ = count;
3660
3661 for (size_t index(0); index != count; ++index)
3662 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3663
3664 _trace();
3665 }
3666 } }
3667
3668 - (void) clear {
3669 @synchronized (self) {
3670 delete resolver_;
3671 resolver_ = new pkgProblemResolver(cache_);
3672
3673 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3674 if (!cache_[iterator].Keep())
3675 cache_->MarkKeep(iterator, false);
3676 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3677 cache_->SetReInstall(iterator, false);
3678 } }
3679
3680 - (void) configure {
3681 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3682 _trace();
3683 system([dpkg UTF8String]);
3684 _trace();
3685 }
3686
3687 - (bool) clean {
3688 @synchronized (self) {
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 [delegate_ cancelAndClear:YES];
5018 [self dismissModalViewControllerAnimated: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 pid_t pid(ExecFork());
5230 if (pid == 0) {
5231 pid_t pid(ExecFork());
5232 if (pid == 0) {
5233 execl("/usr/bin/sbreload", "sbreload", NULL);
5234 perror("sbreload");
5235 exit(0);
5236 }
5237
5238 exit(0);
5239 }
5240
5241 ReapZombie(pid);
5242
5243 sleep(15);
5244 system("/usr/bin/killall SpringBoard");
5245 }
5246
5247 - (void) close {
5248 UpdateExternalStatus(0);
5249
5250 if (Finish_ > 1)
5251 [delegate_ saveState];
5252
5253 switch (Finish_) {
5254 case 0:
5255 [delegate_ returnToCydia];
5256 break;
5257
5258 case 1:
5259 [delegate_ terminateWithSuccess];
5260 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5261 [delegate_ suspendWithAnimation:YES];
5262 else
5263 [delegate_ suspend];*/
5264 break;
5265
5266 case 2:
5267 _trace();
5268 goto reload;
5269
5270 case 3:
5271 _trace();
5272 goto reload;
5273
5274 reload: {
5275 UIProgressHUD *hud([delegate_ addProgressHUD]);
5276 [hud setText:UCLocalize("LOADING")];
5277 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5278 return;
5279 }
5280
5281 case 4:
5282 _trace();
5283 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5284 SBReboot(SBSSpringBoardServerPort());
5285 else
5286 reboot2(RB_AUTOBOOT);
5287 break;
5288 }
5289
5290 [super close];
5291 }
5292
5293 - (void) setTitle:(NSString *)title {
5294 [progress_ setTitle:title];
5295 [self updateProgress];
5296 }
5297
5298 - (UIBarButtonItem *) rightButton {
5299 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5300 initWithTitle:UCLocalize("CLOSE")
5301 style:UIBarButtonItemStylePlain
5302 target:self
5303 action:@selector(close)
5304 ] autorelease];
5305 }
5306
5307 - (void) uicache {
5308 _trace();
5309 system("su -c /usr/bin/uicache mobile");
5310 _trace();
5311 }
5312
5313 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5314 UpdateExternalStatus(1);
5315
5316 [progress_ setRunning:true];
5317 [self setTitle:title];
5318 // implicit updateProgress
5319
5320 SHA1SumValue notifyconf; {
5321 FileFd file;
5322 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5323 _error->Discard();
5324 else {
5325 MMap mmap(file, MMap::ReadOnly);
5326 SHA1Summation sha1;
5327 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5328 notifyconf = sha1.Result();
5329 }
5330 }
5331
5332 SHA1SumValue springlist; {
5333 FileFd file;
5334 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5335 _error->Discard();
5336 else {
5337 MMap mmap(file, MMap::ReadOnly);
5338 SHA1Summation sha1;
5339 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5340 springlist = sha1.Result();
5341 }
5342 }
5343
5344 if (invocation != nil) {
5345 [invocation yieldToSelector:@selector(invoke)];
5346 [self setTitle:@"COMPLETE"];
5347 }
5348
5349 if (Finish_ < 4) {
5350 FileFd file;
5351 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5352 _error->Discard();
5353 else {
5354 MMap mmap(file, MMap::ReadOnly);
5355 SHA1Summation sha1;
5356 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5357 if (!(notifyconf == sha1.Result()))
5358 Finish_ = 4;
5359 }
5360 }
5361
5362 if (Finish_ < 3) {
5363 FileFd file;
5364 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5365 _error->Discard();
5366 else {
5367 MMap mmap(file, MMap::ReadOnly);
5368 SHA1Summation sha1;
5369 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5370 if (!(springlist == sha1.Result()))
5371 Finish_ = 3;
5372 }
5373 }
5374
5375 if (Finish_ < 2) {
5376 if (RestartSubstrate_)
5377 Finish_ = 2;
5378 }
5379
5380 RestartSubstrate_ = false;
5381
5382 switch (Finish_) {
5383 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5384 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5385 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5386 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5387 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5388 }
5389
5390 UIProgressHUD *hud([delegate_ addProgressHUD]);
5391 [hud setText:UCLocalize("LOADING")];
5392 [self yieldToSelector:@selector(uicache)];
5393 [delegate_ removeProgressHUD:hud];
5394
5395 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5396
5397 [progress_ setRunning:false];
5398 [self updateProgress];
5399
5400 [self applyRightButton];
5401 }
5402
5403 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5404 [progress_ addEvent:event];
5405 [self updateProgress];
5406 }
5407
5408 - (bool) isProgressCancelled {
5409 return cancel_ == 2;
5410 }
5411
5412 - (void) cancel {
5413 cancel_ = 2;
5414 [self updateCancel];
5415 }
5416
5417 - (void) setCancellable:(bool)cancellable {
5418 unsigned cancel(cancel_);
5419
5420 if (!cancellable)
5421 cancel_ = 0;
5422 else if (cancel_ == 0)
5423 cancel_ = 1;
5424
5425 if (cancel != cancel_)
5426 [self updateCancel];
5427 }
5428
5429 - (void) setProgressCancellable:(NSNumber *)cancellable {
5430 [self setCancellable:[cancellable boolValue]];
5431 }
5432
5433 - (void) setProgressPercent:(NSNumber *)percent {
5434 [progress_ setPercent:[percent floatValue]];
5435 [self updateProgress];
5436 }
5437
5438 - (void) setProgressStatus:(NSDictionary *)status {
5439 if (status == nil) {
5440 [progress_ setCurrent:0];
5441 [progress_ setTotal:0];
5442 [progress_ setSpeed:0];
5443 } else {
5444 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5445
5446 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5447 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5448 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5449 }
5450
5451 [self updateProgress];
5452 }
5453
5454 @end
5455 /* }}} */
5456
5457 /* Package Cell {{{ */
5458 @interface PackageCell : CyteTableViewCell <
5459 CyteTableViewCellDelegate
5460 > {
5461 _H<UIImage> icon_;
5462 _H<NSString> name_;
5463 _H<NSString> description_;
5464 bool commercial_;
5465 _H<NSString> source_;
5466 _H<UIImage> badge_;
5467 _H<UIImage> placard_;
5468 bool summarized_;
5469 }
5470
5471 - (PackageCell *) init;
5472 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5473
5474 - (void) drawContentRect:(CGRect)rect;
5475
5476 @end
5477
5478 @implementation PackageCell
5479
5480 - (PackageCell *) init {
5481 CGRect frame(CGRectMake(0, 0, 320, 74));
5482 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5483 UIView *content([self contentView]);
5484 CGRect bounds([content bounds]);
5485
5486 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5487 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5488 [content addSubview:content_];
5489
5490 [content_ setDelegate:self];
5491 [content_ setOpaque:YES];
5492 } return self;
5493 }
5494
5495 - (NSString *) accessibilityLabel {
5496 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5497 }
5498
5499 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5500 summarized_ = summary;
5501
5502 icon_ = nil;
5503 name_ = nil;
5504 description_ = nil;
5505 source_ = nil;
5506 badge_ = nil;
5507 placard_ = nil;
5508
5509 if (package == nil)
5510 [content_ setBackgroundColor:[UIColor whiteColor]];
5511 else {
5512 [package parse];
5513
5514 Source *source = [package source];
5515
5516 icon_ = [package icon];
5517
5518 if (NSString *name = [package name])
5519 name_ = [NSString stringWithString:name];
5520
5521 NSString *description(nil);
5522
5523 if (description == nil && IsWildcat_)
5524 description = [package longDescription];
5525 if (description == nil)
5526 description = [package shortDescription];
5527
5528 if (description != nil)
5529 description_ = [NSString stringWithString:description];
5530
5531 commercial_ = [package isCommercial];
5532
5533 NSString *label = nil;
5534 bool trusted = false;
5535
5536 if (source != nil) {
5537 label = [source label];
5538 trusted = [source trusted];
5539 } else if ([[package id] isEqualToString:@"firmware"])
5540 label = UCLocalize("APPLE");
5541 else
5542 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5543
5544 NSString *from(label);
5545
5546 NSString *section = [package simpleSection];
5547 if (section != nil && ![section isEqualToString:label]) {
5548 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5549 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5550 }
5551
5552 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5553
5554 if (NSString *purpose = [package primaryPurpose])
5555 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5556
5557 UIColor *color;
5558 NSString *placard;
5559
5560 if (NSString *mode = [package mode]) {
5561 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5562 color = RemovingColor_;
5563 //placard = @"removing";
5564 } else {
5565 color = InstallingColor_;
5566 //placard = @"installing";
5567 }
5568
5569 // XXX: the removing/installing placards are not @2x
5570 placard = nil;
5571 } else {
5572 color = [UIColor whiteColor];
5573
5574 if ([package installed] != nil)
5575 placard = @"installed";
5576 else
5577 placard = nil;
5578 }
5579
5580 [content_ setBackgroundColor:color];
5581
5582 if (placard != nil)
5583 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5584 }
5585
5586 [self setNeedsDisplay];
5587 [content_ setNeedsDisplay];
5588 }
5589
5590 - (void) drawSummaryContentRect:(CGRect)rect {
5591 bool highlighted(highlighted_);
5592 float width([self bounds].size.width);
5593
5594 if (icon_ != nil) {
5595 CGRect rect;
5596 rect.size = [(UIImage *) icon_ size];
5597
5598 while (rect.size.width > 16 || rect.size.height > 16) {
5599 rect.size.width /= 2;
5600 rect.size.height /= 2;
5601 }
5602
5603 rect.origin.x = 18 - rect.size.width / 2;
5604 rect.origin.y = 18 - rect.size.height / 2;
5605
5606 [icon_ drawInRect:rect];
5607 }
5608
5609 if (badge_ != nil) {
5610 CGRect rect;
5611 rect.size = [(UIImage *) badge_ size];
5612
5613 rect.size.width /= 4;
5614 rect.size.height /= 4;
5615
5616 rect.origin.x = 23 - rect.size.width / 2;
5617 rect.origin.y = 23 - rect.size.height / 2;
5618
5619 [badge_ drawInRect:rect];
5620 }
5621
5622 if (highlighted)
5623 UISetColor(White_);
5624
5625 if (!highlighted)
5626 UISetColor(commercial_ ? Purple_ : Black_);
5627 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5628
5629 if (placard_ != nil)
5630 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5631 }
5632
5633 - (void) drawNormalContentRect:(CGRect)rect {
5634 bool highlighted(highlighted_);
5635 float width([self bounds].size.width);
5636
5637 if (icon_ != nil) {
5638 CGRect rect;
5639 rect.size = [(UIImage *) icon_ size];
5640
5641 while (rect.size.width > 32 || rect.size.height > 32) {
5642 rect.size.width /= 2;
5643 rect.size.height /= 2;
5644 }
5645
5646 rect.origin.x = 25 - rect.size.width / 2;
5647 rect.origin.y = 25 - rect.size.height / 2;
5648
5649 [icon_ drawInRect:rect];
5650 }
5651
5652 if (badge_ != nil) {
5653 CGRect rect;
5654 rect.size = [(UIImage *) badge_ size];
5655
5656 rect.size.width /= 2;
5657 rect.size.height /= 2;
5658
5659 rect.origin.x = 36 - rect.size.width / 2;
5660 rect.origin.y = 36 - rect.size.height / 2;
5661
5662 [badge_ drawInRect:rect];
5663 }
5664
5665 if (highlighted)
5666 UISetColor(White_);
5667
5668 if (!highlighted)
5669 UISetColor(commercial_ ? Purple_ : Black_);
5670 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5671 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5672
5673 if (!highlighted)
5674 UISetColor(commercial_ ? Purplish_ : Gray_);
5675 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5676
5677 if (placard_ != nil)
5678 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5679 }
5680
5681 - (void) drawContentRect:(CGRect)rect {
5682 if (summarized_)
5683 [self drawSummaryContentRect:rect];
5684 else
5685 [self drawNormalContentRect:rect];
5686 }
5687
5688 @end
5689 /* }}} */
5690 /* Section Cell {{{ */
5691 @interface SectionCell : CyteTableViewCell <
5692 CyteTableViewCellDelegate
5693 > {
5694 _H<NSString> basic_;
5695 _H<NSString> section_;
5696 _H<NSString> name_;
5697 _H<NSString> count_;
5698 _H<UIImage> icon_;
5699 _H<UISwitch> switch_;
5700 BOOL editing_;
5701 }
5702
5703 - (void) setSection:(Section *)section editing:(BOOL)editing;
5704
5705 @end
5706
5707 @implementation SectionCell
5708
5709 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5710 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5711 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5712 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5713 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5714
5715 UIView *content([self contentView]);
5716 CGRect bounds([content bounds]);
5717
5718 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5719 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5720 [content addSubview:content_];
5721 [content_ setBackgroundColor:[UIColor whiteColor]];
5722
5723 [content_ setDelegate:self];
5724 } return self;
5725 }
5726
5727 - (void) onSwitch:(id)sender {
5728 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5729 if (metadata == nil) {
5730 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5731 [Sections_ setObject:metadata forKey:basic_];
5732 }
5733
5734 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5735 Changed_ = true;
5736 }
5737
5738 - (void) setSection:(Section *)section editing:(BOOL)editing {
5739 if (editing != editing_) {
5740 if (editing_)
5741 [switch_ removeFromSuperview];
5742 else
5743 [self addSubview:switch_];
5744 editing_ = editing;
5745 }
5746
5747 basic_ = nil;
5748 section_ = nil;
5749 name_ = nil;
5750 count_ = nil;
5751
5752 if (section == nil) {
5753 name_ = UCLocalize("ALL_PACKAGES");
5754 count_ = nil;
5755 } else {
5756 basic_ = [section name];
5757 section_ = [section localized];
5758
5759 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5760 count_ = [NSString stringWithFormat:@"%d", [section count]];
5761
5762 if (editing_)
5763 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5764 }
5765
5766 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5767 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5768
5769 [content_ setNeedsDisplay];
5770 }
5771
5772 - (void) setFrame:(CGRect)frame {
5773 [super setFrame:frame];
5774
5775 CGRect rect([switch_ frame]);
5776 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5777 }
5778
5779 - (NSString *) accessibilityLabel {
5780 return name_;
5781 }
5782
5783 - (void) drawContentRect:(CGRect)rect {
5784 bool highlighted(highlighted_ && !editing_);
5785
5786 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5787
5788 if (highlighted)
5789 UISetColor(White_);
5790
5791 float width(rect.size.width);
5792 if (editing_)
5793 width -= 87;
5794
5795 if (!highlighted)
5796 UISetColor(Black_);
5797 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5798
5799 CGSize size = [count_ sizeWithFont:Font14_];
5800
5801 UISetColor(White_);
5802 if (count_ != nil)
5803 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5804 }
5805
5806 @end
5807 /* }}} */
5808
5809 /* File Table {{{ */
5810 @interface FileTable : CyteViewController <
5811 UITableViewDataSource,
5812 UITableViewDelegate
5813 > {
5814 _transient Database *database_;
5815 _H<Package> package_;
5816 _H<NSString> name_;
5817 _H<NSMutableArray> files_;
5818 _H<UITableView, 2> list_;
5819 }
5820
5821 - (id) initWithDatabase:(Database *)database;
5822 - (void) setPackage:(Package *)package;
5823
5824 @end
5825
5826 @implementation FileTable
5827
5828 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5829 return files_ == nil ? 0 : [files_ count];
5830 }
5831
5832 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5833 return 24.0f;
5834 }*/
5835
5836 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5837 static NSString *reuseIdentifier = @"Cell";
5838
5839 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5840 if (cell == nil) {
5841 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5842 [cell setFont:[UIFont systemFontOfSize:16]];
5843 }
5844 [cell setText:[files_ objectAtIndex:indexPath.row]];
5845 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5846
5847 return cell;
5848 }
5849
5850 - (NSURL *) navigationURL {
5851 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5852 }
5853
5854 - (void) loadView {
5855 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5856 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5857 [list_ setRowHeight:24.0f];
5858 [(UITableView *) list_ setDataSource:self];
5859 [list_ setDelegate:self];
5860 [self setView:list_];
5861 }
5862
5863 - (void) viewDidLoad {
5864 [super viewDidLoad];
5865
5866 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5867 }
5868
5869 - (void) releaseSubviews {
5870 list_ = nil;
5871
5872 package_ = nil;
5873 files_ = nil;
5874
5875 [super releaseSubviews];
5876 }
5877
5878 - (id) initWithDatabase:(Database *)database {
5879 if ((self = [super init]) != nil) {
5880 database_ = database;
5881 } return self;
5882 }
5883
5884 - (void) setPackage:(Package *)package {
5885 package_ = nil;
5886 name_ = nil;
5887
5888 files_ = [NSMutableArray arrayWithCapacity:32];
5889
5890 if (package != nil) {
5891 package_ = package;
5892 name_ = [package id];
5893
5894 if (NSArray *files = [package files])
5895 [files_ addObjectsFromArray:files];
5896
5897 if ([files_ count] != 0) {
5898 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5899 [files_ removeObjectAtIndex:0];
5900 [files_ sortUsingSelector:@selector(compareByPath:)];
5901
5902 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5903 [stack addObject:@"/"];
5904
5905 for (int i(0), e([files_ count]); i != e; ++i) {
5906 NSString *file = [files_ objectAtIndex:i];
5907 while (![file hasPrefix:[stack lastObject]])
5908 [stack removeLastObject];
5909 NSString *directory = [stack lastObject];
5910 [stack addObject:[file stringByAppendingString:@"/"]];
5911 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5912 ([stack count] - 2) * 3, "",
5913 [file substringFromIndex:[directory length]]
5914 ]];
5915 }
5916 }
5917 }
5918
5919 [list_ reloadData];
5920 }
5921
5922 - (void) reloadData {
5923 [super reloadData];
5924
5925 [self setPackage:[database_ packageWithName:name_]];
5926 }
5927
5928 @end
5929 /* }}} */
5930 /* Package Controller {{{ */
5931 @interface CYPackageController : CydiaWebViewController <
5932 UIActionSheetDelegate
5933 > {
5934 _transient Database *database_;
5935 _H<Package> package_;
5936 _H<NSString> name_;
5937 bool commercial_;
5938 _H<NSMutableArray> buttons_;
5939 _H<UIBarButtonItem> button_;
5940 }
5941
5942 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5943
5944 @end
5945
5946 @implementation CYPackageController
5947
5948 - (NSURL *) navigationURL {
5949 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5950 }
5951
5952 /* XXX: this is not safe at all... localization of /fail/ */
5953 - (void) _clickButtonWithName:(NSString *)name {
5954 if ([name isEqualToString:UCLocalize("CLEAR")])
5955 [delegate_ clearPackage:package_];
5956 else if ([name isEqualToString:UCLocalize("INSTALL")])
5957 [delegate_ installPackage:package_];
5958 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5959 [delegate_ installPackage:package_];
5960 else if ([name isEqualToString:UCLocalize("REMOVE")])
5961 [delegate_ removePackage:package_];
5962 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5963 [delegate_ installPackage:package_];
5964 else _assert(false);
5965 }
5966
5967 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5968 NSString *context([sheet context]);
5969
5970 if ([context isEqualToString:@"modify"]) {
5971 if (button != [sheet cancelButtonIndex]) {
5972 NSString *buttonName = [buttons_ objectAtIndex:button];
5973 [self _clickButtonWithName:buttonName];
5974 }
5975
5976 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5977 }
5978 }
5979
5980 - (bool) _allowJavaScriptPanel {
5981 return commercial_;
5982 }
5983
5984 #if !AlwaysReload
5985 - (void) _customButtonClicked {
5986 int count([buttons_ count]);
5987 if (count == 0)
5988 return;
5989
5990 if (count == 1)
5991 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5992 else {
5993 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5994 [buttons addObjectsFromArray:buttons_];
5995
5996 UIActionSheet *sheet = [[[UIActionSheet alloc]
5997 initWithTitle:nil
5998 delegate:self
5999 cancelButtonTitle:nil
6000 destructiveButtonTitle:nil
6001 otherButtonTitles:nil
6002 ] autorelease];
6003
6004 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6005 if (!IsWildcat_) {
6006 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6007 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6008 }
6009 [sheet setContext:@"modify"];
6010
6011 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6012 }
6013 }
6014
6015 // We don't want to allow non-commercial packages to do custom things to the install button,
6016 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6017 - (void) customButtonClicked {
6018 if (commercial_)
6019 [super customButtonClicked];
6020 else
6021 [self _customButtonClicked];
6022 }
6023
6024 - (void) reloadButtonClicked {
6025 // Don't reload a commerical package by tapping the loading button,
6026 // but if it's not an Install button, we should forward it on.
6027 if (![package_ uninstalled])
6028 [self _customButtonClicked];
6029 }
6030
6031 - (void) applyLoadingTitle {
6032 // Don't show "Loading" as the title. Ever.
6033 }
6034
6035 - (UIBarButtonItem *) rightButton {
6036 return button_;
6037 }
6038 #endif
6039
6040 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6041 if ((self = [super init]) != nil) {
6042 database_ = database;
6043 buttons_ = [NSMutableArray arrayWithCapacity:4];
6044 name_ = name == nil ? @"" : [NSString stringWithString:name];
6045 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6046 } return self;
6047 }
6048
6049 - (void) reloadData {
6050 [super reloadData];
6051
6052 package_ = [database_ packageWithName:name_];
6053
6054 [buttons_ removeAllObjects];
6055
6056 if (package_ != nil) {
6057 [(Package *) package_ parse];
6058
6059 commercial_ = [package_ isCommercial];
6060
6061 if ([package_ mode] != nil)
6062 [buttons_ addObject:UCLocalize("CLEAR")];
6063 if ([package_ source] == nil);
6064 else if ([package_ upgradableAndEssential:NO])
6065 [buttons_ addObject:UCLocalize("UPGRADE")];
6066 else if ([package_ uninstalled])
6067 [buttons_ addObject:UCLocalize("INSTALL")];
6068 else
6069 [buttons_ addObject:UCLocalize("REINSTALL")];
6070 if (![package_ uninstalled])
6071 [buttons_ addObject:UCLocalize("REMOVE")];
6072 }
6073
6074 NSString *title;
6075 switch ([buttons_ count]) {
6076 case 0: title = nil; break;
6077 case 1: title = [buttons_ objectAtIndex:0]; break;
6078 default: title = UCLocalize("MODIFY"); break;
6079 }
6080
6081 button_ = [[[UIBarButtonItem alloc]
6082 initWithTitle:title
6083 style:UIBarButtonItemStylePlain
6084 target:self
6085 action:@selector(customButtonClicked)
6086 ] autorelease];
6087 }
6088
6089 - (bool) isLoading {
6090 return commercial_ ? [super isLoading] : false;
6091 }
6092
6093 @end
6094 /* }}} */
6095
6096 /* Package List Controller {{{ */
6097 @interface PackageListController : CyteViewController <
6098 UITableViewDataSource,
6099 UITableViewDelegate
6100 > {
6101 _transient Database *database_;
6102 unsigned era_;
6103 _H<NSArray> packages_;
6104 _H<NSMutableArray> sections_;
6105 _H<UITableView, 2> list_;
6106 _H<NSMutableArray> index_;
6107 _H<NSMutableDictionary> indices_;
6108 _H<NSString> title_;
6109 unsigned reloading_;
6110 }
6111
6112 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6113 - (void) setDelegate:(id)delegate;
6114 - (void) resetCursor;
6115 - (void) clearData;
6116
6117 @end
6118
6119 @implementation PackageListController
6120
6121 - (NSURL *) referrerURL {
6122 return [self navigationURL];
6123 }
6124
6125 - (bool) isSummarized {
6126 return false;
6127 }
6128
6129 - (bool) showsSections {
6130 return true;
6131 }
6132
6133 - (void) deselectWithAnimation:(BOOL)animated {
6134 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6135 }
6136
6137 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6138 CGRect base = [[self view] bounds];
6139 base.size.height -= bounds.size.height;
6140 base.origin = [list_ frame].origin;
6141
6142 [UIView beginAnimations:nil context:NULL];
6143 [UIView setAnimationBeginsFromCurrentState:YES];
6144 [UIView setAnimationCurve:curve];
6145 [UIView setAnimationDuration:duration];
6146 [list_ setFrame:base];
6147 [UIView commitAnimations];
6148 }
6149
6150 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6151 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6152 }
6153
6154 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6155 [self resizeForKeyboardBounds:bounds duration:0];
6156 }
6157
6158 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6159 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6160 *curve = UIViewAnimationCurveEaseInOut;
6161 else
6162 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6163
6164 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6165 *duration = 0.3;
6166 else
6167 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6168 }
6169
6170 - (void) keyboardWillShow:(NSNotification *)notification {
6171 CGRect bounds;
6172 CGPoint center;
6173 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6174 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6175
6176 NSTimeInterval duration;
6177 UIViewAnimationCurve curve;
6178 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6179
6180 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);
6181 UIViewController *base = self;
6182 while ([base parentViewController] != nil)
6183 base = [base parentViewController];
6184 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6185 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6186
6187 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6188 intersection.size.height += CYStatusBarHeight();
6189
6190 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6191 }
6192
6193 - (void) keyboardWillHide:(NSNotification *)notification {
6194 NSTimeInterval duration;
6195 UIViewAnimationCurve curve;
6196 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6197
6198 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6199 }
6200
6201 - (void) viewWillAppear:(BOOL)animated {
6202 [super viewWillAppear:animated];
6203
6204 [self resizeForKeyboardBounds:CGRectZero];
6205 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6206 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6207 }
6208
6209 - (void) viewWillDisappear:(BOOL)animated {
6210 [super viewWillDisappear:animated];
6211
6212 [self resizeForKeyboardBounds:CGRectZero];
6213 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6214 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6215 }
6216
6217 - (void) viewDidAppear:(BOOL)animated {
6218 [super viewDidAppear:animated];
6219 [self deselectWithAnimation:animated];
6220 }
6221
6222 - (void) didSelectPackage:(Package *)package {
6223 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6224 [view setDelegate:delegate_];
6225 [[self navigationController] pushViewController:view animated:YES];
6226 }
6227
6228 #if TryIndexedCollation
6229 + (BOOL) hasIndexedCollation {
6230 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6231 }
6232 #endif
6233
6234 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6235 NSInteger count([sections_ count]);
6236 return count == 0 ? 1 : count;
6237 }
6238
6239 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6240 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6241 return nil;
6242 return [[sections_ objectAtIndex:section] name];
6243 }
6244
6245 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6246 if ([sections_ count] == 0)
6247 return 0;
6248 return [[sections_ objectAtIndex:section] count];
6249 }
6250
6251 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6252 @synchronized (database_) {
6253 if ([database_ era] != era_)
6254 return nil;
6255
6256 Section *section([sections_ objectAtIndex:[path section]]);
6257 NSInteger row([path row]);
6258 Package *package([packages_ objectAtIndex:([section row] + row)]);
6259 return [[package retain] autorelease];
6260 } }
6261
6262 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6263 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6264 if (cell == nil)
6265 cell = [[[PackageCell alloc] init] autorelease];
6266
6267 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6268 [cell setPackage:package asSummary:[self isSummarized]];
6269 return cell;
6270 }
6271
6272 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6273 Package *package([self packageAtIndexPath:path]);
6274 package = [database_ packageWithName:[package id]];
6275 [self didSelectPackage:package];
6276 }
6277
6278 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6279 if (![self showsSections])
6280 return nil;
6281
6282 return index_;
6283 }
6284
6285 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6286 #if TryIndexedCollation
6287 if ([[self class] hasIndexedCollation]) {
6288 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6289 }
6290 #endif
6291
6292 return index;
6293 }
6294
6295 - (void) updateHeight {
6296 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6297 }
6298
6299 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6300 if ((self = [super init]) != nil) {
6301 database_ = database;
6302 title_ = [title copy];
6303 [[self navigationItem] setTitle:title_];
6304 } return self;
6305 }
6306
6307 - (void) loadView {
6308 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6309 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6310 [self setView:view];
6311
6312 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6313 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6314 [view addSubview:list_];
6315
6316 // XXX: is 20 the most optimal number here?
6317 [list_ setSectionIndexMinimumDisplayRowCount:20];
6318
6319 [(UITableView *) list_ setDataSource:self];
6320 [list_ setDelegate:self];
6321
6322 [self updateHeight];
6323 }
6324
6325 - (void) releaseSubviews {
6326 list_ = nil;
6327
6328 packages_ = nil;
6329 sections_ = nil;
6330 index_ = nil;
6331 indices_ = nil;
6332
6333 [super releaseSubviews];
6334 }
6335
6336 - (void) setDelegate:(id)delegate {
6337 delegate_ = delegate;
6338 }
6339
6340 - (bool) shouldYield {
6341 return false;
6342 }
6343
6344 - (bool) shouldBlock {
6345 return false;
6346 }
6347
6348 - (NSMutableArray *) _reloadPackages {
6349 @synchronized (database_) {
6350 era_ = [database_ era];
6351 NSArray *packages([database_ packages]);
6352
6353 return [NSMutableArray arrayWithArray:packages];
6354 } }
6355
6356 - (void) _reloadData {
6357 if (reloading_ != 0) {
6358 reloading_ = 2;
6359 return;
6360 }
6361
6362 NSArray *packages;
6363
6364 reload:
6365 if ([self shouldYield]) {
6366 do {
6367 UIProgressHUD *hud;
6368
6369 if (![self shouldBlock])
6370 hud = nil;
6371 else {
6372 hud = [delegate_ addProgressHUD];
6373 [hud setText:UCLocalize("LOADING")];
6374 }
6375
6376 reloading_ = 1;
6377 packages = [self yieldToSelector:@selector(_reloadPackages)];
6378
6379 if (hud != nil)
6380 [delegate_ removeProgressHUD:hud];
6381 } while (reloading_ == 2);
6382 } else {
6383 packages = [self _reloadPackages];
6384 }
6385
6386 @synchronized (database_) {
6387 if (era_ != [database_ era])
6388 goto reload;
6389 reloading_ = 0;
6390
6391 packages_ = packages;
6392
6393 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6394 sections_ = [NSMutableArray arrayWithCapacity:16];
6395
6396 Section *section = nil;
6397
6398 #if TryIndexedCollation
6399 if ([[self class] hasIndexedCollation]) {
6400 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6401
6402 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6403 NSArray *titles = [collation sectionIndexTitles];
6404 int secidx = -1;
6405
6406 _profile(PackageTable$reloadData$Section)
6407 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6408 Package *package;
6409 int index;
6410
6411 _profile(PackageTable$reloadData$Section$Package)
6412 package = [packages_ objectAtIndex:offset];
6413 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6414 _end
6415
6416 while (secidx < index) {
6417 secidx += 1;
6418
6419 _profile(PackageTable$reloadData$Section$Allocate)
6420 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6421 _end
6422
6423 _profile(PackageTable$reloadData$Section$Add)
6424 [sections_ addObject:section];
6425 _end
6426 }
6427
6428 [section addToCount];
6429 }
6430 _end
6431 } else
6432 #endif
6433 {
6434 index_ = [NSMutableArray arrayWithCapacity:32];
6435
6436 bool sectioned([self showsSections]);
6437 if (!sectioned) {
6438 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6439 [sections_ addObject:section];
6440 }
6441
6442 _profile(PackageTable$reloadData$Section)
6443 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6444 Package *package;
6445 unichar index;
6446
6447 _profile(PackageTable$reloadData$Section$Package)
6448 package = [packages_ objectAtIndex:offset];
6449 index = [package index];
6450 _end
6451
6452 if (sectioned && (section == nil || [section index] != index)) {
6453 _profile(PackageTable$reloadData$Section$Allocate)
6454 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6455 _end
6456
6457 [index_ addObject:[section name]];
6458 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6459
6460 _profile(PackageTable$reloadData$Section$Add)
6461 [sections_ addObject:section];
6462 _end
6463 }
6464
6465 [section addToCount];
6466 }
6467 _end
6468 }
6469
6470 [self updateHeight];
6471
6472 _profile(PackageTable$reloadData$List)
6473 [(UITableView *) list_ setDataSource:self];
6474 [list_ reloadData];
6475 _end
6476 } }
6477
6478 - (void) reloadData {
6479 [super reloadData];
6480
6481 if ([self shouldYield])
6482 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6483 else
6484 [self _reloadData];
6485 }
6486
6487 - (void) resetCursor {
6488 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6489 }
6490
6491 - (void) clearData {
6492 [self updateHeight];
6493
6494 [list_ setDataSource:nil];
6495 [list_ reloadData];
6496
6497 [self resetCursor];
6498 }
6499
6500 @end
6501 /* }}} */
6502 /* Filtered Package List Controller {{{ */
6503 @interface FilteredPackageListController : PackageListController {
6504 SEL filter_;
6505 IMP imp_;
6506 _H<NSObject> object_;
6507 }
6508
6509 - (void) setObject:(id)object;
6510 - (void) setObject:(id)object forFilter:(SEL)filter;
6511
6512 - (SEL) filter;
6513 - (void) setFilter:(SEL)filter;
6514
6515 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6516
6517 @end
6518
6519 @implementation FilteredPackageListController
6520
6521 - (SEL) filter {
6522 return filter_;
6523 }
6524
6525 - (void) setFilter:(SEL)filter {
6526 @synchronized (self) {
6527 filter_ = filter;
6528
6529 /* XXX: this is an unsafe optimization of doomy hell */
6530 Method method(class_getInstanceMethod([Package class], filter));
6531 _assert(method != NULL);
6532 imp_ = method_getImplementation(method);
6533 _assert(imp_ != NULL);
6534 } }
6535
6536 - (void) setObject:(id)object {
6537 @synchronized (self) {
6538 object_ = object;
6539 } }
6540
6541 - (void) setObject:(id)object forFilter:(SEL)filter {
6542 @synchronized (self) {
6543 [self setFilter:filter];
6544 [self setObject:object];
6545 } }
6546
6547 - (NSMutableArray *) _reloadPackages {
6548 @synchronized (database_) {
6549 era_ = [database_ era];
6550 NSArray *packages([database_ packages]);
6551
6552 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6553
6554 IMP imp;
6555 SEL filter;
6556 _H<NSObject> object;
6557
6558 @synchronized (self) {
6559 imp = imp_;
6560 filter = filter_;
6561 object = object_;
6562 }
6563
6564 _profile(PackageTable$reloadData$Filter)
6565 for (Package *package in packages)
6566 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6567 [filtered addObject:package];
6568 _end
6569
6570 return filtered;
6571 } }
6572
6573 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6574 if ((self = [super initWithDatabase:database title:title]) != nil) {
6575 [self setFilter:filter];
6576 [self setObject:object];
6577 } return self;
6578 }
6579
6580 @end
6581 /* }}} */
6582
6583 /* Home Controller {{{ */
6584 @interface HomeController : CydiaWebViewController {
6585 CFRunLoopRef runloop_;
6586 SCNetworkReachabilityRef reachability_;
6587 }
6588
6589 @end
6590
6591 @implementation HomeController
6592
6593 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6594 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6595 }
6596
6597 - (id) init {
6598 if ((self = [super init]) != nil) {
6599 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6600 [self reloadData];
6601
6602 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6603 if (reachability_ != NULL) {
6604 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6605 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6606
6607 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6608 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6609 runloop_ = runloop;
6610 }
6611 } return self;
6612 }
6613
6614 - (void) dealloc {
6615 if (reachability_ != NULL && runloop_ != NULL)
6616 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6617 [super dealloc];
6618 }
6619
6620 - (NSURL *) navigationURL {
6621 return [NSURL URLWithString:@"cydia://home"];
6622 }
6623
6624 - (void) aboutButtonClicked {
6625 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6626
6627 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6628 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6629 [alert setCancelButtonIndex:0];
6630
6631 [alert setMessage:
6632 @"Copyright \u00a9 2008-2011\n"
6633 "SaurikIT, LLC\n"
6634 "\n"
6635 "Jay Freeman (saurik)\n"
6636 "saurik@saurik.com\n"
6637 "http://www.saurik.com/"
6638 ];
6639
6640 [alert show];
6641 }
6642
6643 - (UIBarButtonItem *) leftButton {
6644 return [[[UIBarButtonItem alloc]
6645 initWithTitle:UCLocalize("ABOUT")
6646 style:UIBarButtonItemStylePlain
6647 target:self
6648 action:@selector(aboutButtonClicked)
6649 ] autorelease];
6650 }
6651
6652 @end
6653 /* }}} */
6654 /* Manage Controller {{{ */
6655 @interface ManageController : CydiaWebViewController {
6656 }
6657
6658 - (void) queueStatusDidChange;
6659
6660 @end
6661
6662 @implementation ManageController
6663
6664 - (id) init {
6665 if ((self = [super init]) != nil) {
6666 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6667 } return self;
6668 }
6669
6670 - (NSURL *) navigationURL {
6671 return [NSURL URLWithString:@"cydia://manage"];
6672 }
6673
6674 - (UIBarButtonItem *) leftButton {
6675 return [[[UIBarButtonItem alloc]
6676 initWithTitle:UCLocalize("SETTINGS")
6677 style:UIBarButtonItemStylePlain
6678 target:self
6679 action:@selector(settingsButtonClicked)
6680 ] autorelease];
6681 }
6682
6683 - (void) settingsButtonClicked {
6684 [delegate_ showSettings];
6685 }
6686
6687 - (void) queueButtonClicked {
6688 [delegate_ queue];
6689 }
6690
6691 - (UIBarButtonItem *) rightButton {
6692 return Queuing_ ? [[[UIBarButtonItem alloc]
6693 initWithTitle:UCLocalize("QUEUE")
6694 style:UIBarButtonItemStyleDone
6695 target:self
6696 action:@selector(queueButtonClicked)
6697 ] autorelease] : nil;
6698 }
6699
6700 - (void) queueStatusDidChange {
6701 [self applyRightButton];
6702 }
6703
6704 - (bool) isLoading {
6705 return !Queuing_ && [super isLoading];
6706 }
6707
6708 @end
6709 /* }}} */
6710
6711 /* Refresh Bar {{{ */
6712 @interface RefreshBar : UINavigationBar {
6713 _H<UIProgressIndicator> indicator_;
6714 _H<UITextLabel> prompt_;
6715 _H<UIProgressBar> progress_;
6716 _H<UINavigationButton> cancel_;
6717 }
6718
6719 @end
6720
6721 @implementation RefreshBar
6722
6723 - (void) positionViews {
6724 CGRect frame = [cancel_ frame];
6725 frame.size = [cancel_ sizeThatFits:frame.size];
6726 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6727 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6728 [cancel_ setFrame:frame];
6729
6730 CGSize prgsize = {75, 100};
6731 CGRect prgrect = {{
6732 [self frame].size.width - prgsize.width - 10,
6733 ([self frame].size.height - prgsize.height) / 2
6734 } , prgsize};
6735 [progress_ setFrame:prgrect];
6736
6737 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6738 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6739 CGRect indrect = {{indoffset, indoffset}, indsize};
6740 [indicator_ setFrame:indrect];
6741
6742 CGSize prmsize = {215, indsize.height + 4};
6743 CGRect prmrect = {{
6744 indoffset * 2 + indsize.width,
6745 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6746 }, prmsize};
6747 [prompt_ setFrame:prmrect];
6748 }
6749
6750 - (void) setFrame:(CGRect)frame {
6751 [super setFrame:frame];
6752 [self positionViews];
6753 }
6754
6755 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6756 if ((self = [super initWithFrame:frame]) != nil) {
6757 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6758
6759 [self setBarStyle:UIBarStyleBlack];
6760
6761 UIBarStyle barstyle([self _barStyle:NO]);
6762 bool ugly(barstyle == UIBarStyleDefault);
6763
6764 UIProgressIndicatorStyle style = ugly ?
6765 UIProgressIndicatorStyleMediumBrown :
6766 UIProgressIndicatorStyleMediumWhite;
6767
6768 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6769 [(UIProgressIndicator *) indicator_ setStyle:style];
6770 [indicator_ startAnimation];
6771 [self addSubview:indicator_];
6772
6773 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6774 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6775 [prompt_ setBackgroundColor:[UIColor clearColor]];
6776 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6777 [self addSubview:prompt_];
6778
6779 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6780 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6781 [(UIProgressBar *) progress_ setStyle:0];
6782 [self addSubview:progress_];
6783
6784 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6785 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6786 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6787 [cancel_ setBarStyle:barstyle];
6788
6789 [self positionViews];
6790 } return self;
6791 }
6792
6793 - (void) setCancellable:(bool)cancellable {
6794 if (cancellable)
6795 [self addSubview:cancel_];
6796 else
6797 [cancel_ removeFromSuperview];
6798 }
6799
6800 - (void) start {
6801 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6802 [progress_ setProgress:0];
6803 }
6804
6805 - (void) stop {
6806 [self setCancellable:NO];
6807 }
6808
6809 - (void) setPrompt:(NSString *)prompt {
6810 [prompt_ setText:prompt];
6811 }
6812
6813 - (void) setProgress:(float)progress {
6814 [progress_ setProgress:progress];
6815 }
6816
6817 @end
6818 /* }}} */
6819
6820 /* Cydia Navigation Controller Interface {{{ */
6821 @interface UINavigationController (Cydia)
6822
6823 - (NSArray *) navigationURLCollection;
6824 - (void) unloadData;
6825
6826 @end
6827 /* }}} */
6828
6829 /* Cydia Tab Bar Controller {{{ */
6830 @interface CYTabBarController : UITabBarController <
6831 UITabBarControllerDelegate,
6832 ProgressDelegate
6833 > {
6834 _transient Database *database_;
6835 _H<RefreshBar, 1> refreshbar_;
6836
6837 bool dropped_;
6838 bool updating_;
6839 // XXX: ok, "updatedelegate_"?...
6840 _transient NSObject<CydiaDelegate> *updatedelegate_;
6841
6842 _H<UIViewController> remembered_;
6843 _transient UIViewController *transient_;
6844 }
6845
6846 - (NSArray *) navigationURLCollection;
6847 - (void) dropBar:(BOOL)animated;
6848 - (void) beginUpdate;
6849 - (void) raiseBar:(BOOL)animated;
6850 - (BOOL) updating;
6851 - (void) unloadData;
6852
6853 @end
6854
6855 @implementation CYTabBarController
6856
6857 - (void) didReceiveMemoryWarning {
6858 [super didReceiveMemoryWarning];
6859
6860 // presenting a UINavigationController on 2.x does not update its transitionView
6861 // it thereby will not allow its topViewController to be unloaded by memory pressure
6862 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6863 UIViewController *selected([self selectedViewController]);
6864 for (UINavigationController *controller in [self viewControllers])
6865 if (controller != selected)
6866 if (UIViewController *top = [controller topViewController])
6867 [top unloadView];
6868 }
6869 }
6870
6871 - (void) setUnselectedViewController:(UIViewController *)transient {
6872 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6873 if (transient != nil) {
6874 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6875 [self setSelectedIndex:0];
6876 } return;
6877 }
6878
6879 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6880 if (transient != nil) {
6881 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6882 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6883 transient = navigation;
6884
6885 if (transient_ == nil)
6886 remembered_ = [controllers objectAtIndex:0];
6887 transient_ = transient;
6888 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6889 [controllers replaceObjectAtIndex:0 withObject:transient_];
6890 [self setSelectedIndex:0];
6891 [self setViewControllers:controllers];
6892 [self concealTabBarSelection];
6893 } else if (remembered_ != nil) {
6894 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6895 transient_ = transient;
6896 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6897 remembered_ = nil;
6898 [self setViewControllers:controllers];
6899 [self revealTabBarSelection];
6900 }
6901 }
6902
6903 - (UIViewController *) unselectedViewController {
6904 return transient_;
6905 }
6906
6907 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6908 if ([self unselectedViewController])
6909 [self setUnselectedViewController:nil];
6910
6911 // presenting a UINavigationController on 2.x does not update its transitionView
6912 // if this view was unloaded, the tranitionView may currently be presenting nothing
6913 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6914 UINavigationController *navigation((UINavigationController *) viewController);
6915 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6916 [navigation popViewControllerAnimated:NO];
6917 }
6918 }
6919
6920 - (NSArray *) navigationURLCollection {
6921 NSMutableArray *items([NSMutableArray array]);
6922
6923 // XXX: Should this deal with transient view controllers?
6924 for (id navigation in [self viewControllers]) {
6925 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6926 if (stack != nil)
6927 [items addObject:stack];
6928 }
6929
6930 return items;
6931 }
6932
6933 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6934 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6935 [self setUnselectedViewController:nil];
6936 else
6937 [super dismissModalViewControllerAnimated:YES];
6938 }
6939
6940 - (void) unloadData {
6941 [super unloadData];
6942
6943 for (UINavigationController *controller in [self viewControllers])
6944 [controller unloadData];
6945
6946 if (UIViewController *selected = [self selectedViewController])
6947 [selected reloadData];
6948
6949 if (UIViewController *unselected = [self unselectedViewController]) {
6950 [unselected unloadData];
6951 [unselected reloadData];
6952 }
6953 }
6954
6955 - (void) dealloc {
6956 [[NSNotificationCenter defaultCenter] removeObserver:self];
6957
6958 [super dealloc];
6959 }
6960
6961 - (id) initWithDatabase:(Database *)database {
6962 if ((self = [super init]) != nil) {
6963 database_ = database;
6964 [self setDelegate:self];
6965
6966 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6967 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6968
6969 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6970 } return self;
6971 }
6972
6973 - (void) setUpdate:(NSDate *)date {
6974 [self beginUpdate];
6975 }
6976
6977 - (void) beginUpdate {
6978 [(RefreshBar *) refreshbar_ start];
6979 [self dropBar:YES];
6980
6981 [updatedelegate_ retainNetworkActivityIndicator];
6982 updating_ = true;
6983
6984 [NSThread
6985 detachNewThreadSelector:@selector(performUpdate)
6986 toTarget:self
6987 withObject:nil
6988 ];
6989 }
6990
6991 - (void) performUpdate {
6992 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6993
6994 Status status;
6995 status.setDelegate(self);
6996 [database_ updateWithStatus:status];
6997
6998 [self
6999 performSelectorOnMainThread:@selector(completeUpdate)
7000 withObject:nil
7001 waitUntilDone:NO
7002 ];
7003
7004 [pool release];
7005 }
7006
7007 - (void) stopUpdateWithSelector:(SEL)selector {
7008 updating_ = false;
7009 [updatedelegate_ releaseNetworkActivityIndicator];
7010
7011 [self raiseBar:YES];
7012 [refreshbar_ stop];
7013
7014 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7015 }
7016
7017 - (void) completeUpdate {
7018 if (!updating_)
7019 return;
7020 [self stopUpdateWithSelector:@selector(reloadData)];
7021 }
7022
7023 - (void) cancelUpdate {
7024 [self stopUpdateWithSelector:@selector(updateData)];
7025 }
7026
7027 - (void) cancelPressed {
7028 [self cancelUpdate];
7029 }
7030
7031 - (BOOL) updating {
7032 return updating_;
7033 }
7034
7035 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7036 [refreshbar_ setPrompt:[event compoundMessage]];
7037 }
7038
7039 - (bool) isProgressCancelled {
7040 return !updating_;
7041 }
7042
7043 - (void) setProgressCancellable:(NSNumber *)cancellable {
7044 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7045 }
7046
7047 - (void) setProgressPercent:(NSNumber *)percent {
7048 [refreshbar_ setProgress:[percent floatValue]];
7049 }
7050
7051 - (void) setProgressStatus:(NSDictionary *)status {
7052 if (status != nil)
7053 [self setProgressPercent:[status objectForKey:@"Percent"]];
7054 }
7055
7056 - (void) setUpdateDelegate:(id)delegate {
7057 updatedelegate_ = delegate;
7058 }
7059
7060 - (UIView *) transitionView {
7061 if ([self respondsToSelector:@selector(_transitionView)])
7062 return [self _transitionView];
7063 else
7064 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7065 }
7066
7067 - (void) dropBar:(BOOL)animated {
7068 if (dropped_)
7069 return;
7070 dropped_ = true;
7071
7072 UIView *transition([self transitionView]);
7073 [[self view] addSubview:refreshbar_];
7074
7075 CGRect barframe([refreshbar_ frame]);
7076
7077 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7078 barframe.origin.y = CYStatusBarHeight();
7079 else
7080 barframe.origin.y = 0;
7081
7082 [refreshbar_ setFrame:barframe];
7083
7084 if (animated)
7085 [UIView beginAnimations:nil context:NULL];
7086
7087 CGRect viewframe = [transition frame];
7088 viewframe.origin.y += barframe.size.height;
7089 viewframe.size.height -= barframe.size.height;
7090 [transition setFrame:viewframe];
7091
7092 if (animated)
7093 [UIView commitAnimations];
7094
7095 // Ensure bar has the proper width for our view, it might have changed
7096 barframe.size.width = viewframe.size.width;
7097 [refreshbar_ setFrame:barframe];
7098 }
7099
7100 - (void) raiseBar:(BOOL)animated {
7101 if (!dropped_)
7102 return;
7103 dropped_ = false;
7104
7105 UIView *transition([self transitionView]);
7106 [refreshbar_ removeFromSuperview];
7107
7108 CGRect barframe([refreshbar_ frame]);
7109
7110 if (animated)
7111 [UIView beginAnimations:nil context:NULL];
7112
7113 CGRect viewframe = [transition frame];
7114 viewframe.origin.y -= barframe.size.height;
7115 viewframe.size.height += barframe.size.height;
7116 [transition setFrame:viewframe];
7117
7118 if (animated)
7119 [UIView commitAnimations];
7120 }
7121
7122 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7123 bool dropped(dropped_);
7124
7125 if (dropped)
7126 [self raiseBar:NO];
7127
7128 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7129
7130 if (dropped)
7131 [self dropBar:NO];
7132 }
7133
7134 - (void) statusBarFrameChanged:(NSNotification *)notification {
7135 if (dropped_) {
7136 [self raiseBar:NO];
7137 [self dropBar:NO];
7138 }
7139 }
7140
7141 @end
7142 /* }}} */
7143
7144 /* Cydia Navigation Controller Implementation {{{ */
7145 @implementation UINavigationController (Cydia)
7146
7147 - (NSArray *) navigationURLCollection {
7148 NSMutableArray *stack([NSMutableArray array]);
7149
7150 for (CyteViewController *controller in [self viewControllers]) {
7151 NSString *url = [[controller navigationURL] absoluteString];
7152 if (url != nil)
7153 [stack addObject:url];
7154 }
7155
7156 return stack;
7157 }
7158
7159 - (void) reloadData {
7160 [super reloadData];
7161
7162 UIViewController *visible([self visibleViewController]);
7163 if (visible != nil)
7164 [visible reloadData];
7165
7166 // on the iPad, this view controller is ALSO visible. :(
7167 if (IsWildcat_)
7168 if (UIViewController *top = [self topViewController])
7169 if (top != visible)
7170 [top reloadData];
7171 }
7172
7173 - (void) unloadData {
7174 for (CyteViewController *page in [self viewControllers])
7175 [page unloadData];
7176
7177 [super unloadData];
7178 }
7179
7180 @end
7181 /* }}} */
7182
7183 /* Cydia:// Protocol {{{ */
7184 @interface CydiaURLProtocol : NSURLProtocol {
7185 }
7186
7187 @end
7188
7189 @implementation CydiaURLProtocol
7190
7191 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7192 NSURL *url([request URL]);
7193 if (url == nil)
7194 return NO;
7195
7196 NSString *scheme([[url scheme] lowercaseString]);
7197 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7198 return YES;
7199 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7200 return YES;
7201
7202 return NO;
7203 }
7204
7205 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7206 return request;
7207 }
7208
7209 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7210 id<NSURLProtocolClient> client([self client]);
7211 if (icon == nil)
7212 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7213 else {
7214 NSData *data(UIImagePNGRepresentation(icon));
7215
7216 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7217 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7218 [client URLProtocol:self didLoadData:data];
7219 [client URLProtocolDidFinishLoading:self];
7220 }
7221 }
7222
7223 - (void) startLoading {
7224 id<NSURLProtocolClient> client([self client]);
7225 NSURLRequest *request([self request]);
7226
7227 NSURL *url([request URL]);
7228 NSString *href([url absoluteString]);
7229 NSString *scheme([[url scheme] lowercaseString]);
7230
7231 NSString *path;
7232
7233 if ([scheme isEqualToString:@"cydia"])
7234 path = [href substringFromIndex:8];
7235 else if ([scheme isEqualToString:@"about"])
7236 path = [href substringFromIndex:12];
7237 else _assert(false);
7238
7239 NSRange slash([path rangeOfString:@"/"]);
7240
7241 NSString *command;
7242 if (slash.location == NSNotFound) {
7243 command = path;
7244 path = nil;
7245 } else {
7246 command = [path substringToIndex:slash.location];
7247 path = [path substringFromIndex:(slash.location + 1)];
7248 }
7249
7250 Database *database([Database sharedInstance]);
7251
7252 if ([command isEqualToString:@"package-icon"]) {
7253 if (path == nil)
7254 goto fail;
7255 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7256 Package *package([database packageWithName:path]);
7257 if (package == nil)
7258 goto fail;
7259 [package parse];
7260 UIImage *icon([package icon]);
7261 [self _returnPNGWithImage:icon forRequest:request];
7262 } else if ([command isEqualToString:@"uikit-image"]) {
7263 if (path == nil)
7264 goto fail;
7265 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7266 UIImage *icon(_UIImageWithName(path));
7267 [self _returnPNGWithImage:icon forRequest:request];
7268 } else if ([command isEqualToString:@"section-icon"]) {
7269 if (path == nil)
7270 goto fail;
7271 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7272 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7273 if (icon == nil)
7274 icon = [UIImage applicationImageNamed:@"unknown.png"];
7275 [self _returnPNGWithImage:icon forRequest:request];
7276 } else fail: {
7277 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7278 }
7279 }
7280
7281 - (void) stopLoading {
7282 }
7283
7284 @end
7285 /* }}} */
7286
7287 /* Section Controller {{{ */
7288 @interface SectionController : FilteredPackageListController {
7289 _H<IndirectDelegate, 1> indirect_;
7290 _H<CydiaObject> cydia_;
7291 _H<NSString> section_;
7292 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7293 }
7294
7295 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7296
7297 @end
7298
7299 @implementation SectionController
7300
7301 - (NSURL *) referrerURL {
7302 NSString *name = section_;
7303 if (name == nil)
7304 name = @"all";
7305
7306 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7307 }
7308
7309 - (NSURL *) navigationURL {
7310 NSString *name = section_;
7311 if (name == nil)
7312 name = @"all";
7313
7314 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7315 }
7316
7317 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7318 NSString *title;
7319 if (name == nil)
7320 title = UCLocalize("ALL_PACKAGES");
7321 else if (![name isEqual:@""])
7322 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7323 else
7324 title = UCLocalize("NO_SECTION");
7325
7326 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7327 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7328 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7329 section_ = name;
7330 } return self;
7331 }
7332
7333 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7334 return [super numberOfSectionsInTableView:list] + 1;
7335 }
7336
7337 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7338 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7339 }
7340
7341 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7342 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7343 }
7344
7345 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7346 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7347 }
7348
7349 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7350 if ([path section] != 0)
7351 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7352
7353 return promoted_[[path row]];
7354 }
7355
7356 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7357 if ([path section] != 0)
7358 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7359 }
7360
7361 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7362 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7363 return section == 0 ? 0 : section + 1;
7364 }
7365
7366 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7367 NSURL *url([request URL]);
7368 if (url == nil)
7369 return;
7370
7371 if ([frame isEqualToString:@"_open"])
7372 [delegate_ openURL:url];
7373 else {
7374 WebFrame *frame(nil);
7375 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7376 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7377 if (frame == nil)
7378 frame = [view mainFrame];
7379
7380 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7381
7382 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7383 [controller setDelegate:delegate_];
7384 [[self navigationController] pushViewController:controller animated:YES];
7385 }
7386
7387 [listener ignore];
7388 }
7389
7390 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7391 return [CydiaWebViewController requestWithHeaders:request];
7392 }
7393
7394 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7395 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7396 }
7397
7398 - (void) loadView {
7399 [super loadView];
7400
7401 // XXX: this code is horrible. I mean, wtf Jay?
7402 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7403 promoted_.resize(1);
7404
7405 for (unsigned i(0); i != promoted_.size(); ++i) {
7406 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7407 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7408 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7409 ]]
7410
7411 cachePolicy:NSURLRequestUseProtocolCachePolicy
7412 timeoutInterval:120
7413 ]]);
7414
7415 [promoted setDelegate:self];
7416 promoted_[i] = promoted;
7417 }
7418 }
7419 }
7420
7421 - (void) setDelegate:(id)delegate {
7422 [super setDelegate:delegate];
7423 [cydia_ setDelegate:delegate];
7424 }
7425
7426 - (void) releaseSubviews {
7427 promoted_.clear();
7428 [super releaseSubviews];
7429 }
7430
7431 @end
7432 /* }}} */
7433 /* Sections Controller {{{ */
7434 @interface SectionsController : CyteViewController <
7435 UITableViewDataSource,
7436 UITableViewDelegate
7437 > {
7438 _transient Database *database_;
7439 _H<NSMutableArray> sections_;
7440 _H<NSMutableArray> filtered_;
7441 _H<UITableView, 2> list_;
7442 }
7443
7444 - (id) initWithDatabase:(Database *)database;
7445 - (void) editButtonClicked;
7446
7447 @end
7448
7449 @implementation SectionsController
7450
7451 - (NSURL *) navigationURL {
7452 return [NSURL URLWithString:@"cydia://sections"];
7453 }
7454
7455 - (void) updateNavigationItem {
7456 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7457 if ([sections_ count] == 0) {
7458 [[self navigationItem] setRightBarButtonItem:nil];
7459 } else {
7460 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7461 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7462 target:self
7463 action:@selector(editButtonClicked)
7464 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7465 }
7466 }
7467
7468 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7469 [super setEditing:editing animated:animated];
7470
7471 if (editing)
7472 [list_ reloadData];
7473 else
7474 [delegate_ updateData];
7475
7476 [self updateNavigationItem];
7477 }
7478
7479 - (void) viewDidAppear:(BOOL)animated {
7480 [super viewDidAppear:animated];
7481 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7482 }
7483
7484 - (void) viewWillDisappear:(BOOL)animated {
7485 [super viewWillDisappear:animated];
7486 [self setEditing:NO];
7487 }
7488
7489 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7490 Section *section = nil;
7491 int index = [indexPath row];
7492 if (![self isEditing]) {
7493 index -= 1;
7494 if (index >= 0)
7495 section = [filtered_ objectAtIndex:index];
7496 } else {
7497 section = [sections_ objectAtIndex:index];
7498 }
7499 return section;
7500 }
7501
7502 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7503 if ([self isEditing])
7504 return [sections_ count];
7505 else
7506 return [filtered_ count] + 1;
7507 }
7508
7509 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7510 return 45.0f;
7511 }*/
7512
7513 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7514 static NSString *reuseIdentifier = @"SectionCell";
7515
7516 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7517 if (cell == nil)
7518 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7519
7520 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7521
7522 return cell;
7523 }
7524
7525 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7526 if ([self isEditing])
7527 return;
7528
7529 Section *section = [self sectionAtIndexPath:indexPath];
7530
7531 SectionController *controller = [[[SectionController alloc]
7532 initWithDatabase:database_
7533 section:[section name]
7534 ] autorelease];
7535 [controller setDelegate:delegate_];
7536
7537 [[self navigationController] pushViewController:controller animated:YES];
7538 }
7539
7540 - (void) loadView {
7541 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7542 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7543 [list_ setRowHeight:45.0f];
7544 [(UITableView *) list_ setDataSource:self];
7545 [list_ setDelegate:self];
7546 [self setView:list_];
7547 }
7548
7549 - (void) viewDidLoad {
7550 [super viewDidLoad];
7551
7552 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7553 }
7554
7555 - (void) releaseSubviews {
7556 list_ = nil;
7557
7558 sections_ = nil;
7559 filtered_ = nil;
7560
7561 [super releaseSubviews];
7562 }
7563
7564 - (id) initWithDatabase:(Database *)database {
7565 if ((self = [super init]) != nil) {
7566 database_ = database;
7567 } return self;
7568 }
7569
7570 - (void) reloadData {
7571 [super reloadData];
7572
7573 NSArray *packages = [database_ packages];
7574
7575 sections_ = [NSMutableArray arrayWithCapacity:16];
7576 filtered_ = [NSMutableArray arrayWithCapacity:16];
7577
7578 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7579
7580 _trace();
7581 for (Package *package in packages) {
7582 NSString *name([package section]);
7583 NSString *key(name == nil ? @"" : name);
7584
7585 Section *section;
7586
7587 _profile(SectionsView$reloadData$Section)
7588 section = [sections objectForKey:key];
7589 if (section == nil) {
7590 _profile(SectionsView$reloadData$Section$Allocate)
7591 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7592 [sections setObject:section forKey:key];
7593 _end
7594 }
7595 _end
7596
7597 [section addToCount];
7598
7599 _profile(SectionsView$reloadData$Filter)
7600 if (![package valid] || ![package visible])
7601 continue;
7602 _end
7603
7604 [section addToRow];
7605 }
7606 _trace();
7607
7608 [sections_ addObjectsFromArray:[sections allValues]];
7609
7610 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7611
7612 for (Section *section in (id) sections_) {
7613 size_t count([section row]);
7614 if (count == 0)
7615 continue;
7616
7617 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7618 [section setCount:count];
7619 [filtered_ addObject:section];
7620 }
7621
7622 [self updateNavigationItem];
7623 [list_ reloadData];
7624 _trace();
7625 }
7626
7627 - (void) editButtonClicked {
7628 [self setEditing:![self isEditing] animated:YES];
7629 }
7630
7631 @end
7632 /* }}} */
7633
7634 /* Changes Controller {{{ */
7635 @interface ChangesController : CyteViewController <
7636 UITableViewDataSource,
7637 UITableViewDelegate
7638 > {
7639 _transient Database *database_;
7640 unsigned era_;
7641 _H<NSArray> packages_;
7642 _H<NSMutableArray> sections_;
7643 _H<UITableView, 2> list_;
7644 _H<CyteWebView, 1> dickbar_;
7645 unsigned upgrades_;
7646 _H<IndirectDelegate, 1> indirect_;
7647 _H<CydiaObject> cydia_;
7648 }
7649
7650 - (id) initWithDatabase:(Database *)database;
7651
7652 @end
7653
7654 @implementation ChangesController
7655
7656 - (NSURL *) navigationURL {
7657 return [NSURL URLWithString:@"cydia://changes"];
7658 }
7659
7660 - (void) viewDidAppear:(BOOL)animated {
7661 [super viewDidAppear:animated];
7662 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7663 }
7664
7665 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7666 NSInteger count([sections_ count]);
7667 return count == 0 ? 1 : count;
7668 }
7669
7670 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7671 if ([sections_ count] == 0)
7672 return nil;
7673 return [[sections_ objectAtIndex:section] name];
7674 }
7675
7676 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7677 if ([sections_ count] == 0)
7678 return 0;
7679 return [[sections_ objectAtIndex:section] count];
7680 }
7681
7682 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7683 @synchronized (database_) {
7684 if ([database_ era] != era_)
7685 return nil;
7686
7687 NSUInteger sectionIndex([path section]);
7688 if (sectionIndex >= [sections_ count])
7689 return nil;
7690 Section *section([sections_ objectAtIndex:sectionIndex]);
7691 NSInteger row([path row]);
7692 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7693 } }
7694
7695 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7696 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7697 if (cell == nil)
7698 cell = [[[PackageCell alloc] init] autorelease];
7699
7700 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7701 [cell setPackage:package asSummary:false];
7702 return cell;
7703 }
7704
7705 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7706 Package *package([self packageAtIndexPath:path]);
7707 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7708 [view setDelegate:delegate_];
7709 [[self navigationController] pushViewController:view animated:YES];
7710 return path;
7711 }
7712
7713 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7714 NSString *context([alert context]);
7715
7716 if ([context isEqualToString:@"norefresh"])
7717 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7718 }
7719
7720 - (void) refreshButtonClicked {
7721 if (IsReachable("cydia.saurik.com")) {
7722 [delegate_ beginUpdate];
7723 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7724 } else {
7725 UIAlertView *alert = [[[UIAlertView alloc]
7726 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7727 message:@"Host Unreachable" // XXX: Localize
7728 delegate:self
7729 cancelButtonTitle:UCLocalize("OK")
7730 otherButtonTitles:nil
7731 ] autorelease];
7732
7733 [alert setContext:@"norefresh"];
7734 [alert show];
7735 }
7736 }
7737
7738 - (void) upgradeButtonClicked {
7739 [delegate_ distUpgrade];
7740 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7741 }
7742
7743 - (void) loadView {
7744 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7745 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7746 [self setView:view];
7747
7748 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7749 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7750 [list_ setRowHeight:73];
7751 [(UITableView *) list_ setDataSource:self];
7752 [list_ setDelegate:self];
7753 [view addSubview:list_];
7754
7755 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7756 CGRect dickframe([view bounds]);
7757 dickframe.size.height = 44;
7758
7759 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7760 [dickbar_ setDelegate:self];
7761 [view addSubview:dickbar_];
7762
7763 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7764 [dickbar_ setScalesPageToFit:YES];
7765
7766 UIWebDocumentView *document([dickbar_ _documentView]);
7767 [document setBackgroundColor:[UIColor clearColor]];
7768 [document setDrawsBackground:NO];
7769
7770 WebView *webview([document webView]);
7771 [webview setShouldUpdateWhileOffscreen:NO];
7772
7773 UIScrollView *scroller([dickbar_ scrollView]);
7774 [scroller setScrollingEnabled:NO];
7775 [scroller setFixedBackgroundPattern:YES];
7776 [scroller setBackgroundColor:[UIColor clearColor]];
7777
7778 WebPreferences *preferences([webview preferences]);
7779 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7780 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7781 [preferences setOfflineWebApplicationCacheEnabled:YES];
7782
7783 [dickbar_ loadRequest:[NSURLRequest
7784 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7785 cachePolicy:NSURLRequestUseProtocolCachePolicy
7786 timeoutInterval:120
7787 ]];
7788
7789 UIEdgeInsets inset = {44, 0, 0, 0};
7790 [list_ setContentInset:inset];
7791
7792 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7793 }
7794 }
7795
7796 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7797 NSURL *url([request URL]);
7798 if (url == nil)
7799 return;
7800
7801 if ([frame isEqualToString:@"_open"])
7802 [delegate_ openURL:url];
7803 else {
7804 WebFrame *frame(nil);
7805 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7806 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7807 if (frame == nil)
7808 frame = [view mainFrame];
7809
7810 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7811
7812 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7813 [controller setDelegate:delegate_];
7814 [[self navigationController] pushViewController:controller animated:YES];
7815 }
7816
7817 [listener ignore];
7818 }
7819
7820 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7821 return [CydiaWebViewController requestWithHeaders:request];
7822 }
7823
7824 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7825 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7826 }
7827
7828 - (void) setDelegate:(id)delegate {
7829 [super setDelegate:delegate];
7830 [cydia_ setDelegate:delegate];
7831 }
7832
7833 - (void) viewDidLoad {
7834 [super viewDidLoad];
7835
7836 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7837 }
7838
7839 - (void) releaseSubviews {
7840 list_ = nil;
7841
7842 packages_ = nil;
7843 sections_ = nil;
7844 dickbar_ = nil;
7845
7846 [super releaseSubviews];
7847 }
7848
7849 - (id) initWithDatabase:(Database *)database {
7850 if ((self = [super init]) != nil) {
7851 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7852 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7853 database_ = database;
7854 } return self;
7855 }
7856
7857 - (NSMutableArray *) _reloadPackages {
7858 @synchronized (database_) {
7859 era_ = [database_ era];
7860 NSArray *packages([database_ packages]);
7861
7862 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7863
7864 _trace();
7865 _profile(ChangesController$_reloadPackages$Filter)
7866 for (Package *package in packages)
7867 if ([package upgradableAndEssential:YES] || [package visible])
7868 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7869 _end
7870 _trace();
7871 _profile(ChangesController$_reloadPackages$radixSort)
7872 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7873 _end
7874 _trace();
7875
7876 return filtered;
7877 } }
7878
7879 - (void) _reloadData {
7880 NSArray *packages;
7881
7882 reload:
7883 if (true) {
7884 UIProgressHUD *hud([delegate_ addProgressHUD]);
7885 [hud setText:UCLocalize("LOADING")];
7886 //NSLog(@"HUD:%@::%@", delegate_, hud);
7887 packages = [self yieldToSelector:@selector(_reloadPackages)];
7888 [delegate_ removeProgressHUD:hud];
7889 } else {
7890 packages = [self _reloadPackages];
7891 }
7892
7893 @synchronized (database_) {
7894 if (era_ != [database_ era])
7895 goto reload;
7896
7897 packages_ = packages;
7898 sections_ = [NSMutableArray arrayWithCapacity:16];
7899
7900 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7901 Section *ignored = nil;
7902 Section *section = nil;
7903 time_t last = 0;
7904
7905 upgrades_ = 0;
7906 bool unseens = false;
7907
7908 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7909
7910 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7911 Package *package = [packages_ objectAtIndex:offset];
7912
7913 BOOL uae = [package upgradableAndEssential:YES];
7914
7915 if (!uae) {
7916 unseens = true;
7917 time_t seen([package seen]);
7918
7919 if (section == nil || last != seen) {
7920 last = seen;
7921
7922 NSString *name;
7923 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7924 [name autorelease];
7925
7926 _profile(ChangesController$reloadData$Allocate)
7927 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7928 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7929 [sections_ addObject:section];
7930 _end
7931 }
7932
7933 [section addToCount];
7934 } else if ([package ignored]) {
7935 if (ignored == nil) {
7936 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7937 }
7938 [ignored addToCount];
7939 } else {
7940 ++upgrades_;
7941 [upgradable addToCount];
7942 }
7943 }
7944 _trace();
7945
7946 CFRelease(formatter);
7947
7948 if (unseens) {
7949 Section *last = [sections_ lastObject];
7950 size_t count = [last count];
7951 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7952 [sections_ removeLastObject];
7953 }
7954
7955 if ([ignored count] != 0)
7956 [sections_ insertObject:ignored atIndex:0];
7957 if (upgrades_ != 0)
7958 [sections_ insertObject:upgradable atIndex:0];
7959
7960 [list_ reloadData];
7961
7962 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7963 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7964 style:UIBarButtonItemStylePlain
7965 target:self
7966 action:@selector(upgradeButtonClicked)
7967 ] autorelease]) animated:YES];
7968
7969 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7970 initWithTitle:UCLocalize("REFRESH")
7971 style:UIBarButtonItemStylePlain
7972 target:self
7973 action:@selector(refreshButtonClicked)
7974 ] autorelease]) animated:YES];
7975
7976 PrintTimes();
7977 } }
7978
7979 - (void) reloadData {
7980 [super reloadData];
7981 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7982 }
7983
7984 @end
7985 /* }}} */
7986 /* Search Controller {{{ */
7987 @interface SearchController : FilteredPackageListController <
7988 UISearchBarDelegate
7989 > {
7990 _H<UISearchBar, 1> search_;
7991 BOOL searchloaded_;
7992 }
7993
7994 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7995 - (void) reloadData;
7996
7997 @end
7998
7999 @implementation SearchController
8000
8001 - (NSURL *) referrerURL {
8002 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8003 }
8004
8005 - (NSURL *) navigationURL {
8006 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8007 return [NSURL URLWithString:@"cydia://search"];
8008 else
8009 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8010 }
8011
8012 - (NSArray *) termsForQuery:(NSString *)query {
8013 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8014 for (NSString *component in [query componentsSeparatedByString:@" "])
8015 if ([component length] != 0)
8016 [terms addObject:component];
8017
8018 return terms;
8019 }
8020
8021 - (void) useSearch {
8022 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8023 [self clearData];
8024 [self reloadData];
8025 }
8026
8027 - (void) viewWillAppear:(BOOL)animated {
8028 [super viewWillAppear:animated];
8029
8030 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
8031 [self useSearch];
8032 }
8033
8034 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8035 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8036 [self clearData];
8037 [self reloadData];
8038 }
8039
8040 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8041 [search_ resignFirstResponder];
8042 [self useSearch];
8043 }
8044
8045 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8046 [search_ setText:@""];
8047 [self searchBarButtonClicked:searchBar];
8048 }
8049
8050 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8051 [self searchBarButtonClicked:searchBar];
8052 }
8053
8054 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8055 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8056 [self reloadData];
8057 }
8058
8059 - (bool) shouldYield {
8060 return YES;
8061 }
8062
8063 - (bool) shouldBlock {
8064 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8065 }
8066
8067 - (bool) isSummarized {
8068 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8069 }
8070
8071 - (bool) showsSections {
8072 return false;
8073 }
8074
8075 - (NSMutableArray *) _reloadPackages {
8076 NSMutableArray *packages([super _reloadPackages]);
8077 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8078 [packages radixSortUsingSelector:@selector(rank)];
8079 return packages;
8080 }
8081
8082 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8083 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8084 search_ = [[[UISearchBar alloc] init] autorelease];
8085 [search_ setDelegate:self];
8086
8087 if (query != nil)
8088 [search_ setText:query];
8089 } return self;
8090 }
8091
8092 - (void) viewDidAppear:(BOOL)animated {
8093 [super viewDidAppear:animated];
8094
8095 if (!searchloaded_) {
8096 searchloaded_ = YES;
8097 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8098 [search_ layoutSubviews];
8099 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8100
8101 UITextField *textField;
8102 if ([search_ respondsToSelector:@selector(searchField)])
8103 textField = [search_ searchField];
8104 else
8105 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8106
8107 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8108 [textField setEnablesReturnKeyAutomatically:NO];
8109 [[self navigationItem] setTitleView:textField];
8110 }
8111 }
8112
8113 - (void) reloadData {
8114 id object([search_ text]);
8115 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8116 object = [self termsForQuery:object];
8117
8118 [self setObject:object];
8119 [self resetCursor];
8120
8121 [super reloadData];
8122 }
8123
8124 - (void) didSelectPackage:(Package *)package {
8125 [search_ resignFirstResponder];
8126 [super didSelectPackage:package];
8127 }
8128
8129 @end
8130 /* }}} */
8131 /* Package Settings Controller {{{ */
8132 @interface PackageSettingsController : CyteViewController <
8133 UITableViewDataSource,
8134 UITableViewDelegate
8135 > {
8136 _transient Database *database_;
8137 _H<NSString> name_;
8138 _H<Package> package_;
8139 _H<UITableView, 2> table_;
8140 _H<UISwitch> subscribedSwitch_;
8141 _H<UISwitch> ignoredSwitch_;
8142 _H<UITableViewCell> subscribedCell_;
8143 _H<UITableViewCell> ignoredCell_;
8144 }
8145
8146 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8147
8148 @end
8149
8150 @implementation PackageSettingsController
8151
8152 - (NSURL *) navigationURL {
8153 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8154 }
8155
8156 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8157 if (package_ == nil)
8158 return 0;
8159
8160 if ([package_ installed] == nil)
8161 return 1;
8162 else
8163 return 2;
8164 }
8165
8166 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8167 if (package_ == nil)
8168 return 0;
8169
8170 // both sections contain just one item right now.
8171 return 1;
8172 }
8173
8174 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8175 return nil;
8176 }
8177
8178 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8179 if (section == 0)
8180 return UCLocalize("SHOW_ALL_CHANGES_EX");
8181 else
8182 return UCLocalize("IGNORE_UPGRADES_EX");
8183 }
8184
8185 - (void) onSubscribed:(id)control {
8186 bool value([control isOn]);
8187 if (package_ == nil)
8188 return;
8189 if ([package_ setSubscribed:value])
8190 [delegate_ updateData];
8191 }
8192
8193 - (void) _updateIgnored {
8194 const char *package([name_ UTF8String]);
8195 bool on([ignoredSwitch_ isOn]);
8196
8197 pid_t pid(ExecFork());
8198 if (pid == 0) {
8199 FILE *dpkg(popen("dpkg --set-selections", "w"));
8200 fwrite(package, strlen(package), 1, dpkg);
8201
8202 if (on)
8203 fwrite(" hold\n", 6, 1, dpkg);
8204 else
8205 fwrite(" install\n", 9, 1, dpkg);
8206
8207 pclose(dpkg);
8208
8209 exit(0);
8210 _assert(false);
8211 }
8212
8213 ReapZombie(pid);
8214 }
8215
8216 - (void) onIgnored:(id)control {
8217 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8218 [invocation setTarget:self];
8219 [invocation setSelector:@selector(_updateIgnored)];
8220
8221 [delegate_ reloadDataWithInvocation:invocation];
8222 }
8223
8224 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8225 if (package_ == nil)
8226 return nil;
8227
8228 switch ([indexPath section]) {
8229 case 0: return subscribedCell_;
8230 case 1: return ignoredCell_;
8231
8232 _nodefault
8233 }
8234
8235 return nil;
8236 }
8237
8238 - (void) loadView {
8239 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8240 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8241 [self setView:view];
8242
8243 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8244 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8245 [(UITableView *) table_ setDataSource:self];
8246 [table_ setDelegate:self];
8247 [view addSubview:table_];
8248
8249 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8250 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8251 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8252
8253 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8254 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8255 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8256
8257 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8258 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8259 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8260 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8261
8262 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8263 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8264 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8265 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8266 }
8267
8268 - (void) viewDidLoad {
8269 [super viewDidLoad];
8270
8271 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8272 }
8273
8274 - (void) releaseSubviews {
8275 ignoredCell_ = nil;
8276 subscribedCell_ = nil;
8277 table_ = nil;
8278 ignoredSwitch_ = nil;
8279 subscribedSwitch_ = nil;
8280
8281 [super releaseSubviews];
8282 }
8283
8284 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8285 if ((self = [super init]) != nil) {
8286 database_ = database;
8287 name_ = package;
8288 } return self;
8289 }
8290
8291 - (void) reloadData {
8292 [super reloadData];
8293
8294 package_ = [database_ packageWithName:name_];
8295
8296 if (package_ != nil) {
8297 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8298 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8299 } // XXX: what now, G?
8300
8301 [table_ reloadData];
8302 }
8303
8304 @end
8305 /* }}} */
8306
8307 /* Installed Controller {{{ */
8308 @interface InstalledController : FilteredPackageListController {
8309 BOOL expert_;
8310 }
8311
8312 - (id) initWithDatabase:(Database *)database;
8313
8314 - (void) updateRoleButton;
8315 - (void) queueStatusDidChange;
8316
8317 @end
8318
8319 @implementation InstalledController
8320
8321 - (NSURL *) referrerURL {
8322 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8323 }
8324
8325 - (NSURL *) navigationURL {
8326 return [NSURL URLWithString:@"cydia://installed"];
8327 }
8328
8329 - (id) initWithDatabase:(Database *)database {
8330 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8331 [self updateRoleButton];
8332 [self queueStatusDidChange];
8333 } return self;
8334 }
8335
8336 #if !AlwaysReload
8337 - (void) queueButtonClicked {
8338 [delegate_ queue];
8339 }
8340 #endif
8341
8342 - (void) queueStatusDidChange {
8343 #if !AlwaysReload
8344 if (IsWildcat_) {
8345 if (Queuing_) {
8346 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8347 initWithTitle:UCLocalize("QUEUE")
8348 style:UIBarButtonItemStyleDone
8349 target:self
8350 action:@selector(queueButtonClicked)
8351 ] autorelease]];
8352 } else {
8353 [[self navigationItem] setLeftBarButtonItem:nil];
8354 }
8355 }
8356 #endif
8357 }
8358
8359 - (void) updateRoleButton {
8360 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8361 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8362 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8363 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8364 target:self
8365 action:@selector(roleButtonClicked)
8366 ] autorelease]];
8367 }
8368
8369 - (void) roleButtonClicked {
8370 [self setObject:[NSNumber numberWithBool:expert_]];
8371 [self reloadData];
8372 expert_ = !expert_;
8373
8374 [self updateRoleButton];
8375 }
8376
8377 @end
8378 /* }}} */
8379
8380 /* Source Cell {{{ */
8381 @interface SourceCell : CyteTableViewCell <
8382 CyteTableViewCellDelegate
8383 > {
8384 _H<NSURL> url_;
8385 _H<UIImage> icon_;
8386 _H<NSString> origin_;
8387 _H<NSString> label_;
8388 }
8389
8390 - (void) setSource:(Source *)source;
8391
8392 @end
8393
8394 @implementation SourceCell
8395
8396 - (void) _setImage:(NSArray *)data {
8397 if ([url_ isEqual:[data objectAtIndex:0]]) {
8398 icon_ = [data objectAtIndex:1];
8399 [content_ setNeedsDisplay];
8400 }
8401 }
8402
8403 - (void) _setSource:(NSURL *) url {
8404 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8405
8406 if (NSData *data = [NSURLConnection
8407 sendSynchronousRequest:[NSURLRequest
8408 requestWithURL:url
8409 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8410 //timeoutInterval:5
8411 ]
8412
8413 returningResponse:NULL
8414 error:NULL
8415 ])
8416 if (UIImage *image = [UIImage imageWithData:data])
8417 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8418
8419 [pool release];
8420 }
8421
8422 - (void) setSource:(Source *)source {
8423 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8424
8425 origin_ = [source name];
8426 label_ = [source rooturi];
8427
8428 [content_ setNeedsDisplay];
8429
8430 url_ = [source iconURL];
8431 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8432 }
8433
8434 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8435 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8436 UIView *content([self contentView]);
8437 CGRect bounds([content bounds]);
8438
8439 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8440 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8441 [content_ setBackgroundColor:[UIColor whiteColor]];
8442 [content addSubview:content_];
8443
8444 [content_ setDelegate:self];
8445 [content_ setOpaque:YES];
8446
8447 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8448 } return self;
8449 }
8450
8451 - (NSString *) accessibilityLabel {
8452 return label_;
8453 }
8454
8455 - (void) drawContentRect:(CGRect)rect {
8456 bool highlighted(highlighted_);
8457 float width(rect.size.width);
8458
8459 if (icon_ != nil) {
8460 CGRect rect;
8461 rect.size = [(UIImage *) icon_ size];
8462
8463 while (rect.size.width > 32 || rect.size.height > 32) {
8464 rect.size.width /= 2;
8465 rect.size.height /= 2;
8466 }
8467
8468 rect.origin.x = 25 - rect.size.width / 2;
8469 rect.origin.y = 25 - rect.size.height / 2;
8470
8471 [icon_ drawInRect:rect];
8472 }
8473
8474 if (highlighted)
8475 UISetColor(White_);
8476
8477 if (!highlighted)
8478 UISetColor(Black_);
8479 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8480
8481 if (!highlighted)
8482 UISetColor(Gray_);
8483 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8484 }
8485
8486 @end
8487 /* }}} */
8488 /* Source Controller {{{ */
8489 @interface SourceController : FilteredPackageListController {
8490 _transient Source *source_;
8491 _H<NSString> key_;
8492 }
8493
8494 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8495
8496 @end
8497
8498 @implementation SourceController
8499
8500 - (NSURL *) referrerURL {
8501 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8502 }
8503
8504 - (NSURL *) navigationURL {
8505 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8506 }
8507
8508 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8509 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8510 source_ = source;
8511 key_ = [source key];
8512 } return self;
8513 }
8514
8515 - (void) reloadData {
8516 source_ = [database_ sourceWithKey:key_];
8517 key_ = [source_ key];
8518 [self setObject:source_];
8519
8520 [[self navigationItem] setTitle:[source_ label]];
8521
8522 [super reloadData];
8523 }
8524
8525 @end
8526 /* }}} */
8527 /* Sources Controller {{{ */
8528 @interface SourcesController : CyteViewController <
8529 UITableViewDataSource,
8530 UITableViewDelegate
8531 > {
8532 _transient Database *database_;
8533 unsigned era_;
8534
8535 _H<UITableView, 2> list_;
8536 _H<NSMutableArray> sources_;
8537 int offset_;
8538
8539 _H<NSString> href_;
8540 _H<UIProgressHUD> hud_;
8541 _H<NSError> error_;
8542
8543 //NSURLConnection *installer_;
8544 NSURLConnection *trivial_;
8545 NSURLConnection *trivial_bz2_;
8546 NSURLConnection *trivial_gz_;
8547 //NSURLConnection *automatic_;
8548
8549 BOOL cydia_;
8550 }
8551
8552 - (id) initWithDatabase:(Database *)database;
8553 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8554
8555 @end
8556
8557 @implementation SourcesController
8558
8559 - (void) _releaseConnection:(NSURLConnection *)connection {
8560 if (connection != nil) {
8561 [connection cancel];
8562 //[connection setDelegate:nil];
8563 [connection release];
8564 }
8565 }
8566
8567 - (void) dealloc {
8568 //[self _releaseConnection:installer_];
8569 [self _releaseConnection:trivial_];
8570 [self _releaseConnection:trivial_gz_];
8571 [self _releaseConnection:trivial_bz2_];
8572 //[self _releaseConnection:automatic_];
8573
8574 [super dealloc];
8575 }
8576
8577 - (NSURL *) navigationURL {
8578 return [NSURL URLWithString:@"cydia://sources"];
8579 }
8580
8581 - (void) viewDidAppear:(BOOL)animated {
8582 [super viewDidAppear:animated];
8583 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8584 }
8585
8586 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8587 return 1;
8588 }
8589
8590 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8591 return nil;
8592 }
8593
8594 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8595 return [sources_ count];
8596 }
8597
8598 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8599 @synchronized (database_) {
8600 if ([database_ era] != era_)
8601 return nil;
8602
8603 return [sources_ objectAtIndex:[indexPath row]];
8604 } }
8605
8606 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8607 static NSString *cellIdentifier = @"SourceCell";
8608
8609 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8610 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8611 [cell setSource:[self sourceAtIndexPath:indexPath]];
8612 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8613
8614 return cell;
8615 }
8616
8617 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8618 Source *source = [self sourceAtIndexPath:indexPath];
8619
8620 SourceController *controller = [[[SourceController alloc]
8621 initWithDatabase:database_
8622 source:source
8623 ] autorelease];
8624
8625 [controller setDelegate:delegate_];
8626
8627 [[self navigationController] pushViewController:controller animated:YES];
8628 }
8629
8630 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8631 Source *source = [self sourceAtIndexPath:indexPath];
8632 return [source record] != nil;
8633 }
8634
8635 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8636 if (editingStyle == UITableViewCellEditingStyleDelete) {
8637 Source *source = [self sourceAtIndexPath:indexPath];
8638 [Sources_ removeObjectForKey:[source key]];
8639 [delegate_ syncData];
8640 }
8641 }
8642
8643 - (void) complete {
8644 [delegate_ addTrivialSource:href_];
8645 href_ = nil;
8646
8647 [delegate_ syncData];
8648 }
8649
8650 - (NSString *) getWarning {
8651 NSString *href(href_);
8652 NSRange colon([href rangeOfString:@"://"]);
8653 if (colon.location != NSNotFound)
8654 href = [href substringFromIndex:(colon.location + 3)];
8655 href = [href stringByAddingPercentEscapes];
8656 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8657
8658 NSURL *url([NSURL URLWithString:href]);
8659
8660 NSStringEncoding encoding;
8661 NSError *error(nil);
8662
8663 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8664 return [warning length] == 0 ? nil : warning;
8665 return nil;
8666 }
8667
8668 - (void) _endConnection:(NSURLConnection *)connection {
8669 // XXX: the memory management in this method is horribly awkward
8670
8671 NSURLConnection **field = NULL;
8672 if (connection == trivial_)
8673 field = &trivial_;
8674 else if (connection == trivial_bz2_)
8675 field = &trivial_bz2_;
8676 else if (connection == trivial_gz_)
8677 field = &trivial_gz_;
8678 _assert(field != NULL);
8679 [connection release];
8680 *field = nil;
8681
8682 if (
8683 trivial_ == nil &&
8684 trivial_bz2_ == nil &&
8685 trivial_gz_ == nil
8686 ) {
8687 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8688
8689 [delegate_ releaseNetworkActivityIndicator];
8690
8691 [delegate_ removeProgressHUD:hud_];
8692 hud_ = nil;
8693
8694 if (cydia_) {
8695 if (warning != nil) {
8696 UIAlertView *alert = [[[UIAlertView alloc]
8697 initWithTitle:UCLocalize("SOURCE_WARNING")
8698 message:warning
8699 delegate:self
8700 cancelButtonTitle:UCLocalize("CANCEL")
8701 otherButtonTitles:
8702 UCLocalize("ADD_ANYWAY"),
8703 nil
8704 ] autorelease];
8705
8706 [alert setContext:@"warning"];
8707 [alert setNumberOfRows:1];
8708 [alert show];
8709
8710 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8711 error_ = nil;
8712 return;
8713 }
8714
8715 [self complete];
8716 } else if (error_ != nil) {
8717 UIAlertView *alert = [[[UIAlertView alloc]
8718 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8719 message:[error_ localizedDescription]
8720 delegate:self
8721 cancelButtonTitle:UCLocalize("OK")
8722 otherButtonTitles:nil
8723 ] autorelease];
8724
8725 [alert setContext:@"urlerror"];
8726 [alert show];
8727
8728 href_ = nil;
8729 } else {
8730 UIAlertView *alert = [[[UIAlertView alloc]
8731 initWithTitle:UCLocalize("NOT_REPOSITORY")
8732 message:UCLocalize("NOT_REPOSITORY_EX")
8733 delegate:self
8734 cancelButtonTitle:UCLocalize("OK")
8735 otherButtonTitles:nil
8736 ] autorelease];
8737
8738 [alert setContext:@"trivial"];
8739 [alert show];
8740
8741 href_ = nil;
8742 }
8743
8744 error_ = nil;
8745 }
8746 }
8747
8748 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8749 switch ([response statusCode]) {
8750 case 200:
8751 cydia_ = YES;
8752 }
8753 }
8754
8755 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8756 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8757 error_ = error;
8758 [self _endConnection:connection];
8759 }
8760
8761 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8762 [self _endConnection:connection];
8763 }
8764
8765 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8766 NSURL *url([NSURL URLWithString:href]);
8767
8768 NSMutableURLRequest *request = [NSMutableURLRequest
8769 requestWithURL:url
8770 cachePolicy:NSURLRequestUseProtocolCachePolicy
8771 timeoutInterval:120.0
8772 ];
8773
8774 [request setHTTPMethod:method];
8775
8776 if (Machine_ != NULL)
8777 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8778
8779 if ([url isCydiaSecure]) {
8780 if (UniqueID_ != nil) {
8781 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8782 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8783 }
8784 }
8785
8786 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8787 }
8788
8789 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8790 NSString *context([alert context]);
8791
8792 if ([context isEqualToString:@"source"]) {
8793 switch (button) {
8794 case 1: {
8795 NSString *href = [[alert textField] text];
8796
8797 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8798
8799 if (![href hasSuffix:@"/"])
8800 href_ = [href stringByAppendingString:@"/"];
8801 else
8802 href_ = href;
8803
8804 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8805 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8806 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8807 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8808
8809 cydia_ = false;
8810
8811 // XXX: this is stupid
8812 hud_ = [delegate_ addProgressHUD];
8813 [hud_ setText:UCLocalize("VERIFYING_URL")];
8814 [delegate_ retainNetworkActivityIndicator];
8815 } break;
8816
8817 case 0:
8818 break;
8819
8820 _nodefault
8821 }
8822
8823 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8824 } else if ([context isEqualToString:@"trivial"])
8825 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8826 else if ([context isEqualToString:@"urlerror"])
8827 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8828 else if ([context isEqualToString:@"warning"]) {
8829 switch (button) {
8830 case 1:
8831 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8832 break;
8833
8834 case 0:
8835 break;
8836
8837 _nodefault
8838 }
8839
8840 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8841 }
8842 }
8843
8844 - (void) loadView {
8845 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8846 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8847 [list_ setRowHeight:53];
8848 [(UITableView *) list_ setDataSource:self];
8849 [list_ setDelegate:self];
8850 [self setView:list_];
8851 }
8852
8853 - (void) viewDidLoad {
8854 [super viewDidLoad];
8855
8856 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8857 [self updateButtonsForEditingStatusAnimated:NO];
8858 }
8859
8860 - (void) viewWillDisappear:(BOOL)animated {
8861 [super viewWillAppear:animated];
8862
8863 [list_ setEditing:NO];
8864 [self updateButtonsForEditingStatusAnimated:NO];
8865 }
8866
8867 - (void) releaseSubviews {
8868 list_ = nil;
8869
8870 sources_ = nil;
8871
8872 [super releaseSubviews];
8873 }
8874
8875 - (id) initWithDatabase:(Database *)database {
8876 if ((self = [super init]) != nil) {
8877 database_ = database;
8878 } return self;
8879 }
8880
8881 - (void) reloadData {
8882 [super reloadData];
8883
8884 @synchronized (database_) {
8885 era_ = [database_ era];
8886
8887 pkgSourceList list;
8888 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8889 return;
8890
8891 sources_ = [NSMutableArray arrayWithCapacity:16];
8892 [sources_ addObjectsFromArray:[database_ sources]];
8893 _trace();
8894 [sources_ sortUsingSelector:@selector(compareByName:)];
8895 _trace();
8896
8897 int count([sources_ count]);
8898 offset_ = 0;
8899 for (int i = 0; i != count; i++) {
8900 if ([[sources_ objectAtIndex:i] record] == nil)
8901 break;
8902 offset_++;
8903 }
8904
8905 [list_ reloadData];
8906 } }
8907
8908 - (void) showAddSourcePrompt {
8909 UIAlertView *alert = [[[UIAlertView alloc]
8910 initWithTitle:UCLocalize("ENTER_APT_URL")
8911 message:nil
8912 delegate:self
8913 cancelButtonTitle:UCLocalize("CANCEL")
8914 otherButtonTitles:
8915 UCLocalize("ADD_SOURCE"),
8916 nil
8917 ] autorelease];
8918
8919 [alert setContext:@"source"];
8920
8921 [alert setNumberOfRows:1];
8922 [alert addTextFieldWithValue:@"http://" label:@""];
8923
8924 UITextInputTraits *traits = [[alert textField] textInputTraits];
8925 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8926 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8927 [traits setKeyboardType:UIKeyboardTypeURL];
8928 // XXX: UIReturnKeyDone
8929 [traits setReturnKeyType:UIReturnKeyNext];
8930
8931 [alert show];
8932 }
8933
8934 - (void) addButtonClicked {
8935 [self showAddSourcePrompt];
8936 }
8937
8938 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8939 BOOL editing([list_ isEditing]);
8940
8941 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8942 initWithTitle:UCLocalize("ADD")
8943 style:UIBarButtonItemStylePlain
8944 target:self
8945 action:@selector(addButtonClicked)
8946 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8947
8948 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8949 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8950 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8951 target:self
8952 action:@selector(editButtonClicked)
8953 ] autorelease] animated:animated];
8954
8955 if (IsWildcat_ && !editing)
8956 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8957 initWithTitle:UCLocalize("SETTINGS")
8958 style:UIBarButtonItemStylePlain
8959 target:self
8960 action:@selector(settingsButtonClicked)
8961 ] autorelease]];
8962 }
8963
8964 - (void) settingsButtonClicked {
8965 [delegate_ showSettings];
8966 }
8967
8968 - (void) editButtonClicked {
8969 [list_ setEditing:![list_ isEditing] animated:YES];
8970 [self updateButtonsForEditingStatusAnimated:YES];
8971 }
8972
8973 @end
8974 /* }}} */
8975
8976 /* Settings Controller {{{ */
8977 @interface SettingsController : CyteViewController <
8978 UITableViewDataSource,
8979 UITableViewDelegate
8980 > {
8981 _transient Database *database_;
8982 // XXX: ok, "roledelegate_"?...
8983 _transient id roledelegate_;
8984 _H<UITableView, 2> table_;
8985 _H<UISegmentedControl> segment_;
8986 _H<UIView> container_;
8987 }
8988
8989 - (void) showDoneButton;
8990 - (void) resizeSegmentedControl;
8991
8992 @end
8993
8994 @implementation SettingsController
8995
8996 - (void) loadView {
8997 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
8998 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8999 [table_ setDelegate:self];
9000 [(UITableView *) table_ setDataSource:self];
9001 [self setView:table_];
9002
9003 NSArray *items = [NSArray arrayWithObjects:
9004 UCLocalize("USER"),
9005 UCLocalize("HACKER"),
9006 UCLocalize("DEVELOPER"),
9007 nil];
9008 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9009 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9010 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9011 [container_ addSubview:segment_];
9012 }
9013
9014 - (void) viewDidLoad {
9015 [super viewDidLoad];
9016
9017 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9018
9019 int index = -1;
9020 if ([Role_ isEqualToString:@"User"]) index = 0;
9021 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9022 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9023 if (index != -1) {
9024 [segment_ setSelectedSegmentIndex:index];
9025 [self showDoneButton];
9026 }
9027
9028 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9029 [self resizeSegmentedControl];
9030 }
9031
9032 - (void) releaseSubviews {
9033 table_ = nil;
9034 segment_ = nil;
9035 container_ = nil;
9036
9037 [super releaseSubviews];
9038 }
9039
9040 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9041 if ((self = [super init]) != nil) {
9042 database_ = database;
9043 roledelegate_ = delegate;
9044 } return self;
9045 }
9046
9047 - (void) resizeSegmentedControl {
9048 CGFloat width = [[self view] frame].size.width;
9049 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9050 }
9051
9052 - (void) viewWillAppear:(BOOL)animated {
9053 [super viewWillAppear:animated];
9054
9055 [self resizeSegmentedControl];
9056 }
9057
9058 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9059 [self resizeSegmentedControl];
9060 }
9061
9062 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9063 [self resizeSegmentedControl];
9064 }
9065
9066 - (void) save {
9067 NSString *role(nil);
9068
9069 switch ([segment_ selectedSegmentIndex]) {
9070 case 0: role = @"User"; break;
9071 case 1: role = @"Hacker"; break;
9072 case 2: role = @"Developer"; break;
9073
9074 _nodefault
9075 }
9076
9077 if (![role isEqualToString:Role_]) {
9078 bool rolling(Role_ == nil);
9079 Role_ = role;
9080
9081 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9082 Role_, @"Role",
9083 nil];
9084
9085 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9086 Changed_ = true;
9087
9088 if (rolling)
9089 [roledelegate_ loadData];
9090 else
9091 [roledelegate_ updateData];
9092 }
9093 }
9094
9095 - (void) segmentChanged:(UISegmentedControl *)control {
9096 [self showDoneButton];
9097 }
9098
9099 - (void) saveAndClose {
9100 [self save];
9101
9102 [[self navigationItem] setRightBarButtonItem:nil];
9103 [[self navigationController] dismissModalViewControllerAnimated:YES];
9104 }
9105
9106 - (void) doneButtonClicked {
9107 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9108 [spinner startAnimating];
9109 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9110 [[self navigationItem] setRightBarButtonItem:spinItem];
9111
9112 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9113 }
9114
9115 - (void) showDoneButton {
9116 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9117 initWithTitle:UCLocalize("DONE")
9118 style:UIBarButtonItemStyleDone
9119 target:self
9120 action:@selector(doneButtonClicked)
9121 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9122 }
9123
9124 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9125 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9126 return 6;
9127 }
9128
9129 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9130 return 0; // :(
9131 }
9132
9133 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9134 return nil; // This method is required by the protocol.
9135 }
9136
9137 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9138 if (section == 1)
9139 return UCLocalize("ROLE_EX");
9140 if (section == 4)
9141 return [NSString stringWithFormat:
9142 @"%@: %@\n%@: %@\n%@: %@",
9143 UCLocalize("USER"), UCLocalize("USER_EX"),
9144 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9145 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9146 ];
9147 else return nil;
9148 }
9149
9150 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9151 return section == 3 ? 44.0f : 0;
9152 }
9153
9154 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9155 return section == 3 ? container_ : nil;
9156 }
9157
9158 - (void) reloadData {
9159 [super reloadData];
9160
9161 [table_ reloadData];
9162 }
9163
9164 @end
9165 /* }}} */
9166 /* Stash Controller {{{ */
9167 @interface StashController : CyteViewController {
9168 _H<UIActivityIndicatorView> spinner_;
9169 _H<UILabel> status_;
9170 _H<UILabel> caption_;
9171 }
9172
9173 @end
9174
9175 @implementation StashController
9176
9177 - (void) loadView {
9178 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9179 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9180 [self setView:view];
9181
9182 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9183
9184 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9185 CGRect spinrect = [spinner_ frame];
9186 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9187 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9188 [spinner_ setFrame:spinrect];
9189 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9190 [view addSubview:spinner_];
9191 [spinner_ startAnimating];
9192
9193 CGRect captrect;
9194 captrect.size.width = [[self view] frame].size.width;
9195 captrect.size.height = 40.0f;
9196 captrect.origin.x = 0;
9197 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9198 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9199 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9200 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9201 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9202 [caption_ setTextColor:[UIColor whiteColor]];
9203 [caption_ setBackgroundColor:[UIColor clearColor]];
9204 [caption_ setShadowColor:[UIColor blackColor]];
9205 [caption_ setTextAlignment:UITextAlignmentCenter];
9206 [view addSubview:caption_];
9207
9208 CGRect statusrect;
9209 statusrect.size.width = [[self view] frame].size.width;
9210 statusrect.size.height = 30.0f;
9211 statusrect.origin.x = 0;
9212 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9213 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9214 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9215 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9216 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9217 [status_ setTextColor:[UIColor whiteColor]];
9218 [status_ setBackgroundColor:[UIColor clearColor]];
9219 [status_ setShadowColor:[UIColor blackColor]];
9220 [status_ setTextAlignment:UITextAlignmentCenter];
9221 [view addSubview:status_];
9222 }
9223
9224 - (void) releaseSubviews {
9225 spinner_ = nil;
9226 status_ = nil;
9227 caption_ = nil;
9228
9229 [super releaseSubviews];
9230 }
9231
9232 @end
9233 /* }}} */
9234
9235 @interface CYURLCache : SDURLCache {
9236 }
9237
9238 @end
9239
9240 @implementation CYURLCache
9241
9242 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9243 #if !ForRelease
9244 if (false);
9245 else if ([event isEqualToString:@"no-cache"])
9246 event = @"!!!";
9247 else if ([event isEqualToString:@"store"])
9248 event = @">>>";
9249 else if ([event isEqualToString:@"invalid"])
9250 event = @"???";
9251 else if ([event isEqualToString:@"memory"])
9252 event = @"mem";
9253 else if ([event isEqualToString:@"disk"])
9254 event = @"ssd";
9255 else if ([event isEqualToString:@"miss"])
9256 event = @"---";
9257
9258 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9259 #endif
9260 }
9261
9262 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9263 if (NSURLResponse *response = [cached response])
9264 if (NSString *mime = [response MIMEType])
9265 if ([mime isEqualToString:@"text/cache-manifest"]) {
9266 NSURL *url([response URL]);
9267
9268 #if !ForRelease
9269 NSLog(@"###: %@", [url absoluteString]);
9270 #endif
9271
9272 @synchronized (HostConfig_) {
9273 [CachedURLs_ addObject:url];
9274 }
9275 }
9276
9277 [super storeCachedResponse:cached forRequest:request];
9278 }
9279
9280 @end
9281
9282 @interface Cydia : UIApplication <
9283 ConfirmationControllerDelegate,
9284 DatabaseDelegate,
9285 CydiaDelegate,
9286 UINavigationControllerDelegate,
9287 UITabBarControllerDelegate
9288 > {
9289 _H<UIWindow> window_;
9290 _H<CYTabBarController> tabbar_;
9291 _H<CydiaLoadingViewController> emulated_;
9292
9293 _H<NSMutableArray> essential_;
9294 _H<NSMutableArray> broken_;
9295
9296 Database *database_;
9297
9298 _H<NSURL> starturl_;
9299
9300 unsigned locked_;
9301 unsigned activity_;
9302
9303 _H<StashController> stash_;
9304
9305 bool loaded_;
9306 }
9307
9308 - (void) loadData;
9309
9310 @end
9311
9312 @implementation Cydia
9313
9314 - (void) beginUpdate {
9315 [tabbar_ beginUpdate];
9316 }
9317
9318 - (BOOL) updating {
9319 return [tabbar_ updating];
9320 }
9321
9322 - (void) _loaded {
9323 if ([broken_ count] != 0) {
9324 int count = [broken_ count];
9325
9326 UIAlertView *alert = [[[UIAlertView alloc]
9327 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9328 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9329 delegate:self
9330 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9331 otherButtonTitles:
9332 UCLocalize("TEMPORARY_IGNORE"),
9333 nil
9334 ] autorelease];
9335
9336 [alert setContext:@"fixhalf"];
9337 [alert setNumberOfRows:2];
9338 [alert show];
9339 } else if (!Ignored_ && [essential_ count] != 0) {
9340 int count = [essential_ count];
9341
9342 UIAlertView *alert = [[[UIAlertView alloc]
9343 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9344 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9345 delegate:self
9346 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9347 otherButtonTitles:
9348 UCLocalize("UPGRADE_ESSENTIAL"),
9349 UCLocalize("COMPLETE_UPGRADE"),
9350 nil
9351 ] autorelease];
9352
9353 [alert setContext:@"upgrade"];
9354 [alert show];
9355 }
9356 }
9357
9358 - (void) returnToCydia {
9359 [self _loaded];
9360 }
9361
9362 - (void) _saveConfig {
9363 @synchronized (database_) {
9364 _trace();
9365 MetaFile_.Sync();
9366 _trace();
9367 }
9368
9369 if (Changed_) {
9370 NSString *error(nil);
9371
9372 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9373 _trace();
9374 NSError *error(nil);
9375 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9376 NSLog(@"failure to save metadata data: %@", error);
9377 _trace();
9378
9379 Changed_ = false;
9380 } else {
9381 NSLog(@"failure to serialize metadata: %@", error);
9382 }
9383 }
9384
9385 CydiaWriteSources();
9386 }
9387
9388 // Navigation controller for the queuing badge.
9389 - (UINavigationController *) queueNavigationController {
9390 NSArray *controllers = [tabbar_ viewControllers];
9391 return [controllers objectAtIndex:3];
9392 }
9393
9394 - (void) unloadData {
9395 [tabbar_ unloadData];
9396 }
9397
9398 - (void) _updateData {
9399 [self _saveConfig];
9400 [self unloadData];
9401
9402 UINavigationController *navigation = [self queueNavigationController];
9403
9404 id queuedelegate = nil;
9405 if ([[navigation viewControllers] count] > 0)
9406 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9407
9408 [queuedelegate queueStatusDidChange];
9409 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9410 }
9411
9412 - (void) _refreshIfPossible:(NSDate *)update {
9413 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9414
9415 bool recently = false;
9416 if (update != nil) {
9417 NSTimeInterval interval([update timeIntervalSinceNow]);
9418 if (interval <= 0 && interval > -(15*60))
9419 recently = true;
9420 }
9421
9422 // Don't automatic refresh if:
9423 // - We already refreshed recently.
9424 // - We already auto-refreshed this launch.
9425 // - Auto-refresh is disabled.
9426 if (recently || loaded_ || ManualRefresh) {
9427 // If we are cancelling, we need to make sure it knows it's already loaded.
9428 loaded_ = true;
9429
9430 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9431 } else {
9432 // We are going to load, so remember that.
9433 loaded_ = true;
9434
9435 // If we can reach the server, auto-refresh!
9436 if (IsReachable("cydia.saurik.com"))
9437 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9438 }
9439
9440 [pool release];
9441 }
9442
9443 - (void) refreshIfPossible {
9444 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9445 }
9446
9447 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9448 @synchronized (self) {
9449 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9450 [hud setText:UCLocalize("RELOADING_DATA")];
9451
9452 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9453
9454 size_t changes(0);
9455
9456 [essential_ removeAllObjects];
9457 [broken_ removeAllObjects];
9458
9459 NSArray *packages([database_ packages]);
9460 for (Package *package in packages) {
9461 if ([package half])
9462 [broken_ addObject:package];
9463 if ([package upgradableAndEssential:NO] && ![package ignored]) {
9464 if ([package essential])
9465 [essential_ addObject:package];
9466 ++changes;
9467 }
9468 }
9469
9470 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9471 if (changes != 0) {
9472 _trace();
9473 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9474 [changesItem setBadgeValue:badge];
9475 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9476 [self setApplicationIconBadgeNumber:changes];
9477 } else {
9478 _trace();
9479 [changesItem setBadgeValue:nil];
9480 [changesItem setAnimatedBadge:NO];
9481 [self setApplicationIconBadgeNumber:0];
9482 }
9483
9484 [self _updateData];
9485
9486 if (hud != nil)
9487 [self removeProgressHUD:hud];
9488 } }
9489
9490 - (void) updateData {
9491 [self _updateData];
9492 }
9493
9494 - (void) update_ {
9495 [database_ update];
9496 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9497 }
9498
9499 - (void) disemulate {
9500 if (emulated_ == nil)
9501 return;
9502
9503 [window_ addSubview:[tabbar_ view]];
9504 [[emulated_ view] removeFromSuperview];
9505 emulated_ = nil;
9506 [window_ setUserInteractionEnabled:YES];
9507 }
9508
9509 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9510 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9511 if (IsWildcat_)
9512 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9513
9514 UIViewController *parent;
9515 if (emulated_ == nil)
9516 parent = tabbar_;
9517 else if (!force)
9518 parent = emulated_;
9519 else {
9520 [self disemulate];
9521 parent = tabbar_;
9522 }
9523
9524 [parent presentModalViewController:navigation animated:YES];
9525 }
9526
9527 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9528 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9529
9530 if (navigation != nil)
9531 [navigation pushViewController:progress animated:YES];
9532 else
9533 [self presentModalViewController:progress force:YES];
9534
9535 [progress invoke:invocation withTitle:title];
9536 return progress;
9537 }
9538
9539 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9540 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9541 }
9542
9543 - (void) repairWithInvocation:(NSInvocation *)invocation {
9544 _trace();
9545 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9546 _trace();
9547 }
9548
9549 - (void) repairWithSelector:(SEL)selector {
9550 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9551 }
9552
9553 - (void) reloadData {
9554 [self reloadDataWithInvocation:nil];
9555 if ([database_ progressDelegate] == nil)
9556 [self _loaded];
9557 }
9558
9559 - (void) syncData {
9560 [self _saveConfig];
9561 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9562 }
9563
9564 - (void) addSource:(NSDictionary *) source {
9565 CydiaAddSource(source);
9566 }
9567
9568 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9569 CydiaAddSource(href, distribution, sections);
9570 }
9571
9572 - (void) addTrivialSource:(NSString *)href {
9573 CydiaAddSource(href, @"./");
9574 }
9575
9576 - (void) updateValues {
9577 Changed_ = true;
9578 }
9579
9580 - (void) resolve {
9581 pkgProblemResolver *resolver = [database_ resolver];
9582
9583 resolver->InstallProtect();
9584 if (!resolver->Resolve(true))
9585 _error->Discard();
9586 }
9587
9588 - (bool) perform {
9589 // XXX: this is a really crappy way of doing this.
9590 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9591 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9592 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9593 if ([tabbar_ updating])
9594 [tabbar_ cancelUpdate];
9595
9596 if (![database_ prepare])
9597 return false;
9598
9599 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9600 [page setDelegate:self];
9601 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9602
9603 if (IsWildcat_)
9604 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9605 [tabbar_ presentModalViewController:confirm_ animated:YES];
9606
9607 return true;
9608 }
9609
9610 - (void) queue {
9611 @synchronized (self) {
9612 [self perform];
9613 }
9614 }
9615
9616 - (void) clearPackage:(Package *)package {
9617 @synchronized (self) {
9618 [package clear];
9619 [self resolve];
9620 [self perform];
9621 }
9622 }
9623
9624 - (void) installPackages:(NSArray *)packages {
9625 @synchronized (self) {
9626 for (Package *package in packages)
9627 [package install];
9628 [self resolve];
9629 [self perform];
9630 }
9631 }
9632
9633 - (void) installPackage:(Package *)package {
9634 @synchronized (self) {
9635 [package install];
9636 [self resolve];
9637 [self perform];
9638 }
9639 }
9640
9641 - (void) removePackage:(Package *)package {
9642 @synchronized (self) {
9643 [package remove];
9644 [self resolve];
9645 [self perform];
9646 }
9647 }
9648
9649 - (void) distUpgrade {
9650 @synchronized (self) {
9651 if (![database_ upgrade])
9652 return;
9653 [self perform];
9654 }
9655 }
9656
9657 - (void) perform_ {
9658 [database_ perform];
9659 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9660 }
9661
9662 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9663 Queuing_ = false;
9664 ++locked_;
9665 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9666 --locked_;
9667 [self refreshIfPossible];
9668 }
9669
9670 - (void) showSettings {
9671 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9672 }
9673
9674 - (void) retainNetworkActivityIndicator {
9675 if (activity_++ == 0)
9676 [self setNetworkActivityIndicatorVisible:YES];
9677
9678 #if TraceLogging
9679 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9680 #endif
9681 }
9682
9683 - (void) releaseNetworkActivityIndicator {
9684 if (--activity_ == 0)
9685 [self setNetworkActivityIndicatorVisible:NO];
9686
9687 #if TraceLogging
9688 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9689 #endif
9690
9691 }
9692
9693 - (void) cancelAndClear:(bool)clear {
9694 @synchronized (self) {
9695 if (clear) {
9696 [database_ clear];
9697 Queuing_ = false;
9698 } else {
9699 Queuing_ = true;
9700 }
9701
9702 [self _updateData];
9703 }
9704 }
9705
9706 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9707 NSString *context([alert context]);
9708
9709 if ([context isEqualToString:@"conffile"]) {
9710 FILE *input = [database_ input];
9711 if (button == [alert cancelButtonIndex])
9712 fprintf(input, "N\n");
9713 else if (button == [alert firstOtherButtonIndex])
9714 fprintf(input, "Y\n");
9715 fflush(input);
9716
9717 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9718 } else if ([context isEqualToString:@"fixhalf"]) {
9719 if (button == [alert cancelButtonIndex]) {
9720 @synchronized (self) {
9721 for (Package *broken in (id) broken_) {
9722 [broken remove];
9723
9724 NSString *id = [broken id];
9725 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9726 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9727 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9728 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9729 }
9730
9731 [self resolve];
9732 [self perform];
9733 }
9734 } else if (button == [alert firstOtherButtonIndex]) {
9735 [broken_ removeAllObjects];
9736 [self _loaded];
9737 }
9738
9739 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9740 } else if ([context isEqualToString:@"upgrade"]) {
9741 if (button == [alert firstOtherButtonIndex]) {
9742 @synchronized (self) {
9743 for (Package *essential in (id) essential_)
9744 [essential install];
9745
9746 [self resolve];
9747 [self perform];
9748 }
9749 } else if (button == [alert firstOtherButtonIndex] + 1) {
9750 [self distUpgrade];
9751 } else if (button == [alert cancelButtonIndex]) {
9752 Ignored_ = YES;
9753 }
9754
9755 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9756 }
9757 }
9758
9759 - (void) system:(NSString *)command {
9760 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9761
9762 _trace();
9763 system([command UTF8String]);
9764 _trace();
9765
9766 [pool release];
9767 }
9768
9769 - (void) applicationWillSuspend {
9770 [database_ clean];
9771 [super applicationWillSuspend];
9772 }
9773
9774 - (BOOL) isSafeToSuspend {
9775 if (locked_ != 0) {
9776 #if !ForRelease
9777 NSLog(@"isSafeToSuspend: locked_ != 0");
9778 #endif
9779 return false;
9780 }
9781
9782 // Use external process status API internally.
9783 // This is probably a really bad idea.
9784 // XXX: what is the point of this? does this solve anything at all?
9785 uint64_t status = 0;
9786 int notify_token;
9787 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9788 notify_get_state(notify_token, &status);
9789 notify_cancel(notify_token);
9790 }
9791
9792 if (status != 0) {
9793 #if !ForRelease
9794 NSLog(@"isSafeToSuspend: status != 0");
9795 #endif
9796 return false;
9797 }
9798
9799 #if !ForRelease
9800 NSLog(@"isSafeToSuspend: -> true");
9801 #endif
9802 return true;
9803 }
9804
9805 - (void) applicationSuspend:(__GSEvent *)event {
9806 if ([self isSafeToSuspend])
9807 [super applicationSuspend:event];
9808 }
9809
9810 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9811 if ([self isSafeToSuspend])
9812 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9813 }
9814
9815 - (void) _setSuspended:(BOOL)value {
9816 if ([self isSafeToSuspend])
9817 [super _setSuspended:value];
9818 }
9819
9820 - (UIProgressHUD *) addProgressHUD {
9821 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9822 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9823
9824 [window_ setUserInteractionEnabled:NO];
9825
9826 UIViewController *target(tabbar_);
9827 if (UIViewController *modal = [target modalViewController])
9828 target = modal;
9829
9830 [hud showInView:[target view]];
9831
9832 ++locked_;
9833 return hud;
9834 }
9835
9836 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9837 --locked_;
9838 [hud hide];
9839 [hud removeFromSuperview];
9840 [window_ setUserInteractionEnabled:YES];
9841 }
9842
9843 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9844 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9845 }
9846
9847 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9848 NSString *scheme([[url scheme] lowercaseString]);
9849 if ([[url absoluteString] length] <= [scheme length] + 3)
9850 return nil;
9851 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9852 NSArray *components([path componentsSeparatedByString:@"/"]);
9853
9854 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9855 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9856 if (controller != nil)
9857 [controller setDelegate:self];
9858 return controller;
9859 }
9860
9861 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9862 return nil;
9863
9864 NSString *base([components objectAtIndex:0]);
9865
9866 CyteViewController *controller = nil;
9867
9868 if ([base isEqualToString:@"url"]) {
9869 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9870 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9871 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9872 } else if (!external && [components count] == 1) {
9873 if ([base isEqualToString:@"manage"]) {
9874 controller = [[[ManageController alloc] init] autorelease];
9875 }
9876
9877 if ([base isEqualToString:@"storage"]) {
9878 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9879 }
9880
9881 if ([base isEqualToString:@"sources"]) {
9882 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9883 }
9884
9885 if ([base isEqualToString:@"home"]) {
9886 controller = [[[HomeController alloc] init] autorelease];
9887 }
9888
9889 if ([base isEqualToString:@"sections"]) {
9890 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9891 }
9892
9893 if ([base isEqualToString:@"search"]) {
9894 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9895 }
9896
9897 if ([base isEqualToString:@"changes"]) {
9898 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9899 }
9900
9901 if ([base isEqualToString:@"installed"]) {
9902 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9903 }
9904 } else if ([components count] == 2) {
9905 NSString *argument = [components objectAtIndex:1];
9906
9907 if ([base isEqualToString:@"package"]) {
9908 controller = [self pageForPackage:argument withReferrer:referrer];
9909 }
9910
9911 if (!external && [base isEqualToString:@"search"]) {
9912 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9913 }
9914
9915 if (!external && [base isEqualToString:@"sections"]) {
9916 if ([argument isEqualToString:@"all"])
9917 argument = nil;
9918 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9919 }
9920
9921 if (!external && [base isEqualToString:@"sources"]) {
9922 if ([argument isEqualToString:@"add"]) {
9923 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9924 [(SourcesController *)controller showAddSourcePrompt];
9925 } else {
9926 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9927 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9928 }
9929 }
9930
9931 if (!external && [base isEqualToString:@"launch"]) {
9932 [self launchApplicationWithIdentifier:argument suspended:NO];
9933 return nil;
9934 }
9935 } else if (!external && [components count] == 3) {
9936 NSString *arg1 = [components objectAtIndex:1];
9937 NSString *arg2 = [components objectAtIndex:2];
9938
9939 if ([base isEqualToString:@"package"]) {
9940 if ([arg2 isEqualToString:@"settings"]) {
9941 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9942 } else if ([arg2 isEqualToString:@"files"]) {
9943 if (Package *package = [database_ packageWithName:arg1]) {
9944 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9945 [(FileTable *)controller setPackage:package];
9946 }
9947 }
9948 }
9949 }
9950
9951 [controller setDelegate:self];
9952 return controller;
9953 }
9954
9955 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9956 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9957
9958 if (page != nil)
9959 [tabbar_ setUnselectedViewController:page];
9960
9961 return page != nil;
9962 }
9963
9964 - (void) applicationOpenURL:(NSURL *)url {
9965 [super applicationOpenURL:url];
9966
9967 if (!loaded_)
9968 starturl_ = url;
9969 else
9970 [self openCydiaURL:url forExternal:YES];
9971 }
9972
9973 - (void) applicationWillResignActive:(UIApplication *)application {
9974 // Stop refreshing if you get a phone call or lock the device.
9975 if ([tabbar_ updating])
9976 [tabbar_ cancelUpdate];
9977
9978 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9979 [super applicationWillResignActive:application];
9980 }
9981
9982 - (void) saveState {
9983 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9984 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9985 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9986 Changed_ = true;
9987
9988 [self _saveConfig];
9989 }
9990
9991 - (void) applicationWillTerminate:(UIApplication *)application {
9992 [self saveState];
9993 }
9994
9995 - (void) setConfigurationData:(NSString *)data {
9996 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9997
9998 if (!conffile_r(data)) {
9999 lprintf("E:invalid conffile\n");
10000 return;
10001 }
10002
10003 NSString *ofile = conffile_r[1];
10004 //NSString *nfile = conffile_r[2];
10005
10006 UIAlertView *alert = [[[UIAlertView alloc]
10007 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10008 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10009 delegate:self
10010 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10011 otherButtonTitles:
10012 UCLocalize("ACCEPT_NEW_COPY"),
10013 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10014 nil
10015 ] autorelease];
10016
10017 [alert setContext:@"conffile"];
10018 [alert setNumberOfRows:2];
10019 [alert show];
10020 }
10021
10022 - (void) addStashController {
10023 ++locked_;
10024 stash_ = [[[StashController alloc] init] autorelease];
10025 [window_ addSubview:[stash_ view]];
10026 }
10027
10028 - (void) removeStashController {
10029 [[stash_ view] removeFromSuperview];
10030 stash_ = nil;
10031 --locked_;
10032 }
10033
10034 - (void) stash {
10035 [self setIdleTimerDisabled:YES];
10036
10037 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10038 UpdateExternalStatus(1);
10039 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10040 UpdateExternalStatus(0);
10041
10042 [self removeStashController];
10043
10044 pid_t pid(ExecFork());
10045 if (pid == 0) {
10046 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10047 perror("launchctl stop");
10048 exit(0);
10049 }
10050
10051 ReapZombie(pid);
10052 }
10053
10054 - (void) setupViewControllers {
10055 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10056
10057 NSMutableArray *items([NSMutableArray arrayWithObjects:
10058 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10059 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10060 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10061 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10062 nil]);
10063
10064 if (IsWildcat_) {
10065 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10066 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10067 } else {
10068 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10069 }
10070
10071 NSMutableArray *controllers([NSMutableArray array]);
10072 for (UITabBarItem *item in items) {
10073 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10074 [controller setTabBarItem:item];
10075 [controllers addObject:controller];
10076 }
10077 [tabbar_ setViewControllers:controllers];
10078
10079 [tabbar_ setUpdateDelegate:self];
10080 }
10081
10082 - (void) _sendMemoryWarningNotification {
10083 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10084 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10085 else
10086 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10087 }
10088
10089 - (void) _sendMemoryWarningNotifications {
10090 while (true) {
10091 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10092 sleep(2);
10093 //usleep(2000000);
10094 }
10095 }
10096
10097 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10098 NSLog(@"--");
10099 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10100 }
10101
10102 - (void) applicationDidFinishLaunching:(id)unused {
10103 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10104
10105 _trace();
10106 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10107 [self setApplicationSupportsShakeToEdit:NO];
10108
10109 @synchronized (HostConfig_) {
10110 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10111 }
10112
10113 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10114 initWithMemoryCapacity:524288
10115 diskCapacity:10485760
10116 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
10117 ] autorelease]];
10118
10119 [CydiaWebViewController _initialize];
10120
10121 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10122
10123 // this would disallow http{,s} URLs from accessing this data
10124 //[WebView registerURLSchemeAsLocal:@"cydia"];
10125
10126 Font12_ = [UIFont systemFontOfSize:12];
10127 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10128 Font14_ = [UIFont systemFontOfSize:14];
10129 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10130 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10131
10132 essential_ = [NSMutableArray arrayWithCapacity:4];
10133 broken_ = [NSMutableArray arrayWithCapacity:4];
10134
10135 // XXX: I really need this thing... like, seriously... I'm sorry
10136 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10137
10138 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10139 [window_ orderFront:self];
10140 [window_ makeKey:self];
10141 [window_ setHidden:NO];
10142
10143 if (
10144 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
10145 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
10146 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
10147 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
10148 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
10149 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
10150 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
10151 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
10152 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
10153 false
10154 ) {
10155 [self addStashController];
10156 // XXX: this would be much cleaner as a yieldToSelector:
10157 // that way the removeStashController could happen right here inline
10158 // we also could no longer require the useless stash_ field anymore
10159 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10160 return;
10161 }
10162
10163 database_ = [Database sharedInstance];
10164 [database_ setDelegate:self];
10165
10166 [window_ setUserInteractionEnabled:NO];
10167 [self setupViewControllers];
10168
10169 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10170 [window_ addSubview:[emulated_ view]];
10171
10172 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10173 _trace();
10174 }
10175
10176 - (NSArray *) defaultStartPages {
10177 NSMutableArray *standard = [NSMutableArray array];
10178 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10179 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10180 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10181 if (!IsWildcat_) {
10182 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10183 } else {
10184 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10185 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10186 }
10187 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10188 return standard;
10189 }
10190
10191 - (void) loadData {
10192 _trace();
10193 if (Role_ == nil) {
10194 [window_ setUserInteractionEnabled:YES];
10195 [self showSettings];
10196 return;
10197 } else {
10198 if ([emulated_ modalViewController] != nil)
10199 [emulated_ dismissModalViewControllerAnimated:YES];
10200 [window_ setUserInteractionEnabled:NO];
10201 }
10202
10203 [self reloadDataWithInvocation:nil];
10204 [self refreshIfPossible];
10205 PrintTimes();
10206
10207 [self disemulate];
10208
10209 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10210 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
10211 int standardIndex = 0;
10212 NSArray *standard = [self defaultStartPages];
10213
10214 BOOL valid = YES;
10215
10216 if (saved == nil)
10217 valid = NO;
10218
10219 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10220 if (valid && closed != nil) {
10221 NSTimeInterval interval([closed timeIntervalSinceNow]);
10222 // XXX: Is 30 minutes the optimal time here?
10223 if (interval <= -(30*60))
10224 valid = NO;
10225 }
10226
10227 if (valid && [saved count] != [standard count])
10228 valid = NO;
10229
10230 if (valid) {
10231 for (unsigned int i = 0; i < [standard count]; i++) {
10232 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10233 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10234 // but it's good enough for now.
10235 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10236 valid = NO;
10237 break;
10238 }
10239 }
10240 }
10241
10242 NSArray *items = nil;
10243 if (valid) {
10244 [tabbar_ setSelectedIndex:savedIndex];
10245 items = saved;
10246 } else {
10247 [tabbar_ setSelectedIndex:standardIndex];
10248 items = standard;
10249 }
10250
10251 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10252 NSArray *stack = [items objectAtIndex:tab];
10253 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10254 NSMutableArray *current = [NSMutableArray array];
10255
10256 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10257 NSString *addr = [stack objectAtIndex:nav];
10258 NSURL *url = [NSURL URLWithString:addr];
10259 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10260 if (page != nil)
10261 [current addObject:page];
10262 }
10263
10264 [navigation setViewControllers:current];
10265 }
10266
10267 // (Try to) show the startup URL.
10268 if (starturl_ != nil) {
10269 [self openCydiaURL:starturl_ forExternal:NO];
10270 starturl_ = nil;
10271 }
10272 }
10273
10274 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10275 if (item != nil && IsWildcat_) {
10276 [sheet showFromBarButtonItem:item animated:YES];
10277 } else {
10278 [sheet showInView:window_];
10279 }
10280 }
10281
10282 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10283 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10284 [progress setTitle:task];
10285 [progress addProgressEvent:event];
10286 }
10287
10288 - (void) addProgressEventForTask:(NSArray *)data {
10289 CydiaProgressEvent *event([data objectAtIndex:0]);
10290 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10291 [self addProgressEvent:event forTask:task];
10292 }
10293
10294 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10295 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10296 }
10297
10298 @end
10299
10300 /*IMP alloc_;
10301 id Alloc_(id self, SEL selector) {
10302 id object = alloc_(self, selector);
10303 lprintf("[%s]A-%p\n", self->isa->name, object);
10304 return object;
10305 }*/
10306
10307 /*IMP dealloc_;
10308 id Dealloc_(id self, SEL selector) {
10309 id object = dealloc_(self, selector);
10310 lprintf("[%s]D-%p\n", self->isa->name, object);
10311 return object;
10312 }*/
10313
10314 Class $WebDefaultUIKitDelegate;
10315
10316 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
10317 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
10318 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
10319 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
10320 }
10321
10322 static NSSet *MobilizedFiles_;
10323
10324 static NSURL *MobilizeURL(NSURL *url) {
10325 NSString *path([url path]);
10326 if ([path hasPrefix:@"/var/root/"]) {
10327 NSString *file([path substringFromIndex:10]);
10328 if ([MobilizedFiles_ containsObject:file])
10329 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10330 }
10331
10332 return url;
10333 }
10334
10335 Class $CFXPreferencesPropertyListSource;
10336 @class CFXPreferencesPropertyListSource;
10337
10338 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10339 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10340 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10341 url = MobilizeURL(url);
10342 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10343 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10344 url = old;
10345 [pool release];
10346 return value;
10347 }
10348
10349 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10350 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10351 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10352 url = MobilizeURL(url);
10353 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10354 //NSLog(@"%@ %@", [url absoluteString], value);
10355 url = old;
10356 [pool release];
10357 return value;
10358 }
10359
10360 Class $NSURLConnection;
10361
10362 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10363 NSMutableURLRequest *copy([request mutableCopy]);
10364
10365 NSURL *url([copy URL]);
10366
10367 NSString *host([url host]);
10368 NSString *scheme([[url scheme] lowercaseString]);
10369
10370 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10371
10372 @synchronized (HostConfig_) {
10373 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10374 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10375 [copy setHTTPShouldUsePipelining:YES];
10376
10377 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10378 if ([control isEqualToString:@"max-age=0"])
10379 if ([CachedURLs_ containsObject:url]) {
10380 #if !ForRelease
10381 NSLog(@"~~~: %@", url);
10382 #endif
10383
10384 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10385
10386 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10387 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10388 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10389 }
10390 }
10391
10392 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10393 } return self;
10394 }
10395
10396 Class $WAKWindow;
10397
10398 static CGSize $WAKWindow$screenSize(WAKWindow self, SEL _cmd) {
10399 CGSize size([[UIScreen mainScreen] bounds].size);
10400 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10401 if ([$WAKWindow hasLandscapeOrientation])
10402 std::swap(size.width, size.height);*/
10403 return size;
10404 }
10405
10406 int main(int argc, char *argv[]) {
10407 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10408
10409 _trace();
10410
10411 UpdateExternalStatus(0);
10412
10413 if (Class $UIDevice = objc_getClass("UIDevice")) {
10414 UIDevice *device([$UIDevice currentDevice]);
10415 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10416 } else
10417 IsWildcat_ = false;
10418
10419 UIScreen *screen([UIScreen mainScreen]);
10420 if ([screen respondsToSelector:@selector(scale)])
10421 ScreenScale_ = [screen scale];
10422 else
10423 ScreenScale_ = 1;
10424
10425 UIDevice *device([UIDevice currentDevice]);
10426 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10427 Idiom_ = @"iphone";
10428 else {
10429 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10430 if (idiom == UIUserInterfaceIdiomPhone)
10431 Idiom_ = @"iphone";
10432 else if (idiom == UIUserInterfaceIdiomPad)
10433 Idiom_ = @"ipad";
10434 else
10435 NSLog(@"unknown UIUserInterfaceIdiom!");
10436 }
10437
10438 Pcre pattern("^([0-9]+\\.[0-9]+)");
10439
10440 if (pattern([device systemVersion]))
10441 Firmware_ = pattern[1];
10442 if (pattern(Cydia_))
10443 Major_ = pattern[1];
10444
10445 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10446
10447 HostConfig_ = [[[NSObject alloc] init] autorelease];
10448 @synchronized (HostConfig_) {
10449 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10450 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10451 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10452 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10453 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10454 }
10455
10456 NSString *ui(@"ui/ios");
10457 if (Idiom_ != nil)
10458 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10459 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10460 UI_ = CydiaURL(ui);
10461
10462 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10463
10464 MobilizedFiles_ = [NSMutableSet setWithObjects:
10465 @"Library/Preferences/com.apple.Accessibility.plist",
10466 @"Library/Preferences/com.apple.preferences.sounds.plist",
10467 nil];
10468
10469 /* Library Hacks {{{ */
10470 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10471
10472 $WAKWindow = objc_getClass("WAKWindow");
10473 if ($WAKWindow != NULL)
10474 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10475 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10476
10477 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10478
10479 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10480 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10481 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10482 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10483 }
10484
10485 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10486 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10487 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10488 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10489 }
10490
10491 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10492 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10493 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10494 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10495 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10496 }
10497
10498 $NSURLConnection = objc_getClass("NSURLConnection");
10499 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10500 if (NSURLConnection$init$ != NULL) {
10501 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10502 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10503 }
10504 /* }}} */
10505 /* Set Locale {{{ */
10506 Locale_ = CFLocaleCopyCurrent();
10507 Languages_ = [NSLocale preferredLanguages];
10508
10509 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10510 //NSLog(@"%@", [Languages_ description]);
10511
10512 const char *lang;
10513 if (Locale_ != NULL)
10514 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10515 else if (Languages_ != nil && [Languages_ count] != 0)
10516 lang = [[Languages_ objectAtIndex:0] UTF8String];
10517 else
10518 // XXX: consider just setting to C and then falling through?
10519 lang = NULL;
10520
10521 if (lang != NULL) {
10522 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10523 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10524 }
10525
10526 NSLog(@"Setting Language: %s", lang);
10527
10528 if (lang != NULL) {
10529 setenv("LANG", lang, true);
10530 std::setlocale(LC_ALL, lang);
10531 }
10532 /* }}} */
10533
10534 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10535
10536 /* Parse Arguments {{{ */
10537 bool substrate(false);
10538
10539 if (argc != 0) {
10540 char **args(argv);
10541 int arge(1);
10542
10543 for (int argi(1); argi != argc; ++argi)
10544 if (strcmp(argv[argi], "--") == 0) {
10545 arge = argi;
10546 argv[argi] = argv[0];
10547 argv += argi;
10548 argc -= argi;
10549 break;
10550 }
10551
10552 for (int argi(1); argi != arge; ++argi)
10553 if (strcmp(args[argi], "--substrate") == 0)
10554 substrate = true;
10555 else
10556 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10557 }
10558 /* }}} */
10559
10560 App_ = [[NSBundle mainBundle] bundlePath];
10561 Advanced_ = YES;
10562
10563 setuid(0);
10564 setgid(0);
10565
10566 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10567 alloc_ = alloc->method_imp;
10568 alloc->method_imp = (IMP) &Alloc_;*/
10569
10570 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10571 dealloc_ = dealloc->method_imp;
10572 dealloc->method_imp = (IMP) &Dealloc_;*/
10573
10574 /* System Information {{{ */
10575 size_t size;
10576
10577 int maxproc;
10578 size = sizeof(maxproc);
10579 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10580 perror("sysctlbyname(\"kern.maxproc\", ?)");
10581 else if (maxproc < 64) {
10582 maxproc = 64;
10583 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10584 perror("sysctlbyname(\"kern.maxproc\", #)");
10585 }
10586
10587 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10588 char *osversion = new char[size];
10589 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10590 perror("sysctlbyname(\"kern.osversion\", ?)");
10591 else
10592 System_ = [NSString stringWithUTF8String:osversion];
10593
10594 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10595 char *machine = new char[size];
10596 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10597 perror("sysctlbyname(\"hw.machine\", ?)");
10598 else
10599 Machine_ = machine;
10600
10601 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10602 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10603 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10604
10605 UniqueID_ = [device uniqueIdentifier];
10606
10607 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10608 Product_ = [info objectForKey:@"SafariProductVersion"];
10609 Safari_ = [info objectForKey:@"CFBundleVersion"];
10610 }
10611
10612 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10613
10614 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10615 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10616 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10617 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10618 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10619 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10620
10621 UserAgent_ = agent;
10622 /* }}} */
10623 /* Load Database {{{ */
10624 _trace();
10625 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10626 _trace();
10627 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10628
10629 if (Metadata_ == NULL)
10630 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10631 else {
10632 Settings_ = [Metadata_ objectForKey:@"Settings"];
10633
10634 Packages_ = [Metadata_ objectForKey:@"Packages"];
10635
10636 Values_ = [Metadata_ objectForKey:@"Values"];
10637 Sections_ = [Metadata_ objectForKey:@"Sections"];
10638 Sources_ = [Metadata_ objectForKey:@"Sources"];
10639
10640 Token_ = [Metadata_ objectForKey:@"Token"];
10641
10642 Version_ = [Metadata_ objectForKey:@"Version"];
10643 }
10644
10645 if (Settings_ != nil)
10646 Role_ = [Settings_ objectForKey:@"Role"];
10647
10648 if (Values_ == nil) {
10649 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10650 [Metadata_ setObject:Values_ forKey:@"Values"];
10651 }
10652
10653 if (Sections_ == nil) {
10654 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10655 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10656 }
10657
10658 if (Sources_ == nil) {
10659 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10660 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10661 }
10662
10663 if (Version_ == nil) {
10664 Version_ = [NSNumber numberWithUnsignedInt:0];
10665 [Metadata_ setObject:Version_ forKey:@"Version"];
10666 }
10667
10668 if ([Version_ unsignedIntValue] == 0) {
10669 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10670 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10671 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10672 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10673
10674 Version_ = [NSNumber numberWithUnsignedInt:1];
10675 [Metadata_ setObject:Version_ forKey:@"Version"];
10676
10677 [Metadata_ removeObjectForKey:@"LastUpdate"];
10678
10679 Changed_ = true;
10680 }
10681 /* }}} */
10682
10683 CydiaWriteSources();
10684
10685 _trace();
10686 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10687 _trace();
10688
10689 if (Packages_ != nil) {
10690 bool fail(false);
10691 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10692 _trace();
10693
10694 if (!fail) {
10695 [Metadata_ removeObjectForKey:@"Packages"];
10696 Packages_ = nil;
10697 Changed_ = true;
10698 }
10699 }
10700
10701 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10702
10703 #define MobileSubstrate_(name) \
10704 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10705 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10706 if (handle == NULL) \
10707 NSLog(@"%s", dlerror()); \
10708 }
10709
10710 MobileSubstrate_(Activator)
10711 MobileSubstrate_(libstatusbar)
10712 MobileSubstrate_(SimulatedKeyEvents)
10713 MobileSubstrate_(WinterBoard)
10714
10715 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10716 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10717
10718 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10719
10720 if (access("/User", F_OK) != 0 || version != 5) {
10721 _trace();
10722 system("/usr/libexec/cydia/firmware.sh");
10723 _trace();
10724 }
10725
10726 _assert([[NSFileManager defaultManager]
10727 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10728 withIntermediateDirectories:YES
10729 attributes:nil
10730 error:NULL
10731 ]);
10732
10733 if (access("/tmp/cydia.chk", F_OK) == 0) {
10734 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10735 _assert(errno == ENOENT);
10736 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10737 _assert(errno == ENOENT);
10738 }
10739
10740 /* APT Initialization {{{ */
10741 _assert(pkgInitConfig(*_config));
10742 _assert(pkgInitSystem(*_config, _system));
10743
10744 if (lang != NULL)
10745 _config->Set("APT::Acquire::Translation", lang);
10746
10747 // XXX: this timeout might be important :(
10748 //_config->Set("Acquire::http::Timeout", 15);
10749
10750 _config->Set("Acquire::http::MaxParallel", 3);
10751 /* }}} */
10752 /* Color Choices {{{ */
10753 space_ = CGColorSpaceCreateDeviceRGB();
10754
10755 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10756 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10757 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10758 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10759 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10760 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10761 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10762 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10763 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10764
10765 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10766 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10767 /* }}}*/
10768 /* UIKit Configuration {{{ */
10769 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10770 if ($GSFontSetUseLegacyFontMetrics != NULL)
10771 $GSFontSetUseLegacyFontMetrics(YES);
10772
10773 // XXX: I have a feeling this was important
10774 //UIKeyboardDisableAutomaticAppearance();
10775 /* }}} */
10776
10777 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10778 ShowPromoted_ = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10779
10780 Colon_ = UCLocalize("COLON_DELIMITED");
10781 Elision_ = UCLocalize("ELISION");
10782 Error_ = UCLocalize("ERROR");
10783 Warning_ = UCLocalize("WARNING");
10784
10785 #if !ForRelease
10786 AprilFools_ = true;
10787 #else
10788 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10789 AprilFools_ = date.month == 4 && date.day == 1;
10790 #endif
10791
10792 _trace();
10793 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10794
10795 CGColorSpaceRelease(space_);
10796 CFRelease(Locale_);
10797
10798 [pool release];
10799 return value;
10800 }