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