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