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