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