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