]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Remove obsolete CYEmulatedLoadingController::database_.
[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 _H<CYLoadingIndicator> indicator_;
4237 _H<UITabBar> tabbar_;
4238 _H<UINavigationBar> navbar_;
4239 }
4240
4241 @end
4242
4243 @implementation CYEmulatedLoadingController
4244
4245 - (void) loadView {
4246 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4247
4248 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4249 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4250 [[self view] addSubview:table];
4251
4252 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4253 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4254 [[self view] addSubview:indicator_];
4255
4256 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4257 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4258 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4259 [[self view] addSubview:tabbar_];
4260
4261 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4262 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4263 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4264 [[self view] addSubview:navbar_];
4265 }
4266
4267 - (void) releaseSubviews {
4268 indicator_ = nil;
4269 tabbar_ = nil;
4270 navbar_ = nil;
4271 }
4272
4273 @end
4274 /* }}} */
4275
4276 /* Cydia Browser Controller {{{ */
4277 @implementation CydiaWebViewController
4278
4279 - (NSURL *) navigationURL {
4280 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4281 }
4282
4283 + (void) initialize {
4284 Diversions_ = [NSMutableSet setWithCapacity:0];
4285 }
4286
4287 + (void) addDiversion:(Diversion *)diversion {
4288 [Diversions_ addObject:diversion];
4289 }
4290
4291 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4292 [super webView:view didClearWindowObject:window forFrame:frame];
4293
4294 WebDataSource *source([frame dataSource]);
4295 NSURLResponse *response([source response]);
4296 NSURL *url([response URL]);
4297 NSString *scheme([[url scheme] lowercaseString]);
4298
4299 bool bridged(false);
4300
4301 @synchronized (HostConfig_) {
4302 if ([scheme isEqualToString:@"file"])
4303 bridged = true;
4304 else if ([scheme isEqualToString:@"https"])
4305 if ([BridgedHosts_ containsObject:[url host]])
4306 bridged = true;
4307 }
4308
4309 if (bridged)
4310 [window setValue:cydia_ forKey:@"cydia"];
4311 }
4312
4313 - (NSURL *) URLWithURL:(NSURL *)url {
4314 return [Diversion divertURL:url];
4315 }
4316
4317 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4318 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4319
4320 if (System_ != NULL)
4321 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4322 if (Machine_ != NULL)
4323 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4324 if (Token_ != nil)
4325 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4326
4327 return copy;
4328 }
4329
4330 - (void) setDelegate:(id)delegate {
4331 [super setDelegate:delegate];
4332 [cydia_ setDelegate:delegate];
4333 }
4334
4335 - (id) init {
4336 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4337 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4338
4339 WebView *webview([[webview_ _documentView] webView]);
4340
4341 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4342
4343 if (Safari_ != nil)
4344 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4345 if (Build_ != nil)
4346 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4347 if (Product_ != nil)
4348 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4349
4350 [webview setApplicationNameForUserAgent:application];
4351 } return self;
4352 }
4353
4354 @end
4355 /* }}} */
4356
4357 // CydiaScript {{{
4358 @interface NSObject (CydiaScript)
4359 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4360 @end
4361
4362 @implementation NSObject (CydiaScript)
4363
4364 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4365 return self;
4366 }
4367
4368 @end
4369
4370 @implementation NSArray (CydiaScript)
4371
4372 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4373 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4374 for (size_t i(0), e([self count]); i != e; ++i)
4375 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4376 return object;
4377 }
4378
4379 @end
4380
4381 @implementation NSDictionary (CydiaScript)
4382
4383 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4384 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4385 for (id i in self)
4386 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4387 return object;
4388 }
4389
4390 @end
4391 // }}}
4392
4393 /* Confirmation Controller {{{ */
4394 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4395 if (!iterator.end())
4396 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4397 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4398 continue;
4399 pkgCache::PkgIterator package(dep.TargetPkg());
4400 if (package.end())
4401 continue;
4402 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4403 return true;
4404 }
4405
4406 return false;
4407 }
4408
4409 @protocol ConfirmationControllerDelegate
4410 - (void) cancelAndClear:(bool)clear;
4411 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4412 - (void) queue;
4413 @end
4414
4415 @interface ConfirmationController : CydiaWebViewController {
4416 _transient Database *database_;
4417
4418 _H<UIAlertView> essential_;
4419
4420 _H<NSDictionary> changes_;
4421 _H<NSMutableArray> issues_;
4422 _H<NSDictionary> sizes_;
4423
4424 BOOL substrate_;
4425 }
4426
4427 - (id) initWithDatabase:(Database *)database;
4428
4429 @end
4430
4431 @implementation ConfirmationController
4432
4433 - (void) complete {
4434 if (substrate_)
4435 RestartSubstrate_ = true;
4436 [delegate_ confirmWithNavigationController:[self navigationController]];
4437 }
4438
4439 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4440 NSString *context([alert context]);
4441
4442 if ([context isEqualToString:@"remove"]) {
4443 if (button == [alert cancelButtonIndex])
4444 [self dismissModalViewControllerAnimated:YES];
4445 else if (button == [alert firstOtherButtonIndex]) {
4446 [self complete];
4447 }
4448
4449 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4450 } else if ([context isEqualToString:@"unable"]) {
4451 [self dismissModalViewControllerAnimated:YES];
4452 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4453 } else {
4454 [super alertView:alert clickedButtonAtIndex:button];
4455 }
4456 }
4457
4458 - (void) _doContinue {
4459 [self dismissModalViewControllerAnimated:YES];
4460 [delegate_ cancelAndClear:NO];
4461 }
4462
4463 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4464 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4465 return nil;
4466 }
4467
4468 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4469 [super webView:view didClearWindowObject:window forFrame:frame];
4470
4471 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4472 (id) changes_, @"changes",
4473 (id) issues_, @"issues",
4474 (id) sizes_, @"sizes",
4475 self, @"queue",
4476 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4477 }
4478
4479 - (id) initWithDatabase:(Database *)database {
4480 if ((self = [super init]) != nil) {
4481 database_ = database;
4482
4483 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4484 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4485 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4486 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4487 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4488
4489 bool remove(false);
4490
4491 pkgCacheFile &cache([database_ cache]);
4492 NSArray *packages([database_ packages]);
4493 pkgDepCache::Policy *policy([database_ policy]);
4494
4495 issues_ = [NSMutableArray arrayWithCapacity:4];
4496
4497 for (Package *package in packages) {
4498 pkgCache::PkgIterator iterator([package iterator]);
4499 NSString *name([package id]);
4500
4501 if ([package broken]) {
4502 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4503
4504 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4505 name, @"package",
4506 reasons, @"reasons",
4507 nil]];
4508
4509 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4510 if (ver.end())
4511 continue;
4512
4513 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4514 pkgCache::DepIterator start;
4515 pkgCache::DepIterator end;
4516 dep.GlobOr(start, end); // ++dep
4517
4518 if (!cache->IsImportantDep(end))
4519 continue;
4520 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4521 continue;
4522
4523 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4524
4525 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4526 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4527 clauses, @"clauses",
4528 nil]];
4529
4530 _forever {
4531 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4532
4533 pkgCache::PkgIterator target(start.TargetPkg());
4534 if (target->ProvidesList != 0)
4535 reason = @"missing";
4536 else {
4537 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4538 if (!ver.end()) {
4539 reason = @"installed";
4540 installed = [NSString stringWithUTF8String:ver.VerStr()];
4541 } else if (!cache[target].CandidateVerIter(cache).end())
4542 reason = @"uninstalled";
4543 else if (target->ProvidesList == 0)
4544 reason = @"uninstallable";
4545 else
4546 reason = @"virtual";
4547 }
4548
4549 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4550 [NSString stringWithUTF8String:start.CompType()], @"operator",
4551 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4552 nil]);
4553
4554 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4555 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4556 version, @"version",
4557 reason, @"reason",
4558 installed, @"installed",
4559 nil]];
4560
4561 // yes, seriously. (wtf?)
4562 if (start == end)
4563 break;
4564 ++start;
4565 }
4566 }
4567 }
4568
4569 pkgDepCache::StateCache &state(cache[iterator]);
4570
4571 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4572
4573 if (state.NewInstall())
4574 [installs addObject:name];
4575 // XXX: else if (state.Install())
4576 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4577 [reinstalls addObject:name];
4578 // XXX: move before previous if
4579 else if (state.Upgrade())
4580 [upgrades addObject:name];
4581 else if (state.Downgrade())
4582 [downgrades addObject:name];
4583 else if (!state.Delete())
4584 // XXX: _assert(state.Keep());
4585 continue;
4586 else if (special_r(name))
4587 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4588 [NSNull null], @"package",
4589 [NSArray arrayWithObjects:
4590 [NSDictionary dictionaryWithObjectsAndKeys:
4591 @"Conflicts", @"relationship",
4592 [NSArray arrayWithObjects:
4593 [NSDictionary dictionaryWithObjectsAndKeys:
4594 name, @"package",
4595 [NSNull null], @"version",
4596 @"installed", @"reason",
4597 nil],
4598 nil], @"clauses",
4599 nil],
4600 nil], @"reasons",
4601 nil]];
4602 else {
4603 if ([package essential])
4604 remove = true;
4605 [removes addObject:name];
4606 }
4607
4608 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4609 substrate_ |= DepSubstrate(iterator.CurrentVer());
4610 }
4611
4612 if (!remove)
4613 essential_ = nil;
4614 else if (Advanced_) {
4615 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4616
4617 essential_ = [[[UIAlertView alloc]
4618 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4619 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4620 delegate:self
4621 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4622 otherButtonTitles:
4623 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4624 nil
4625 ] autorelease];
4626
4627 [essential_ setContext:@"remove"];
4628 } else {
4629 essential_ = [[[UIAlertView alloc]
4630 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4631 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4632 delegate:self
4633 cancelButtonTitle:UCLocalize("OKAY")
4634 otherButtonTitles:nil
4635 ] autorelease];
4636
4637 [essential_ setContext:@"unable"];
4638 }
4639
4640 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4641 installs, @"installs",
4642 reinstalls, @"reinstalls",
4643 upgrades, @"upgrades",
4644 downgrades, @"downgrades",
4645 removes, @"removes",
4646 nil];
4647
4648 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4649 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4650 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4651 nil];
4652
4653 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4654 } return self;
4655 }
4656
4657 - (UIBarButtonItem *) leftButton {
4658 return [[[UIBarButtonItem alloc]
4659 initWithTitle:UCLocalize("CANCEL")
4660 style:UIBarButtonItemStylePlain
4661 target:self
4662 action:@selector(cancelButtonClicked)
4663 ] autorelease];
4664 }
4665
4666 #if !AlwaysReload
4667 - (void) applyRightButton {
4668 if ([issues_ count] == 0 && ![self isLoading])
4669 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4670 initWithTitle:UCLocalize("CONFIRM")
4671 style:UIBarButtonItemStyleDone
4672 target:self
4673 action:@selector(confirmButtonClicked)
4674 ] autorelease]];
4675 else
4676 [[self navigationItem] setRightBarButtonItem:nil];
4677 }
4678 #endif
4679
4680 - (void) cancelButtonClicked {
4681 [self dismissModalViewControllerAnimated:YES];
4682 [delegate_ cancelAndClear:YES];
4683 }
4684
4685 #if !AlwaysReload
4686 - (void) confirmButtonClicked {
4687 if (essential_ != nil)
4688 [essential_ show];
4689 else
4690 [self complete];
4691 }
4692 #endif
4693
4694 @end
4695 /* }}} */
4696
4697 /* Progress Data {{{ */
4698 @interface CydiaProgressData : NSObject {
4699 _transient id delegate_;
4700
4701 bool running_;
4702 float percent_;
4703
4704 float current_;
4705 float total_;
4706 float speed_;
4707
4708 _H<NSMutableArray> events_;
4709 _H<NSString> title_;
4710
4711 _H<NSString> status_;
4712 _H<NSString> finish_;
4713 }
4714
4715 @end
4716
4717 @implementation CydiaProgressData
4718
4719 + (NSArray *) _attributeKeys {
4720 return [NSArray arrayWithObjects:
4721 @"current",
4722 @"events",
4723 @"finish",
4724 @"percent",
4725 @"running",
4726 @"speed",
4727 @"title",
4728 @"total",
4729 nil];
4730 }
4731
4732 - (NSArray *) attributeKeys {
4733 return [[self class] _attributeKeys];
4734 }
4735
4736 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4737 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4738 }
4739
4740 - (id) init {
4741 if ((self = [super init]) != nil) {
4742 events_ = [NSMutableArray arrayWithCapacity:32];
4743 } return self;
4744 }
4745
4746 - (void) setDelegate:(id)delegate {
4747 delegate_ = delegate;
4748 }
4749
4750 - (void) setPercent:(float)value {
4751 percent_ = value;
4752 }
4753
4754 - (NSNumber *) percent {
4755 return [NSNumber numberWithFloat:percent_];
4756 }
4757
4758 - (void) setCurrent:(float)value {
4759 current_ = value;
4760 }
4761
4762 - (NSNumber *) current {
4763 return [NSNumber numberWithFloat:current_];
4764 }
4765
4766 - (void) setTotal:(float)value {
4767 total_ = value;
4768 }
4769
4770 - (NSNumber *) total {
4771 return [NSNumber numberWithFloat:total_];
4772 }
4773
4774 - (void) setSpeed:(float)value {
4775 speed_ = value;
4776 }
4777
4778 - (NSNumber *) speed {
4779 return [NSNumber numberWithFloat:speed_];
4780 }
4781
4782 - (NSArray *) events {
4783 return events_;
4784 }
4785
4786 - (void) removeAllEvents {
4787 [events_ removeAllObjects];
4788 }
4789
4790 - (void) addEvent:(CydiaProgressEvent *)event {
4791 [events_ addObject:event];
4792 }
4793
4794 - (void) setTitle:(NSString *)text {
4795 title_ = text;
4796 }
4797
4798 - (NSString *) title {
4799 return title_;
4800 }
4801
4802 - (void) setFinish:(NSString *)text {
4803 finish_ = text;
4804 }
4805
4806 - (NSString *) finish {
4807 return (id) finish_ ?: [NSNull null];
4808 }
4809
4810 - (void) setRunning:(bool)running {
4811 running_ = running;
4812 }
4813
4814 - (NSNumber *) running {
4815 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4816 }
4817
4818 @end
4819 /* }}} */
4820 /* Progress Controller {{{ */
4821 @interface ProgressController : CydiaWebViewController <
4822 ProgressDelegate
4823 > {
4824 _transient Database *database_;
4825 _H<CydiaProgressData, 1> progress_;
4826 unsigned cancel_;
4827 }
4828
4829 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4830
4831 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4832
4833 - (void) setTitle:(NSString *)title;
4834 - (void) setCancellable:(bool)cancellable;
4835
4836 @end
4837
4838 @implementation ProgressController
4839
4840 - (void) dealloc {
4841 [database_ setProgressDelegate:nil];
4842 [super dealloc];
4843 }
4844
4845 - (UIBarButtonItem *) leftButton {
4846 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4847 initWithTitle:UCLocalize("CANCEL")
4848 style:UIBarButtonItemStylePlain
4849 target:self
4850 action:@selector(cancel)
4851 ] autorelease] : nil;
4852 }
4853
4854 - (void) updateCancel {
4855 [super applyLeftButton];
4856 }
4857
4858 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4859 if ((self = [super init]) != nil) {
4860 database_ = database;
4861 delegate_ = delegate;
4862
4863 [database_ setProgressDelegate:self];
4864
4865 progress_ = [[[CydiaProgressData alloc] init] autorelease];
4866 [progress_ setDelegate:self];
4867
4868 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
4869
4870 [scroller_ setBackgroundColor:[UIColor blackColor]];
4871
4872 [[self navigationItem] setHidesBackButton:YES];
4873
4874 [self updateCancel];
4875 } return self;
4876 }
4877
4878 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4879 [super webView:view didClearWindowObject:window forFrame:frame];
4880 [window setValue:progress_ forKey:@"cydiaProgress"];
4881 }
4882
4883 - (void) updateProgress {
4884 [self dispatchEvent:@"CydiaProgressUpdate"];
4885 }
4886
4887 - (void) viewWillAppear:(BOOL)animated {
4888 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4889 [super viewWillAppear:animated];
4890 }
4891
4892 - (void) close {
4893 UpdateExternalStatus(0);
4894
4895 switch (Finish_) {
4896 case 0:
4897 break;
4898
4899 case 1:
4900 [delegate_ terminateWithSuccess];
4901 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4902 [delegate_ suspendWithAnimation:YES];
4903 else
4904 [delegate_ suspend];*/
4905 break;
4906
4907 case 2:
4908 _trace();
4909 goto reload;
4910
4911 case 3:
4912 _trace();
4913 goto reload;
4914
4915 reload:
4916 system("/usr/bin/sbreload");
4917 _trace();
4918 break;
4919
4920 case 4:
4921 _trace();
4922 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4923 SBReboot(SBSSpringBoardServerPort());
4924 else
4925 reboot2(RB_AUTOBOOT);
4926 break;
4927 }
4928
4929 [super close];
4930 }
4931
4932 - (void) setTitle:(NSString *)title {
4933 [progress_ setTitle:title];
4934 [self updateProgress];
4935 }
4936
4937 - (UIBarButtonItem *) rightButton {
4938 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
4939 initWithTitle:UCLocalize("CLOSE")
4940 style:UIBarButtonItemStylePlain
4941 target:self
4942 action:@selector(close)
4943 ] autorelease];
4944 }
4945
4946 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4947 UpdateExternalStatus(1);
4948
4949 [progress_ setRunning:true];
4950 [self setTitle:title];
4951 // implicit updateProgress
4952
4953 SHA1SumValue notifyconf; {
4954 FileFd file;
4955 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4956 _error->Discard();
4957 else {
4958 MMap mmap(file, MMap::ReadOnly);
4959 SHA1Summation sha1;
4960 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4961 notifyconf = sha1.Result();
4962 }
4963 }
4964
4965 SHA1SumValue springlist; {
4966 FileFd file;
4967 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4968 _error->Discard();
4969 else {
4970 MMap mmap(file, MMap::ReadOnly);
4971 SHA1Summation sha1;
4972 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4973 springlist = sha1.Result();
4974 }
4975 }
4976
4977 if (invocation != nil) {
4978 [invocation yieldToSelector:@selector(invoke)];
4979 [self setTitle:@"COMPLETE"];
4980 }
4981
4982 if (Finish_ < 4) {
4983 FileFd file;
4984 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4985 _error->Discard();
4986 else {
4987 MMap mmap(file, MMap::ReadOnly);
4988 SHA1Summation sha1;
4989 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4990 if (!(notifyconf == sha1.Result()))
4991 Finish_ = 4;
4992 }
4993 }
4994
4995 if (Finish_ < 3) {
4996 FileFd file;
4997 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4998 _error->Discard();
4999 else {
5000 MMap mmap(file, MMap::ReadOnly);
5001 SHA1Summation sha1;
5002 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5003 if (!(springlist == sha1.Result()))
5004 Finish_ = 3;
5005 }
5006 }
5007
5008 if (Finish_ < 2) {
5009 if (RestartSubstrate_)
5010 Finish_ = 2;
5011 }
5012
5013 RestartSubstrate_ = false;
5014
5015 switch (Finish_) {
5016 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5017 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5018 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5019 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5020 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5021 }
5022
5023 _trace();
5024 system("su -c /usr/bin/uicache mobile");
5025 _trace();
5026
5027 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5028
5029 [progress_ setRunning:false];
5030 [self updateProgress];
5031
5032 [self applyRightButton];
5033 }
5034
5035 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5036 [progress_ addEvent:event];
5037 [self updateProgress];
5038 }
5039
5040 - (bool) isProgressCancelled {
5041 return cancel_ == 2;
5042 }
5043
5044 - (void) cancel {
5045 cancel_ = 2;
5046 [self updateCancel];
5047 }
5048
5049 - (void) setCancellable:(bool)cancellable {
5050 unsigned cancel(cancel_);
5051
5052 if (!cancellable)
5053 cancel_ = 0;
5054 else if (cancel_ == 0)
5055 cancel_ = 1;
5056
5057 if (cancel != cancel_)
5058 [self updateCancel];
5059 }
5060
5061 - (void) setProgressCancellable:(NSNumber *)cancellable {
5062 [self setCancellable:[cancellable boolValue]];
5063 }
5064
5065 - (void) setProgressPercent:(NSNumber *)percent {
5066 [progress_ setPercent:[percent floatValue]];
5067 [self updateProgress];
5068 }
5069
5070 - (void) setProgressStatus:(NSDictionary *)status {
5071 if (status == nil) {
5072 [progress_ setCurrent:0];
5073 [progress_ setTotal:0];
5074 [progress_ setSpeed:0];
5075 } else {
5076 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5077
5078 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5079 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5080 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5081 }
5082
5083 [self updateProgress];
5084 }
5085
5086 @end
5087 /* }}} */
5088
5089 /* Package Cell {{{ */
5090 @interface PackageCell : CyteTableViewCell <
5091 CyteTableViewCellDelegate
5092 > {
5093 _H<UIImage> icon_;
5094 _H<NSString> name_;
5095 _H<NSString> description_;
5096 bool commercial_;
5097 _H<NSString> source_;
5098 _H<UIImage> badge_;
5099 _H<Package> package_;
5100 _H<UIImage> placard_;
5101 bool summarized_;
5102 }
5103
5104 - (PackageCell *) init;
5105 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5106
5107 - (void) drawContentRect:(CGRect)rect;
5108
5109 @end
5110
5111 @implementation PackageCell
5112
5113 - (PackageCell *) init {
5114 CGRect frame(CGRectMake(0, 0, 320, 74));
5115 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5116 UIView *content([self contentView]);
5117 CGRect bounds([content bounds]);
5118
5119 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5120 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5121 [content addSubview:content_];
5122
5123 [content_ setDelegate:self];
5124 [content_ setOpaque:YES];
5125 } return self;
5126 }
5127
5128 - (NSString *) accessibilityLabel {
5129 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5130 }
5131
5132 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5133 summarized_ = summary;
5134
5135 icon_ = nil;
5136 name_ = nil;
5137 description_ = nil;
5138 source_ = nil;
5139 badge_ = nil;
5140 placard_ = nil;
5141 package_ = nil;
5142
5143 [package parse];
5144
5145 Source *source = [package source];
5146
5147 icon_ = [package icon];
5148 name_ = [package name];
5149
5150 if (IsWildcat_)
5151 description_ = [package longDescription];
5152 if (description_ == nil)
5153 description_ = [package shortDescription];
5154
5155 commercial_ = [package isCommercial];
5156
5157 package_ = package;
5158
5159 NSString *label = nil;
5160 bool trusted = false;
5161
5162 if (source != nil) {
5163 label = [source label];
5164 trusted = [source trusted];
5165 } else if ([[package id] isEqualToString:@"firmware"])
5166 label = UCLocalize("APPLE");
5167 else
5168 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5169
5170 NSString *from(label);
5171
5172 NSString *section = [package simpleSection];
5173 if (section != nil && ![section isEqualToString:label]) {
5174 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5175 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5176 }
5177
5178 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5179
5180 if (NSString *purpose = [package primaryPurpose])
5181 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5182
5183 UIColor *color;
5184 NSString *placard;
5185
5186 if (NSString *mode = [package_ mode]) {
5187 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5188 color = RemovingColor_;
5189 //placard = @"removing";
5190 } else {
5191 color = InstallingColor_;
5192 //placard = @"installing";
5193 }
5194
5195 // XXX: the removing/installing placards are not @2x
5196 placard = nil;
5197 } else {
5198 color = [UIColor whiteColor];
5199
5200 if ([package installed] != nil)
5201 placard = @"installed";
5202 else
5203 placard = nil;
5204 }
5205
5206 [content_ setBackgroundColor:color];
5207
5208 if (placard != nil)
5209 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5210
5211 [self setNeedsDisplay];
5212 [content_ setNeedsDisplay];
5213 }
5214
5215 - (void) drawSummaryContentRect:(CGRect)rect {
5216 bool highlighted(highlighted_);
5217 float width([self bounds].size.width);
5218
5219 if (icon_ != nil) {
5220 CGRect rect;
5221 rect.size = [(UIImage *) icon_ size];
5222
5223 rect.size.width /= 4;
5224 rect.size.height /= 4;
5225
5226 rect.origin.x = 14 - rect.size.width / 4;
5227 rect.origin.y = 14 - rect.size.height / 4;
5228
5229 [icon_ drawInRect:rect];
5230 }
5231
5232 if (badge_ != nil) {
5233 CGRect rect;
5234 rect.size = [(UIImage *) badge_ size];
5235
5236 rect.size.width /= 4;
5237 rect.size.height /= 4;
5238
5239 rect.origin.x = 20 - rect.size.width / 4;
5240 rect.origin.y = 20 - rect.size.height / 4;
5241
5242 [badge_ drawInRect:rect];
5243 }
5244
5245 if (highlighted)
5246 UISetColor(White_);
5247
5248 if (!highlighted)
5249 UISetColor(commercial_ ? Purple_ : Black_);
5250 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5251
5252 if (placard_ != nil)
5253 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5254 }
5255
5256 - (void) drawNormalContentRect:(CGRect)rect {
5257 bool highlighted(highlighted_);
5258 float width([self bounds].size.width);
5259
5260 if (icon_ != nil) {
5261 CGRect rect;
5262 rect.size = [(UIImage *) icon_ size];
5263
5264 rect.size.width /= 2;
5265 rect.size.height /= 2;
5266
5267 rect.origin.x = 25 - rect.size.width / 2;
5268 rect.origin.y = 25 - rect.size.height / 2;
5269
5270 [icon_ drawInRect:rect];
5271 }
5272
5273 if (badge_ != nil) {
5274 CGRect rect;
5275 rect.size = [(UIImage *) badge_ size];
5276
5277 rect.size.width /= 2;
5278 rect.size.height /= 2;
5279
5280 rect.origin.x = 36 - rect.size.width / 2;
5281 rect.origin.y = 36 - rect.size.height / 2;
5282
5283 [badge_ drawInRect:rect];
5284 }
5285
5286 if (highlighted)
5287 UISetColor(White_);
5288
5289 if (!highlighted)
5290 UISetColor(commercial_ ? Purple_ : Black_);
5291 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5292 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5293
5294 if (!highlighted)
5295 UISetColor(commercial_ ? Purplish_ : Gray_);
5296 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5297
5298 if (placard_ != nil)
5299 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5300 }
5301
5302 - (void) drawContentRect:(CGRect)rect {
5303 if (summarized_)
5304 [self drawSummaryContentRect:rect];
5305 else
5306 [self drawNormalContentRect:rect];
5307 }
5308
5309 @end
5310 /* }}} */
5311 /* Section Cell {{{ */
5312 @interface SectionCell : CyteTableViewCell <
5313 CyteTableViewCellDelegate
5314 > {
5315 _H<NSString> basic_;
5316 _H<NSString> section_;
5317 _H<NSString> name_;
5318 _H<NSString> count_;
5319 _H<UIImage> icon_;
5320 _H<UISwitch> switch_;
5321 BOOL editing_;
5322 }
5323
5324 - (void) setSection:(Section *)section editing:(BOOL)editing;
5325
5326 @end
5327
5328 @implementation SectionCell
5329
5330 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5331 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5332 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5333 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5334 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5335
5336 UIView *content([self contentView]);
5337 CGRect bounds([content bounds]);
5338
5339 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5340 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5341 [content addSubview:content_];
5342 [content_ setBackgroundColor:[UIColor whiteColor]];
5343
5344 [content_ setDelegate:self];
5345 } return self;
5346 }
5347
5348 - (void) onSwitch:(id)sender {
5349 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5350 if (metadata == nil) {
5351 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5352 [Sections_ setObject:metadata forKey:basic_];
5353 }
5354
5355 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5356 Changed_ = true;
5357 }
5358
5359 - (void) setSection:(Section *)section editing:(BOOL)editing {
5360 if (editing != editing_) {
5361 if (editing_)
5362 [switch_ removeFromSuperview];
5363 else
5364 [self addSubview:switch_];
5365 editing_ = editing;
5366 }
5367
5368 basic_ = nil;
5369 section_ = nil;
5370 name_ = nil;
5371 count_ = nil;
5372
5373 if (section == nil) {
5374 name_ = UCLocalize("ALL_PACKAGES");
5375 count_ = nil;
5376 } else {
5377 basic_ = [section name];
5378 section_ = [section localized];
5379
5380 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5381 count_ = [NSString stringWithFormat:@"%d", [section count]];
5382
5383 if (editing_)
5384 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5385 }
5386
5387 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5388 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5389
5390 [content_ setNeedsDisplay];
5391 }
5392
5393 - (void) setFrame:(CGRect)frame {
5394 [super setFrame:frame];
5395
5396 CGRect rect([switch_ frame]);
5397 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5398 }
5399
5400 - (NSString *) accessibilityLabel {
5401 return name_;
5402 }
5403
5404 - (void) drawContentRect:(CGRect)rect {
5405 bool highlighted(highlighted_ && !editing_);
5406
5407 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5408
5409 if (highlighted)
5410 UISetColor(White_);
5411
5412 float width(rect.size.width);
5413 if (editing_)
5414 width -= 87;
5415
5416 if (!highlighted)
5417 UISetColor(Black_);
5418 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5419
5420 CGSize size = [count_ sizeWithFont:Font14_];
5421
5422 UISetColor(White_);
5423 if (count_ != nil)
5424 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5425 }
5426
5427 @end
5428 /* }}} */
5429
5430 /* File Table {{{ */
5431 @interface FileTable : CyteViewController <
5432 UITableViewDataSource,
5433 UITableViewDelegate
5434 > {
5435 _transient Database *database_;
5436 _H<Package> package_;
5437 _H<NSString> name_;
5438 _H<NSMutableArray> files_;
5439 _H<UITableView, 2> list_;
5440 }
5441
5442 - (id) initWithDatabase:(Database *)database;
5443 - (void) setPackage:(Package *)package;
5444
5445 @end
5446
5447 @implementation FileTable
5448
5449 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5450 return files_ == nil ? 0 : [files_ count];
5451 }
5452
5453 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5454 return 24.0f;
5455 }*/
5456
5457 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5458 static NSString *reuseIdentifier = @"Cell";
5459
5460 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5461 if (cell == nil) {
5462 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5463 [cell setFont:[UIFont systemFontOfSize:16]];
5464 }
5465 [cell setText:[files_ objectAtIndex:indexPath.row]];
5466 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5467
5468 return cell;
5469 }
5470
5471 - (NSURL *) navigationURL {
5472 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5473 }
5474
5475 - (void) loadView {
5476 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5477
5478 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5479 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5480 [list_ setRowHeight:24.0f];
5481 [(UITableView *) list_ setDataSource:self];
5482 [list_ setDelegate:self];
5483 [[self view] addSubview:list_];
5484 }
5485
5486 - (void) viewDidLoad {
5487 [super viewDidLoad];
5488
5489 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5490 }
5491
5492 - (void) releaseSubviews {
5493 list_ = nil;
5494 }
5495
5496 - (id) initWithDatabase:(Database *)database {
5497 if ((self = [super init]) != nil) {
5498 database_ = database;
5499
5500 files_ = [NSMutableArray arrayWithCapacity:32];
5501 } return self;
5502 }
5503
5504 - (void) setPackage:(Package *)package {
5505 package_ = nil;
5506 name_ = nil;
5507
5508 [files_ removeAllObjects];
5509
5510 if (package != nil) {
5511 package_ = package;
5512 name_ = [package id];
5513
5514 if (NSArray *files = [package files])
5515 [files_ addObjectsFromArray:files];
5516
5517 if ([files_ count] != 0) {
5518 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5519 [files_ removeObjectAtIndex:0];
5520 [files_ sortUsingSelector:@selector(compareByPath:)];
5521
5522 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5523 [stack addObject:@"/"];
5524
5525 for (int i(0), e([files_ count]); i != e; ++i) {
5526 NSString *file = [files_ objectAtIndex:i];
5527 while (![file hasPrefix:[stack lastObject]])
5528 [stack removeLastObject];
5529 NSString *directory = [stack lastObject];
5530 [stack addObject:[file stringByAppendingString:@"/"]];
5531 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5532 ([stack count] - 2) * 3, "",
5533 [file substringFromIndex:[directory length]]
5534 ]];
5535 }
5536 }
5537 }
5538
5539 [list_ reloadData];
5540 }
5541
5542 - (void) reloadData {
5543 [super reloadData];
5544
5545 [self setPackage:[database_ packageWithName:name_]];
5546 }
5547
5548 @end
5549 /* }}} */
5550 /* Package Controller {{{ */
5551 @interface CYPackageController : CydiaWebViewController <
5552 UIActionSheetDelegate
5553 > {
5554 _transient Database *database_;
5555 _H<Package> package_;
5556 _H<NSString> name_;
5557 bool commercial_;
5558 _H<NSMutableArray> buttons_;
5559 _H<UIBarButtonItem> button_;
5560 }
5561
5562 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5563
5564 @end
5565
5566 @implementation CYPackageController
5567
5568 - (NSURL *) navigationURL {
5569 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5570 }
5571
5572 /* XXX: this is not safe at all... localization of /fail/ */
5573 - (void) _clickButtonWithName:(NSString *)name {
5574 if ([name isEqualToString:UCLocalize("CLEAR")])
5575 [delegate_ clearPackage:package_];
5576 else if ([name isEqualToString:UCLocalize("INSTALL")])
5577 [delegate_ installPackage:package_];
5578 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5579 [delegate_ installPackage:package_];
5580 else if ([name isEqualToString:UCLocalize("REMOVE")])
5581 [delegate_ removePackage:package_];
5582 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5583 [delegate_ installPackage:package_];
5584 else _assert(false);
5585 }
5586
5587 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5588 NSString *context([sheet context]);
5589
5590 if ([context isEqualToString:@"modify"]) {
5591 if (button != [sheet cancelButtonIndex]) {
5592 NSString *buttonName = [buttons_ objectAtIndex:button];
5593 [self _clickButtonWithName:buttonName];
5594 }
5595
5596 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5597 }
5598 }
5599
5600 - (bool) _allowJavaScriptPanel {
5601 return commercial_;
5602 }
5603
5604 #if !AlwaysReload
5605 - (void) _customButtonClicked {
5606 int count([buttons_ count]);
5607 if (count == 0)
5608 return;
5609
5610 if (count == 1)
5611 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5612 else {
5613 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5614 [buttons addObjectsFromArray:buttons_];
5615
5616 UIActionSheet *sheet = [[[UIActionSheet alloc]
5617 initWithTitle:nil
5618 delegate:self
5619 cancelButtonTitle:nil
5620 destructiveButtonTitle:nil
5621 otherButtonTitles:nil
5622 ] autorelease];
5623
5624 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5625 if (!IsWildcat_) {
5626 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5627 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5628 }
5629 [sheet setContext:@"modify"];
5630
5631 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5632 }
5633 }
5634
5635 // We don't want to allow non-commercial packages to do custom things to the install button,
5636 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5637 - (void) customButtonClicked {
5638 if (commercial_)
5639 [super customButtonClicked];
5640 else
5641 [self _customButtonClicked];
5642 }
5643
5644 - (void) reloadButtonClicked {
5645 // Don't reload a commerical package by tapping the loading button,
5646 // but if it's not an Install button, we should forward it on.
5647 if (![package_ uninstalled])
5648 [self _customButtonClicked];
5649 }
5650
5651 - (void) applyLoadingTitle {
5652 // Don't show "Loading" as the title. Ever.
5653 }
5654
5655 - (UIBarButtonItem *) rightButton {
5656 return button_;
5657 }
5658 #endif
5659
5660 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5661 if ((self = [super init]) != nil) {
5662 database_ = database;
5663 buttons_ = [NSMutableArray arrayWithCapacity:4];
5664 name_ = [NSString stringWithString:name];
5665 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5666 } return self;
5667 }
5668
5669 - (void) reloadData {
5670 [super reloadData];
5671
5672 package_ = [database_ packageWithName:name_];
5673
5674 [buttons_ removeAllObjects];
5675
5676 if (package_ != nil) {
5677 [(Package *) package_ parse];
5678
5679 commercial_ = [package_ isCommercial];
5680
5681 if ([package_ mode] != nil)
5682 [buttons_ addObject:UCLocalize("CLEAR")];
5683 if ([package_ source] == nil);
5684 else if ([package_ upgradableAndEssential:NO])
5685 [buttons_ addObject:UCLocalize("UPGRADE")];
5686 else if ([package_ uninstalled])
5687 [buttons_ addObject:UCLocalize("INSTALL")];
5688 else
5689 [buttons_ addObject:UCLocalize("REINSTALL")];
5690 if (![package_ uninstalled])
5691 [buttons_ addObject:UCLocalize("REMOVE")];
5692 }
5693
5694 NSString *title;
5695 switch ([buttons_ count]) {
5696 case 0: title = nil; break;
5697 case 1: title = [buttons_ objectAtIndex:0]; break;
5698 default: title = UCLocalize("MODIFY"); break;
5699 }
5700
5701 button_ = [[[UIBarButtonItem alloc]
5702 initWithTitle:title
5703 style:UIBarButtonItemStylePlain
5704 target:self
5705 action:@selector(customButtonClicked)
5706 ] autorelease];
5707 }
5708
5709 - (bool) isLoading {
5710 return commercial_ ? [super isLoading] : false;
5711 }
5712
5713 @end
5714 /* }}} */
5715
5716 /* Package List Controller {{{ */
5717 @interface PackageListController : CyteViewController <
5718 UITableViewDataSource,
5719 UITableViewDelegate
5720 > {
5721 _transient Database *database_;
5722 unsigned era_;
5723 _H<NSArray> packages_;
5724 _H<NSMutableArray> sections_;
5725 _H<UITableView, 2> list_;
5726 _H<NSMutableArray> index_;
5727 _H<NSMutableDictionary> indices_;
5728 _H<NSString> title_;
5729 unsigned reloading_;
5730 }
5731
5732 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5733 - (void) setDelegate:(id)delegate;
5734 - (void) resetCursor;
5735 - (void) clearData;
5736
5737 @end
5738
5739 @implementation PackageListController
5740
5741 - (bool) isSummarized {
5742 return false;
5743 }
5744
5745 - (void) deselectWithAnimation:(BOOL)animated {
5746 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5747 }
5748
5749 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5750 CGRect base = [[self view] bounds];
5751 base.size.height -= bounds.size.height;
5752 base.origin = [list_ frame].origin;
5753
5754 [UIView beginAnimations:nil context:NULL];
5755 [UIView setAnimationBeginsFromCurrentState:YES];
5756 [UIView setAnimationCurve:curve];
5757 [UIView setAnimationDuration:duration];
5758 [list_ setFrame:base];
5759 [UIView commitAnimations];
5760 }
5761
5762 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5763 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5764 }
5765
5766 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5767 [self resizeForKeyboardBounds:bounds duration:0];
5768 }
5769
5770 - (void) keyboardWillShow:(NSNotification *)notification {
5771 CGRect bounds;
5772 CGPoint center;
5773 NSTimeInterval duration;
5774 UIViewAnimationCurve curve;
5775 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5776 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
5777 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5778 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5779
5780 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);
5781 UIViewController *base = self;
5782 while ([base parentViewController] != nil)
5783 base = [base parentViewController];
5784 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5785 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5786
5787 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5788 }
5789
5790 - (void) keyboardWillHide:(NSNotification *)notification {
5791 NSTimeInterval duration;
5792 UIViewAnimationCurve curve;
5793 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5794 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5795
5796 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5797 }
5798
5799 - (void) viewWillAppear:(BOOL)animated {
5800 [super viewWillAppear:animated];
5801
5802 [self resizeForKeyboardBounds:CGRectZero];
5803 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5804 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5805 }
5806
5807 - (void) viewWillDisappear:(BOOL)animated {
5808 [super viewWillDisappear:animated];
5809
5810 [self resizeForKeyboardBounds:CGRectZero];
5811 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5812 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5813 }
5814
5815 - (void) viewDidAppear:(BOOL)animated {
5816 [super viewDidAppear:animated];
5817 [self deselectWithAnimation:animated];
5818 }
5819
5820 - (void) didSelectPackage:(Package *)package {
5821 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5822 [view setDelegate:delegate_];
5823 [[self navigationController] pushViewController:view animated:YES];
5824 }
5825
5826 #if TryIndexedCollation
5827 + (BOOL) hasIndexedCollation {
5828 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5829 }
5830 #endif
5831
5832 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5833 NSInteger count([sections_ count]);
5834 return count == 0 ? 1 : count;
5835 }
5836
5837 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5838 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5839 return nil;
5840 return [[sections_ objectAtIndex:section] name];
5841 }
5842
5843 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5844 if ([sections_ count] == 0)
5845 return 0;
5846 return [[sections_ objectAtIndex:section] count];
5847 }
5848
5849 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5850 @synchronized (database_) {
5851 if ([database_ era] != era_)
5852 return nil;
5853
5854 Section *section([sections_ objectAtIndex:[path section]]);
5855 NSInteger row([path row]);
5856 Package *package([packages_ objectAtIndex:([section row] + row)]);
5857 return [[package retain] autorelease];
5858 } }
5859
5860 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5861 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5862 if (cell == nil)
5863 cell = [[[PackageCell alloc] init] autorelease];
5864 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
5865 return cell;
5866 }
5867
5868 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5869 Package *package([self packageAtIndexPath:path]);
5870 package = [database_ packageWithName:[package id]];
5871 [self didSelectPackage:package];
5872 }
5873
5874 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5875 if ([self isSummarized])
5876 return nil;
5877
5878 return index_;
5879 }
5880
5881 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5882 #if TryIndexedCollation
5883 if ([[self class] hasIndexedCollation]) {
5884 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5885 }
5886 #endif
5887
5888 return index;
5889 }
5890
5891 - (void) updateHeight {
5892 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
5893 }
5894
5895 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5896 if ((self = [super init]) != nil) {
5897 database_ = database;
5898 title_ = [title copy];
5899 [[self navigationItem] setTitle:title_];
5900
5901 #if TryIndexedCollation
5902 if ([[self class] hasIndexedCollation])
5903 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
5904 else
5905 #endif
5906 index_ = [NSMutableArray arrayWithCapacity:32];
5907
5908 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5909
5910 packages_ = [NSArray array];
5911 sections_ = [NSMutableArray arrayWithCapacity:16];
5912
5913 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5914 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5915 [[self view] addSubview:list_];
5916
5917 // XXX: is 20 the most optimal number here?
5918 [list_ setSectionIndexMinimumDisplayRowCount:20];
5919
5920 [(UITableView *) list_ setDataSource:self];
5921 [list_ setDelegate:self];
5922
5923 [self updateHeight];
5924 } return self;
5925 }
5926
5927 - (void) setDelegate:(id)delegate {
5928 delegate_ = delegate;
5929 }
5930
5931 - (bool) hasPackage:(Package *)package {
5932 return true;
5933 }
5934
5935 - (bool) shouldYield {
5936 return false;
5937 }
5938
5939 - (bool) shouldBlock {
5940 return false;
5941 }
5942
5943 - (NSArray *) _reloadPackages:(NSArray *)packages {
5944 // XXX: maybe move @synchronized() to _reloadData?
5945 @synchronized (database_) {
5946 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
5947
5948 _profile(PackageTable$reloadData$Filter)
5949 for (Package *package in packages)
5950 if ([self hasPackage:package])
5951 [filtered addObject:package];
5952 _end
5953
5954 return filtered;
5955 } }
5956
5957 - (void) _reloadData {
5958 if (reloading_ != 0) {
5959 reloading_ = 2;
5960 return;
5961 }
5962
5963 era_ = [database_ era];
5964 NSArray *packages = [database_ packages];
5965
5966 if ([self shouldYield]) {
5967 UIProgressHUD *hud;
5968
5969 if (![self shouldBlock])
5970 hud = nil;
5971 else {
5972 hud = [delegate_ addProgressHUD];
5973 [hud setText:UCLocalize("LOADING")];
5974 }
5975
5976 do {
5977 reloading_ = 1;
5978 packages_ = [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
5979 } while (reloading_ == 2);
5980
5981 reloading_ = 0;
5982
5983 if (hud != nil)
5984 [delegate_ removeProgressHUD:hud];
5985 } else {
5986 packages_ = [self _reloadPackages:packages];
5987 }
5988
5989 [indices_ removeAllObjects];
5990 [sections_ removeAllObjects];
5991
5992 Section *section = nil;
5993
5994 #if TryIndexedCollation
5995 if ([[self class] hasIndexedCollation]) {
5996 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5997 NSArray *titles = [collation sectionIndexTitles];
5998 int secidx = -1;
5999
6000 _profile(PackageTable$reloadData$Section)
6001 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6002 Package *package;
6003 int index;
6004
6005 _profile(PackageTable$reloadData$Section$Package)
6006 package = [packages_ objectAtIndex:offset];
6007 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6008 _end
6009
6010 while (secidx < index) {
6011 secidx += 1;
6012
6013 _profile(PackageTable$reloadData$Section$Allocate)
6014 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6015 _end
6016
6017 _profile(PackageTable$reloadData$Section$Add)
6018 [sections_ addObject:section];
6019 _end
6020 }
6021
6022 [section addToCount];
6023 }
6024 _end
6025 } else
6026 #endif
6027 {
6028 [index_ removeAllObjects];
6029
6030 bool summary([self isSummarized]);
6031 if (summary) {
6032 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6033 [sections_ addObject:section];
6034 }
6035
6036 _profile(PackageTable$reloadData$Section)
6037 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6038 Package *package;
6039 unichar index;
6040
6041 _profile(PackageTable$reloadData$Section$Package)
6042 package = [packages_ objectAtIndex:offset];
6043 index = [package index];
6044 _end
6045
6046 if (!summary && (section == nil || [section index] != index)) {
6047 _profile(PackageTable$reloadData$Section$Allocate)
6048 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6049 _end
6050
6051 [index_ addObject:[section name]];
6052 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6053
6054 _profile(PackageTable$reloadData$Section$Add)
6055 [sections_ addObject:section];
6056 _end
6057 }
6058
6059 [section addToCount];
6060 }
6061 _end
6062 }
6063
6064 [self updateHeight];
6065
6066 _profile(PackageTable$reloadData$List)
6067 [(UITableView *) list_ setDataSource:self];
6068 [list_ reloadData];
6069 _end
6070 }
6071
6072 - (void) reloadData {
6073 [super reloadData];
6074 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6075 }
6076
6077 - (void) resetCursor {
6078 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6079 }
6080
6081 - (void) clearData {
6082 [self updateHeight];
6083
6084 [list_ setDataSource:nil];
6085 [list_ reloadData];
6086
6087 [self resetCursor];
6088 }
6089
6090 @end
6091 /* }}} */
6092 /* Filtered Package List Controller {{{ */
6093 @interface FilteredPackageListController : PackageListController {
6094 SEL filter_;
6095 IMP imp_;
6096 _H<NSObject> object_;
6097 }
6098
6099 - (void) setObject:(id)object;
6100 - (void) setObject:(id)object forFilter:(SEL)filter;
6101
6102 - (SEL) filter;
6103 - (void) setFilter:(SEL)filter;
6104
6105 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6106
6107 @end
6108
6109 @implementation FilteredPackageListController
6110
6111 - (SEL) filter {
6112 return filter_;
6113 }
6114
6115 - (void) setFilter:(SEL)filter {
6116 filter_ = filter;
6117
6118 /* XXX: this is an unsafe optimization of doomy hell */
6119 Method method(class_getInstanceMethod([Package class], filter));
6120 _assert(method != NULL);
6121 imp_ = method_getImplementation(method);
6122 _assert(imp_ != NULL);
6123 }
6124
6125 - (void) setObject:(id)object {
6126 object_ = object;
6127 }
6128
6129 - (void) setObject:(id)object forFilter:(SEL)filter {
6130 [self setFilter:filter];
6131 [self setObject:object];
6132 }
6133
6134 - (bool) hasPackage:(Package *)package {
6135 _profile(FilteredPackageTable$hasPackage)
6136 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6137 _end
6138 }
6139
6140 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6141 if ((self = [super initWithDatabase:database title:title]) != nil) {
6142 [self setFilter:filter];
6143 [self setObject:object];
6144 } return self;
6145 }
6146
6147 @end
6148 /* }}} */
6149
6150 /* Home Controller {{{ */
6151 @interface HomeController : CydiaWebViewController {
6152 }
6153
6154 @end
6155
6156 @implementation HomeController
6157
6158 - (id) init {
6159 if ((self = [super init]) != nil) {
6160 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6161 [self reloadData];
6162 } return self;
6163 }
6164
6165 - (NSURL *) navigationURL {
6166 return [NSURL URLWithString:@"cydia://home"];
6167 }
6168
6169 - (void) aboutButtonClicked {
6170 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6171
6172 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6173 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6174 [alert setCancelButtonIndex:0];
6175
6176 [alert setMessage:
6177 @"Copyright \u00a9 2008-2011\n"
6178 "SaurikIT, LLC\n"
6179 "\n"
6180 "Jay Freeman (saurik)\n"
6181 "saurik@saurik.com\n"
6182 "http://www.saurik.com/"
6183 ];
6184
6185 [alert show];
6186 }
6187
6188 - (UIBarButtonItem *) leftButton {
6189 return [[[UIBarButtonItem alloc]
6190 initWithTitle:UCLocalize("ABOUT")
6191 style:UIBarButtonItemStylePlain
6192 target:self
6193 action:@selector(aboutButtonClicked)
6194 ] autorelease];
6195 }
6196
6197 - (void) unloadData {
6198 [super unloadData];
6199 [self reloadData];
6200 }
6201
6202 @end
6203 /* }}} */
6204 /* Manage Controller {{{ */
6205 @interface ManageController : CydiaWebViewController {
6206 }
6207
6208 - (void) queueStatusDidChange;
6209
6210 @end
6211
6212 @implementation ManageController
6213
6214 - (id) init {
6215 if ((self = [super init]) != nil) {
6216 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6217 } return self;
6218 }
6219
6220 - (NSURL *) navigationURL {
6221 return [NSURL URLWithString:@"cydia://manage"];
6222 }
6223
6224 - (UIBarButtonItem *) leftButton {
6225 return [[[UIBarButtonItem alloc]
6226 initWithTitle:UCLocalize("SETTINGS")
6227 style:UIBarButtonItemStylePlain
6228 target:self
6229 action:@selector(settingsButtonClicked)
6230 ] autorelease];
6231 }
6232
6233 - (void) settingsButtonClicked {
6234 [delegate_ showSettings];
6235 }
6236
6237 - (void) queueButtonClicked {
6238 [delegate_ queue];
6239 }
6240
6241 - (UIBarButtonItem *) customButton {
6242 return Queuing_ ? [[[UIBarButtonItem alloc]
6243 initWithTitle:UCLocalize("QUEUE")
6244 style:UIBarButtonItemStyleDone
6245 target:self
6246 action:@selector(queueButtonClicked)
6247 ] autorelease] : [super customButton];
6248 }
6249
6250 - (void) queueStatusDidChange {
6251 [self applyRightButton];
6252 }
6253
6254 - (bool) isLoading {
6255 return !Queuing_ && [super isLoading];
6256 }
6257
6258 @end
6259 /* }}} */
6260
6261 /* Refresh Bar {{{ */
6262 @interface RefreshBar : UINavigationBar {
6263 _H<UIProgressIndicator> indicator_;
6264 _H<UITextLabel> prompt_;
6265 _H<UIProgressBar> progress_;
6266 _H<UINavigationButton> cancel_;
6267 }
6268
6269 @end
6270
6271 @implementation RefreshBar
6272
6273 - (void) positionViews {
6274 CGRect frame = [cancel_ frame];
6275 frame.size = [cancel_ sizeThatFits:frame.size];
6276 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6277 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6278 [cancel_ setFrame:frame];
6279
6280 CGSize prgsize = {75, 100};
6281 CGRect prgrect = {{
6282 [self frame].size.width - prgsize.width - 10,
6283 ([self frame].size.height - prgsize.height) / 2
6284 } , prgsize};
6285 [progress_ setFrame:prgrect];
6286
6287 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6288 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6289 CGRect indrect = {{indoffset, indoffset}, indsize};
6290 [indicator_ setFrame:indrect];
6291
6292 CGSize prmsize = {215, indsize.height + 4};
6293 CGRect prmrect = {{
6294 indoffset * 2 + indsize.width,
6295 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6296 }, prmsize};
6297 [prompt_ setFrame:prmrect];
6298 }
6299
6300 - (void) setFrame:(CGRect)frame {
6301 [super setFrame:frame];
6302 [self positionViews];
6303 }
6304
6305 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6306 if ((self = [super initWithFrame:frame]) != nil) {
6307 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6308
6309 [self setBarStyle:UIBarStyleBlack];
6310
6311 UIBarStyle barstyle([self _barStyle:NO]);
6312 bool ugly(barstyle == UIBarStyleDefault);
6313
6314 UIProgressIndicatorStyle style = ugly ?
6315 UIProgressIndicatorStyleMediumBrown :
6316 UIProgressIndicatorStyleMediumWhite;
6317
6318 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6319 [(UIProgressIndicator *) indicator_ setStyle:style];
6320 [indicator_ startAnimation];
6321 [self addSubview:indicator_];
6322
6323 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6324 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6325 [prompt_ setBackgroundColor:[UIColor clearColor]];
6326 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6327 [self addSubview:prompt_];
6328
6329 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6330 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6331 [(UIProgressBar *) progress_ setStyle:0];
6332 [self addSubview:progress_];
6333
6334 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6335 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6336 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6337 [cancel_ setBarStyle:barstyle];
6338
6339 [self positionViews];
6340 } return self;
6341 }
6342
6343 - (void) setCancellable:(bool)cancellable {
6344 if (cancellable)
6345 [self addSubview:cancel_];
6346 else
6347 [cancel_ removeFromSuperview];
6348 }
6349
6350 - (void) start {
6351 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6352 [progress_ setProgress:0];
6353 }
6354
6355 - (void) stop {
6356 [self setCancellable:NO];
6357 }
6358
6359 - (void) setPrompt:(NSString *)prompt {
6360 [prompt_ setText:prompt];
6361 }
6362
6363 - (void) setProgress:(float)progress {
6364 [progress_ setProgress:progress];
6365 }
6366
6367 @end
6368 /* }}} */
6369
6370 /* Cydia Navigation Controller Interface {{{ */
6371 @interface UINavigationController (Cydia)
6372
6373 - (NSArray *) navigationURLCollection;
6374 - (void) unloadData;
6375
6376 @end
6377 /* }}} */
6378
6379 /* Cydia Tab Bar Controller {{{ */
6380 @interface CYTabBarController : UITabBarController <
6381 UITabBarControllerDelegate,
6382 ProgressDelegate
6383 > {
6384 _transient Database *database_;
6385 _H<RefreshBar, 1> refreshbar_;
6386
6387 bool dropped_;
6388 bool updating_;
6389 // XXX: ok, "updatedelegate_"?...
6390 _transient NSObject<CydiaDelegate> *updatedelegate_;
6391
6392 _H<UIViewController> remembered_;
6393 _transient UIViewController *transient_;
6394 }
6395
6396 - (NSArray *) navigationURLCollection;
6397 - (void) dropBar:(BOOL)animated;
6398 - (void) beginUpdate;
6399 - (void) raiseBar:(BOOL)animated;
6400 - (BOOL) updating;
6401 - (void) unloadData;
6402
6403 @end
6404
6405 @implementation CYTabBarController
6406
6407 - (void) setUnselectedViewController:(UIViewController *)transient {
6408 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6409 if (transient != nil) {
6410 if (transient_ == nil)
6411 remembered_ = [controllers objectAtIndex:0];
6412 transient_ = transient;
6413 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6414 [controllers replaceObjectAtIndex:0 withObject:transient_];
6415 [self setSelectedIndex:0];
6416 [self setViewControllers:controllers];
6417 [self concealTabBarSelection];
6418 } else if (remembered_ != nil) {
6419 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6420 transient_ = transient;
6421 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6422 remembered_ = nil;
6423 [self setViewControllers:controllers];
6424 [self revealTabBarSelection];
6425 }
6426 }
6427
6428 - (UIViewController *) unselectedViewController {
6429 return transient_;
6430 }
6431
6432 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6433 if ([self unselectedViewController])
6434 [self setUnselectedViewController:nil];
6435 }
6436
6437 - (NSArray *) navigationURLCollection {
6438 NSMutableArray *items([NSMutableArray array]);
6439
6440 // XXX: Should this deal with transient view controllers?
6441 for (id navigation in [self viewControllers]) {
6442 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6443 if (stack != nil)
6444 [items addObject:stack];
6445 }
6446
6447 return items;
6448 }
6449
6450 - (void) unloadData {
6451 UIViewController *selected([self selectedViewController]);
6452 for (UINavigationController *controller in [self viewControllers])
6453 [controller unloadData];
6454
6455 [selected reloadData];
6456
6457 if (UIViewController *unselected = [self unselectedViewController])
6458 [unselected reloadData];
6459
6460 [super unloadData];
6461 }
6462
6463 - (void) dealloc {
6464 [[NSNotificationCenter defaultCenter] removeObserver:self];
6465
6466 [super dealloc];
6467 }
6468
6469 - (id) initWithDatabase:(Database *)database {
6470 if ((self = [super init]) != nil) {
6471 database_ = database;
6472 [self setDelegate:self];
6473
6474 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6475 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6476
6477 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6478 } return self;
6479 }
6480
6481 - (void) setUpdate:(NSDate *)date {
6482 [self beginUpdate];
6483 }
6484
6485 - (void) beginUpdate {
6486 [(RefreshBar *) refreshbar_ start];
6487 [self dropBar:YES];
6488
6489 [updatedelegate_ retainNetworkActivityIndicator];
6490 updating_ = true;
6491
6492 [NSThread
6493 detachNewThreadSelector:@selector(performUpdate)
6494 toTarget:self
6495 withObject:nil
6496 ];
6497 }
6498
6499 - (void) performUpdate {
6500 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6501
6502 Status status;
6503 status.setDelegate(self);
6504 [database_ updateWithStatus:status];
6505
6506 [self
6507 performSelectorOnMainThread:@selector(completeUpdate)
6508 withObject:nil
6509 waitUntilDone:NO
6510 ];
6511
6512 [pool release];
6513 }
6514
6515 - (void) stopUpdateWithSelector:(SEL)selector {
6516 updating_ = false;
6517 [updatedelegate_ releaseNetworkActivityIndicator];
6518
6519 [self raiseBar:YES];
6520 [refreshbar_ stop];
6521
6522 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6523 }
6524
6525 - (void) completeUpdate {
6526 if (!updating_)
6527 return;
6528 [self stopUpdateWithSelector:@selector(reloadData)];
6529 }
6530
6531 - (void) cancelUpdate {
6532 [self stopUpdateWithSelector:@selector(updateData)];
6533 }
6534
6535 - (void) cancelPressed {
6536 [self cancelUpdate];
6537 }
6538
6539 - (BOOL) updating {
6540 return updating_;
6541 }
6542
6543 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6544 [refreshbar_ setPrompt:[event compoundMessage]];
6545 }
6546
6547 - (bool) isProgressCancelled {
6548 return !updating_;
6549 }
6550
6551 - (void) setProgressCancellable:(NSNumber *)cancellable {
6552 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6553 }
6554
6555 - (void) setProgressPercent:(NSNumber *)percent {
6556 [refreshbar_ setProgress:[percent floatValue]];
6557 }
6558
6559 - (void) setProgressStatus:(NSDictionary *)status {
6560 if (status != nil)
6561 [self setProgressPercent:[status objectForKey:@"Percent"]];
6562 }
6563
6564 - (void) setUpdateDelegate:(id)delegate {
6565 updatedelegate_ = delegate;
6566 }
6567
6568 - (CGFloat) statusBarHeight {
6569 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6570 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6571 } else {
6572 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6573 }
6574 }
6575
6576 - (UIView *) transitionView {
6577 if ([self respondsToSelector:@selector(_transitionView)])
6578 return [self _transitionView];
6579 else
6580 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6581 }
6582
6583 - (void) dropBar:(BOOL)animated {
6584 if (dropped_)
6585 return;
6586 dropped_ = true;
6587
6588 UIView *transition([self transitionView]);
6589 [[self view] addSubview:refreshbar_];
6590
6591 CGRect barframe([refreshbar_ frame]);
6592
6593 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6594 barframe.origin.y = [self statusBarHeight];
6595 else
6596 barframe.origin.y = 0;
6597
6598 [refreshbar_ setFrame:barframe];
6599
6600 if (animated)
6601 [UIView beginAnimations:nil context:NULL];
6602
6603 CGRect viewframe = [transition frame];
6604 viewframe.origin.y += barframe.size.height;
6605 viewframe.size.height -= barframe.size.height;
6606 [transition setFrame:viewframe];
6607
6608 if (animated)
6609 [UIView commitAnimations];
6610
6611 // Ensure bar has the proper width for our view, it might have changed
6612 barframe.size.width = viewframe.size.width;
6613 [refreshbar_ setFrame:barframe];
6614 }
6615
6616 - (void) raiseBar:(BOOL)animated {
6617 if (!dropped_)
6618 return;
6619 dropped_ = false;
6620
6621 UIView *transition([self transitionView]);
6622 [refreshbar_ removeFromSuperview];
6623
6624 CGRect barframe([refreshbar_ frame]);
6625
6626 if (animated)
6627 [UIView beginAnimations:nil context:NULL];
6628
6629 CGRect viewframe = [transition frame];
6630 viewframe.origin.y -= barframe.size.height;
6631 viewframe.size.height += barframe.size.height;
6632 [transition setFrame:viewframe];
6633
6634 if (animated)
6635 [UIView commitAnimations];
6636 }
6637
6638 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6639 bool dropped(dropped_);
6640
6641 if (dropped)
6642 [self raiseBar:NO];
6643
6644 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6645
6646 if (dropped)
6647 [self dropBar:NO];
6648 }
6649
6650 - (void) statusBarFrameChanged:(NSNotification *)notification {
6651 if (dropped_) {
6652 [self raiseBar:NO];
6653 [self dropBar:NO];
6654 }
6655 }
6656
6657 @end
6658 /* }}} */
6659
6660 /* Cydia Navigation Controller Implementation {{{ */
6661 @implementation UINavigationController (Cydia)
6662
6663 - (NSArray *) navigationURLCollection {
6664 NSMutableArray *stack([NSMutableArray array]);
6665
6666 for (CyteViewController *controller in [self viewControllers]) {
6667 NSString *url = [[controller navigationURL] absoluteString];
6668 if (url != nil)
6669 [stack addObject:url];
6670 }
6671
6672 return stack;
6673 }
6674
6675 - (void) reloadData {
6676 [super reloadData];
6677
6678 if (UIViewController *visible = [self visibleViewController])
6679 [visible reloadData];
6680 }
6681
6682 - (void) unloadData {
6683 for (CyteViewController *page in [self viewControllers])
6684 [page unloadData];
6685
6686 [super unloadData];
6687 }
6688
6689 @end
6690 /* }}} */
6691
6692 /* Cydia:// Protocol {{{ */
6693 @interface CydiaURLProtocol : NSURLProtocol {
6694 }
6695
6696 @end
6697
6698 @implementation CydiaURLProtocol
6699
6700 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6701 NSURL *url([request URL]);
6702 if (url == nil)
6703 return NO;
6704
6705 NSString *scheme([[url scheme] lowercaseString]);
6706 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6707 return YES;
6708 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6709 return YES;
6710
6711 return NO;
6712 }
6713
6714 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6715 return request;
6716 }
6717
6718 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6719 id<NSURLProtocolClient> client([self client]);
6720 if (icon == nil)
6721 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6722 else {
6723 NSData *data(UIImagePNGRepresentation(icon));
6724
6725 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6726 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6727 [client URLProtocol:self didLoadData:data];
6728 [client URLProtocolDidFinishLoading:self];
6729 }
6730 }
6731
6732 - (void) startLoading {
6733 id<NSURLProtocolClient> client([self client]);
6734 NSURLRequest *request([self request]);
6735
6736 NSURL *url([request URL]);
6737 NSString *href([url absoluteString]);
6738 NSString *scheme([[url scheme] lowercaseString]);
6739
6740 NSString *path;
6741
6742 if ([scheme isEqualToString:@"cydia"])
6743 path = [href substringFromIndex:8];
6744 else if ([scheme isEqualToString:@"about"])
6745 path = [href substringFromIndex:12];
6746 else _assert(false);
6747
6748 NSRange slash([path rangeOfString:@"/"]);
6749
6750 NSString *command;
6751 if (slash.location == NSNotFound) {
6752 command = path;
6753 path = nil;
6754 } else {
6755 command = [path substringToIndex:slash.location];
6756 path = [path substringFromIndex:(slash.location + 1)];
6757 }
6758
6759 Database *database([Database sharedInstance]);
6760
6761 if ([command isEqualToString:@"package-icon"]) {
6762 if (path == nil)
6763 goto fail;
6764 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6765 Package *package([database packageWithName:path]);
6766 if (package == nil)
6767 goto fail;
6768 [package parse];
6769 UIImage *icon([package icon]);
6770 [self _returnPNGWithImage:icon forRequest:request];
6771 } else if ([command isEqualToString:@"source-icon"]) {
6772 if (path == nil)
6773 goto fail;
6774 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6775 NSString *source(Simplify(path));
6776 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6777 if (icon == nil)
6778 icon = [UIImage applicationImageNamed:@"unknown.png"];
6779 [self _returnPNGWithImage:icon forRequest:request];
6780 } else if ([command isEqualToString:@"uikit-image"]) {
6781 if (path == nil)
6782 goto fail;
6783 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6784 UIImage *icon(_UIImageWithName(path));
6785 [self _returnPNGWithImage:icon forRequest:request];
6786 } else if ([command isEqualToString:@"section-icon"]) {
6787 if (path == nil)
6788 goto fail;
6789 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6790 NSString *section(Simplify(path));
6791 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6792 if (icon == nil)
6793 icon = [UIImage applicationImageNamed:@"unknown.png"];
6794 [self _returnPNGWithImage:icon forRequest:request];
6795 } else fail: {
6796 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6797 }
6798 }
6799
6800 - (void) stopLoading {
6801 }
6802
6803 @end
6804 /* }}} */
6805
6806 /* Section Controller {{{ */
6807 @interface SectionController : FilteredPackageListController {
6808 _H<NSString> section_;
6809 }
6810
6811 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6812
6813 @end
6814
6815 @implementation SectionController
6816
6817 - (NSURL *) navigationURL {
6818 NSString *name = section_;
6819 if (name == nil)
6820 name = @"all";
6821
6822 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6823 }
6824
6825 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6826 NSString *title;
6827 if (name == nil)
6828 title = UCLocalize("ALL_PACKAGES");
6829 else if (![name isEqual:@""])
6830 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6831 else
6832 title = UCLocalize("NO_SECTION");
6833
6834 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6835 section_ = name;
6836 } return self;
6837 }
6838
6839 @end
6840 /* }}} */
6841 /* Sections Controller {{{ */
6842 @interface SectionsController : CyteViewController <
6843 UITableViewDataSource,
6844 UITableViewDelegate
6845 > {
6846 _transient Database *database_;
6847 _H<NSMutableArray> sections_;
6848 _H<NSMutableArray> filtered_;
6849 _H<UITableView, 2> list_;
6850 }
6851
6852 - (id) initWithDatabase:(Database *)database;
6853 - (void) editButtonClicked;
6854
6855 @end
6856
6857 @implementation SectionsController
6858
6859 - (NSURL *) navigationURL {
6860 return [NSURL URLWithString:@"cydia://sections"];
6861 }
6862
6863 - (void) updateNavigationItem {
6864 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6865 if ([sections_ count] == 0) {
6866 [[self navigationItem] setRightBarButtonItem:nil];
6867 } else {
6868 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6869 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6870 target:self
6871 action:@selector(editButtonClicked)
6872 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6873 }
6874 }
6875
6876 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6877 [super setEditing:editing animated:animated];
6878
6879 if (editing)
6880 [list_ reloadData];
6881 else
6882 [delegate_ updateData];
6883
6884 [self updateNavigationItem];
6885 }
6886
6887 - (void) viewDidAppear:(BOOL)animated {
6888 [super viewDidAppear:animated];
6889 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6890 }
6891
6892 - (void) viewWillDisappear:(BOOL)animated {
6893 [super viewWillDisappear:animated];
6894 if ([self isEditing]) [self setEditing:NO];
6895 }
6896
6897 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6898 Section *section = nil;
6899 int index = [indexPath row];
6900 if (![self isEditing]) {
6901 index -= 1;
6902 if (index >= 0)
6903 section = [filtered_ objectAtIndex:index];
6904 } else {
6905 section = [sections_ objectAtIndex:index];
6906 }
6907 return section;
6908 }
6909
6910 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6911 if ([self isEditing])
6912 return [sections_ count];
6913 else
6914 return [filtered_ count] + 1;
6915 }
6916
6917 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6918 return 45.0f;
6919 }*/
6920
6921 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6922 static NSString *reuseIdentifier = @"SectionCell";
6923
6924 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6925 if (cell == nil)
6926 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6927
6928 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6929
6930 return cell;
6931 }
6932
6933 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6934 if ([self isEditing])
6935 return;
6936
6937 Section *section = [self sectionAtIndexPath:indexPath];
6938
6939 SectionController *controller = [[[SectionController alloc]
6940 initWithDatabase:database_
6941 section:[section name]
6942 ] autorelease];
6943 [controller setDelegate:delegate_];
6944
6945 [[self navigationController] pushViewController:controller animated:YES];
6946 }
6947
6948 - (void) loadView {
6949 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6950
6951 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
6952 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6953 [list_ setRowHeight:45.0f];
6954 [(UITableView *) list_ setDataSource:self];
6955 [list_ setDelegate:self];
6956 [[self view] addSubview:list_];
6957 }
6958
6959 - (void) viewDidLoad {
6960 [super viewDidLoad];
6961
6962 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6963 }
6964
6965 - (void) releaseSubviews {
6966 list_ = nil;
6967 }
6968
6969 - (id) initWithDatabase:(Database *)database {
6970 if ((self = [super init]) != nil) {
6971 database_ = database;
6972
6973 sections_ = [NSMutableArray arrayWithCapacity:16];
6974 filtered_ = [NSMutableArray arrayWithCapacity:16];
6975 } return self;
6976 }
6977
6978 - (void) reloadData {
6979 [super reloadData];
6980
6981 NSArray *packages = [database_ packages];
6982
6983 [sections_ removeAllObjects];
6984 [filtered_ removeAllObjects];
6985
6986 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6987
6988 _trace();
6989 for (Package *package in packages) {
6990 NSString *name([package section]);
6991 NSString *key(name == nil ? @"" : name);
6992
6993 Section *section;
6994
6995 _profile(SectionsView$reloadData$Section)
6996 section = [sections objectForKey:key];
6997 if (section == nil) {
6998 _profile(SectionsView$reloadData$Section$Allocate)
6999 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7000 [sections setObject:section forKey:key];
7001 _end
7002 }
7003 _end
7004
7005 [section addToCount];
7006
7007 _profile(SectionsView$reloadData$Filter)
7008 if (![package valid] || ![package visible])
7009 continue;
7010 _end
7011
7012 [section addToRow];
7013 }
7014 _trace();
7015
7016 [sections_ addObjectsFromArray:[sections allValues]];
7017
7018 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7019
7020 for (Section *section in (id) sections_) {
7021 size_t count([section row]);
7022 if (count == 0)
7023 continue;
7024
7025 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7026 [section setCount:count];
7027 [filtered_ addObject:section];
7028 }
7029
7030 [self updateNavigationItem];
7031 [list_ reloadData];
7032 _trace();
7033 }
7034
7035 - (void) editButtonClicked {
7036 [self setEditing:![self isEditing] animated:YES];
7037 }
7038
7039 @end
7040 /* }}} */
7041
7042 /* Changes Controller {{{ */
7043 @interface ChangesController : CyteViewController <
7044 UITableViewDataSource,
7045 UITableViewDelegate
7046 > {
7047 _transient Database *database_;
7048 unsigned era_;
7049 _H<NSArray> packages_;
7050 _H<NSMutableArray> sections_;
7051 _H<UITableView, 2> list_;
7052 unsigned upgrades_;
7053 }
7054
7055 - (id) initWithDatabase:(Database *)database;
7056
7057 @end
7058
7059 @implementation ChangesController
7060
7061 - (NSURL *) navigationURL {
7062 return [NSURL URLWithString:@"cydia://changes"];
7063 }
7064
7065 - (void) viewDidAppear:(BOOL)animated {
7066 [super viewDidAppear:animated];
7067 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7068 }
7069
7070 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7071 NSInteger count([sections_ count]);
7072 return count == 0 ? 1 : count;
7073 }
7074
7075 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7076 if ([sections_ count] == 0)
7077 return nil;
7078 return [[sections_ objectAtIndex:section] name];
7079 }
7080
7081 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7082 if ([sections_ count] == 0)
7083 return 0;
7084 return [[sections_ objectAtIndex:section] count];
7085 }
7086
7087 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7088 @synchronized (database_) {
7089 if ([database_ era] != era_)
7090 return nil;
7091
7092 NSUInteger sectionIndex([path section]);
7093 if (sectionIndex >= [sections_ count])
7094 return nil;
7095 Section *section([sections_ objectAtIndex:sectionIndex]);
7096 NSInteger row([path row]);
7097 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7098 } }
7099
7100 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7101 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7102 if (cell == nil)
7103 cell = [[[PackageCell alloc] init] autorelease];
7104 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7105 return cell;
7106 }
7107
7108 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7109 Package *package([self packageAtIndexPath:path]);
7110 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7111 [view setDelegate:delegate_];
7112 [[self navigationController] pushViewController:view animated:YES];
7113 return path;
7114 }
7115
7116 - (void) refreshButtonClicked {
7117 [delegate_ beginUpdate];
7118 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7119 }
7120
7121 - (void) upgradeButtonClicked {
7122 [delegate_ distUpgrade];
7123 }
7124
7125 - (void) loadView {
7126 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7127
7128 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7129 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7130 [list_ setRowHeight:73];
7131 [(UITableView *) list_ setDataSource:self];
7132 [list_ setDelegate:self];
7133 [[self view] addSubview:list_];
7134 }
7135
7136 - (void) viewDidLoad {
7137 [super viewDidLoad];
7138
7139 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7140 }
7141
7142 - (void) releaseSubviews {
7143 list_ = nil;
7144 }
7145
7146 - (id) initWithDatabase:(Database *)database {
7147 if ((self = [super init]) != nil) {
7148 database_ = database;
7149
7150 packages_ = [NSArray array];
7151 sections_ = [NSMutableArray arrayWithCapacity:16];
7152 } return self;
7153 }
7154
7155 - (NSArray *) _reloadPackages:(NSArray *)packages {
7156 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7157
7158 _trace();
7159 _profile(ChangesController$_reloadPackages$Filter)
7160 for (Package *package in packages)
7161 if ([package upgradableAndEssential:YES] || [package visible])
7162 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7163 _end
7164 _trace();
7165 _profile(ChangesController$_reloadPackages$radixSort)
7166 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7167 _end
7168 _trace();
7169
7170 return filtered;
7171 }
7172
7173 - (void) _reloadData {
7174 @synchronized (database_) {
7175 era_ = [database_ era];
7176 NSArray *packages = [database_ packages];
7177
7178 #if 1
7179 UIProgressHUD *hud([delegate_ addProgressHUD]);
7180 [hud setText:UCLocalize("LOADING")];
7181 //NSLog(@"HUD:%@::%@", delegate_, hud);
7182 packages_ = [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7183 [delegate_ removeProgressHUD:hud];
7184 #else
7185 packages_ = [self _reloadPackages:packages];
7186 #endif
7187
7188 [sections_ removeAllObjects];
7189
7190 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7191 Section *ignored = nil;
7192 Section *section = nil;
7193 time_t last = 0;
7194
7195 upgrades_ = 0;
7196 bool unseens = false;
7197
7198 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7199
7200 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7201 Package *package = [packages_ objectAtIndex:offset];
7202
7203 BOOL uae = [package upgradableAndEssential:YES];
7204
7205 if (!uae) {
7206 unseens = true;
7207 time_t seen([package seen]);
7208
7209 if (section == nil || last != seen) {
7210 last = seen;
7211
7212 NSString *name;
7213 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7214 [name autorelease];
7215
7216 _profile(ChangesController$reloadData$Allocate)
7217 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7218 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7219 [sections_ addObject:section];
7220 _end
7221 }
7222
7223 [section addToCount];
7224 } else if ([package ignored]) {
7225 if (ignored == nil) {
7226 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7227 }
7228 [ignored addToCount];
7229 } else {
7230 ++upgrades_;
7231 [upgradable addToCount];
7232 }
7233 }
7234 _trace();
7235
7236 CFRelease(formatter);
7237
7238 if (unseens) {
7239 Section *last = [sections_ lastObject];
7240 size_t count = [last count];
7241 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7242 [sections_ removeLastObject];
7243 }
7244
7245 if ([ignored count] != 0)
7246 [sections_ insertObject:ignored atIndex:0];
7247 if (upgrades_ != 0)
7248 [sections_ insertObject:upgradable atIndex:0];
7249
7250 [list_ reloadData];
7251
7252 if (upgrades_ > 0)
7253 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7254 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7255 style:UIBarButtonItemStylePlain
7256 target:self
7257 action:@selector(upgradeButtonClicked)
7258 ] autorelease]];
7259
7260 if (![delegate_ updating])
7261 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7262 initWithTitle:UCLocalize("REFRESH")
7263 style:UIBarButtonItemStylePlain
7264 target:self
7265 action:@selector(refreshButtonClicked)
7266 ] autorelease]];
7267
7268 PrintTimes();
7269 } }
7270
7271 - (void) reloadData {
7272 [super reloadData];
7273 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7274 }
7275
7276 @end
7277 /* }}} */
7278 /* Search Controller {{{ */
7279 @interface SearchController : FilteredPackageListController <
7280 UISearchBarDelegate
7281 > {
7282 _H<UISearchBar, 1> search_;
7283 BOOL searchloaded_;
7284 }
7285
7286 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7287 - (void) reloadData;
7288
7289 @end
7290
7291 @implementation SearchController
7292
7293 - (NSURL *) navigationURL {
7294 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7295 return [NSURL URLWithString:@"cydia://search"];
7296 else
7297 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7298 }
7299
7300 - (void) useSearch {
7301 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7302 [self clearData];
7303 [self reloadData];
7304 }
7305
7306 - (void) viewWillAppear:(BOOL)animated {
7307 [super viewWillAppear:animated];
7308
7309 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7310 [self useSearch];
7311 }
7312
7313 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7314 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7315 [self clearData];
7316 [self reloadData];
7317 }
7318
7319 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7320 [search_ resignFirstResponder];
7321 [self useSearch];
7322 }
7323
7324 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7325 [search_ setText:@""];
7326 [self searchBarButtonClicked:searchBar];
7327 }
7328
7329 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7330 [self searchBarButtonClicked:searchBar];
7331 }
7332
7333 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7334 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7335 [self reloadData];
7336 }
7337
7338 - (bool) shouldYield {
7339 return YES;
7340 }
7341
7342 - (bool) shouldBlock {
7343 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7344 }
7345
7346 - (bool) isSummarized {
7347 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7348 }
7349
7350 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7351 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
7352 search_ = [[[UISearchBar alloc] init] autorelease];
7353 [search_ setDelegate:self];
7354
7355 if (query != nil)
7356 [search_ setText:query];
7357 } return self;
7358 }
7359
7360 - (void) viewDidAppear:(BOOL)animated {
7361 [super viewDidAppear:animated];
7362
7363 if (!searchloaded_) {
7364 searchloaded_ = YES;
7365 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7366 [search_ layoutSubviews];
7367 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7368
7369 UITextField *textField;
7370 if ([search_ respondsToSelector:@selector(searchField)])
7371 textField = [search_ searchField];
7372 else
7373 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7374
7375 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7376 [textField setEnablesReturnKeyAutomatically:NO];
7377 [[self navigationItem] setTitleView:textField];
7378 }
7379 }
7380
7381 - (void) reloadData {
7382 [self setObject:[search_ text]];
7383 [self resetCursor];
7384
7385 [super reloadData];
7386 }
7387
7388 - (void) didSelectPackage:(Package *)package {
7389 [search_ resignFirstResponder];
7390 [super didSelectPackage:package];
7391 }
7392
7393 @end
7394 /* }}} */
7395 /* Package Settings Controller {{{ */
7396 @interface PackageSettingsController : CyteViewController <
7397 UITableViewDataSource,
7398 UITableViewDelegate
7399 > {
7400 _transient Database *database_;
7401 _H<NSString> name_;
7402 _H<Package> package_;
7403 _H<UITableView, 2> table_;
7404 _H<UISwitch> subscribedSwitch_;
7405 _H<UISwitch> ignoredSwitch_;
7406 _H<UITableViewCell> subscribedCell_;
7407 _H<UITableViewCell> ignoredCell_;
7408 }
7409
7410 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7411
7412 @end
7413
7414 @implementation PackageSettingsController
7415
7416 - (NSURL *) navigationURL {
7417 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7418 }
7419
7420 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7421 if (package_ == nil)
7422 return 0;
7423
7424 if ([package_ installed] == nil)
7425 return 1;
7426 else
7427 return 2;
7428 }
7429
7430 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7431 if (package_ == nil)
7432 return 0;
7433
7434 // both sections contain just one item right now.
7435 return 1;
7436 }
7437
7438 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7439 return nil;
7440 }
7441
7442 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7443 if (section == 0)
7444 return UCLocalize("SHOW_ALL_CHANGES_EX");
7445 else
7446 return UCLocalize("IGNORE_UPGRADES_EX");
7447 }
7448
7449 - (void) onSubscribed:(id)control {
7450 bool value([control isOn]);
7451 if (package_ == nil)
7452 return;
7453 if ([package_ setSubscribed:value])
7454 [delegate_ updateData];
7455 }
7456
7457 - (void) _updateIgnored {
7458 const char *package([name_ UTF8String]);
7459 bool on([ignoredSwitch_ isOn]);
7460
7461 pid_t pid(ExecFork());
7462 if (pid == 0) {
7463 FILE *dpkg(popen("dpkg --set-selections", "w"));
7464 fwrite(package, strlen(package), 1, dpkg);
7465
7466 if (on)
7467 fwrite(" hold\n", 6, 1, dpkg);
7468 else
7469 fwrite(" install\n", 9, 1, dpkg);
7470
7471 pclose(dpkg);
7472
7473 exit(0);
7474 _assert(false);
7475 }
7476
7477 _forever {
7478 int status;
7479 int result(waitpid(pid, &status, 0));
7480
7481 if (result != -1) {
7482 _assert(result == pid);
7483 break;
7484 }
7485 }
7486 }
7487
7488 - (void) onIgnored:(id)control {
7489 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7490 [invocation setTarget:self];
7491 [invocation setSelector:@selector(_updateIgnored)];
7492
7493 [delegate_ reloadDataWithInvocation:invocation];
7494 }
7495
7496 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7497 if (package_ == nil)
7498 return nil;
7499
7500 switch ([indexPath section]) {
7501 case 0: return subscribedCell_;
7502 case 1: return ignoredCell_;
7503
7504 _nodefault
7505 }
7506
7507 return nil;
7508 }
7509
7510 - (void) loadView {
7511 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7512
7513 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7514 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7515 [(UITableView *) table_ setDataSource:self];
7516 [table_ setDelegate:self];
7517 [[self view] addSubview:table_];
7518
7519 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7520 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7521 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7522
7523 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7524 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7525 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7526
7527 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7528 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7529 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7530 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7531
7532 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7533 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7534 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7535 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7536 }
7537
7538 - (void) viewDidLoad {
7539 [super viewDidLoad];
7540
7541 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7542 }
7543
7544 - (void) releaseSubviews {
7545 ignoredCell_ = nil;
7546 subscribedCell_ = nil;
7547 table_ = nil;
7548 ignoredSwitch_ = nil;
7549 subscribedSwitch_ = nil;
7550 }
7551
7552 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7553 if ((self = [super init]) != nil) {
7554 database_ = database;
7555 name_ = package;
7556 } return self;
7557 }
7558
7559 - (void) reloadData {
7560 [super reloadData];
7561
7562 package_ = [database_ packageWithName:name_];
7563
7564 if (package_ != nil) {
7565 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7566 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7567 } // XXX: what now, G?
7568
7569 [table_ reloadData];
7570 }
7571
7572 @end
7573 /* }}} */
7574
7575 /* Installed Controller {{{ */
7576 @interface InstalledController : FilteredPackageListController {
7577 BOOL expert_;
7578 }
7579
7580 - (id) initWithDatabase:(Database *)database;
7581
7582 - (void) updateRoleButton;
7583 - (void) queueStatusDidChange;
7584
7585 @end
7586
7587 @implementation InstalledController
7588
7589 - (NSURL *) navigationURL {
7590 return [NSURL URLWithString:@"cydia://installed"];
7591 }
7592
7593 - (id) initWithDatabase:(Database *)database {
7594 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7595 [self updateRoleButton];
7596 [self queueStatusDidChange];
7597 } return self;
7598 }
7599
7600 #if !AlwaysReload
7601 - (void) queueButtonClicked {
7602 [delegate_ queue];
7603 }
7604 #endif
7605
7606 - (void) queueStatusDidChange {
7607 #if !AlwaysReload
7608 if (IsWildcat_) {
7609 if (Queuing_) {
7610 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7611 initWithTitle:UCLocalize("QUEUE")
7612 style:UIBarButtonItemStyleDone
7613 target:self
7614 action:@selector(queueButtonClicked)
7615 ] autorelease]];
7616 } else {
7617 [[self navigationItem] setLeftBarButtonItem:nil];
7618 }
7619 }
7620 #endif
7621 }
7622
7623 - (void) updateRoleButton {
7624 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7625 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7626 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7627 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7628 target:self
7629 action:@selector(roleButtonClicked)
7630 ] autorelease]];
7631 }
7632
7633 - (void) roleButtonClicked {
7634 [self setObject:[NSNumber numberWithBool:expert_]];
7635 [self reloadData];
7636 expert_ = !expert_;
7637
7638 [self updateRoleButton];
7639 }
7640
7641 @end
7642 /* }}} */
7643
7644 /* Source Cell {{{ */
7645 @interface SourceCell : CyteTableViewCell <
7646 CyteTableViewCellDelegate
7647 > {
7648 _H<UIImage> icon_;
7649 _H<NSString> origin_;
7650 _H<NSString> label_;
7651 }
7652
7653 - (void) setSource:(Source *)source;
7654
7655 @end
7656
7657 @implementation SourceCell
7658
7659 - (void) setSource:(Source *)source {
7660 icon_ = nil;
7661 if (icon_ == nil)
7662 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7663 if (icon_ == nil)
7664 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7665
7666 origin_ = [source name];
7667 label_ = [source uri];
7668
7669 [content_ setNeedsDisplay];
7670 }
7671
7672 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7673 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7674 UIView *content([self contentView]);
7675 CGRect bounds([content bounds]);
7676
7677 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7678 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7679 [content_ setBackgroundColor:[UIColor whiteColor]];
7680 [content addSubview:content_];
7681
7682 [content_ setDelegate:self];
7683 [content_ setOpaque:YES];
7684 } return self;
7685 }
7686
7687 - (NSString *) accessibilityLabel {
7688 return label_;
7689 }
7690
7691 - (void) drawContentRect:(CGRect)rect {
7692 bool highlighted(highlighted_);
7693 float width(rect.size.width);
7694
7695 if (icon_ != nil)
7696 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7697
7698 if (highlighted)
7699 UISetColor(White_);
7700
7701 if (!highlighted)
7702 UISetColor(Black_);
7703 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7704
7705 if (!highlighted)
7706 UISetColor(Blue_);
7707 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7708 }
7709
7710 @end
7711 /* }}} */
7712 /* Source Controller {{{ */
7713 @interface SourceController : FilteredPackageListController {
7714 _transient Source *source_;
7715 _H<NSString> key_;
7716 }
7717
7718 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7719
7720 @end
7721
7722 @implementation SourceController
7723
7724 - (NSURL *) navigationURL {
7725 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7726 }
7727
7728 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7729 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7730 source_ = source;
7731 key_ = [source key];
7732 } return self;
7733 }
7734
7735 - (void) reloadData {
7736 source_ = [database_ sourceWithKey:key_];
7737 key_ = [source_ key];
7738 [self setObject:source_];
7739
7740 [[self navigationItem] setTitle:[source_ label]];
7741
7742 [super reloadData];
7743 }
7744
7745 @end
7746 /* }}} */
7747 /* Sources Controller {{{ */
7748 @interface SourcesController : CyteViewController <
7749 UITableViewDataSource,
7750 UITableViewDelegate
7751 > {
7752 _transient Database *database_;
7753 _H<UITableView, 2> list_;
7754 _H<NSMutableArray> sources_;
7755 int offset_;
7756
7757 _H<NSString> href_;
7758 _H<UIProgressHUD> hud_;
7759 _H<NSError> error_;
7760
7761 //NSURLConnection *installer_;
7762 NSURLConnection *trivial_;
7763 NSURLConnection *trivial_bz2_;
7764 NSURLConnection *trivial_gz_;
7765 //NSURLConnection *automatic_;
7766
7767 BOOL cydia_;
7768 }
7769
7770 - (id) initWithDatabase:(Database *)database;
7771 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7772
7773 @end
7774
7775 @implementation SourcesController
7776
7777 - (void) _releaseConnection:(NSURLConnection *)connection {
7778 if (connection != nil) {
7779 [connection cancel];
7780 //[connection setDelegate:nil];
7781 [connection release];
7782 }
7783 }
7784
7785 - (void) dealloc {
7786 //[self _releaseConnection:installer_];
7787 [self _releaseConnection:trivial_];
7788 [self _releaseConnection:trivial_gz_];
7789 [self _releaseConnection:trivial_bz2_];
7790 //[self _releaseConnection:automatic_];
7791
7792 [super dealloc];
7793 }
7794
7795 - (NSURL *) navigationURL {
7796 return [NSURL URLWithString:@"cydia://sources"];
7797 }
7798
7799 - (void) viewDidAppear:(BOOL)animated {
7800 [super viewDidAppear:animated];
7801 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7802 }
7803
7804 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7805 return offset_ == 0 ? 1 : 2;
7806 }
7807
7808 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7809 switch (section + (offset_ == 0 ? 1 : 0)) {
7810 case 0: return UCLocalize("ENTERED_BY_USER");
7811 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7812
7813 _nodefault
7814 }
7815 }
7816
7817 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7818 int count = [sources_ count];
7819 switch (section) {
7820 case 0: return (offset_ == 0 ? count : offset_);
7821 case 1: return count - offset_;
7822
7823 _nodefault
7824 }
7825 }
7826
7827 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7828 unsigned idx = 0;
7829 switch (indexPath.section) {
7830 case 0: idx = indexPath.row; break;
7831 case 1: idx = indexPath.row + offset_; break;
7832
7833 _nodefault
7834 }
7835 return [sources_ objectAtIndex:idx];
7836 }
7837
7838 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7839 static NSString *cellIdentifier = @"SourceCell";
7840
7841 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7842 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7843 [cell setSource:[self sourceAtIndexPath:indexPath]];
7844 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7845
7846 return cell;
7847 }
7848
7849 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7850 Source *source = [self sourceAtIndexPath:indexPath];
7851
7852 SourceController *controller = [[[SourceController alloc]
7853 initWithDatabase:database_
7854 source:source
7855 ] autorelease];
7856
7857 [controller setDelegate:delegate_];
7858
7859 [[self navigationController] pushViewController:controller animated:YES];
7860 }
7861
7862 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7863 Source *source = [self sourceAtIndexPath:indexPath];
7864 return [source record] != nil;
7865 }
7866
7867 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7868 if (editingStyle == UITableViewCellEditingStyleDelete) {
7869 Source *source = [self sourceAtIndexPath:indexPath];
7870 [Sources_ removeObjectForKey:[source key]];
7871 [delegate_ syncData];
7872 }
7873 }
7874
7875 - (void) complete {
7876 [delegate_ addTrivialSource:href_];
7877 [delegate_ syncData];
7878 }
7879
7880 - (NSString *) getWarning {
7881 NSString *href(href_);
7882 NSRange colon([href rangeOfString:@"://"]);
7883 if (colon.location != NSNotFound)
7884 href = [href substringFromIndex:(colon.location + 3)];
7885 href = [href stringByAddingPercentEscapes];
7886 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7887 href = [href stringByCachingURLWithCurrentCDN];
7888
7889 NSURL *url([NSURL URLWithString:href]);
7890
7891 NSStringEncoding encoding;
7892 NSError *error(nil);
7893
7894 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7895 return [warning length] == 0 ? nil : warning;
7896 return nil;
7897 }
7898
7899 - (void) _endConnection:(NSURLConnection *)connection {
7900 // XXX: the memory management in this method is horribly awkward
7901
7902 NSURLConnection **field = NULL;
7903 if (connection == trivial_)
7904 field = &trivial_;
7905 else if (connection == trivial_bz2_)
7906 field = &trivial_bz2_;
7907 else if (connection == trivial_gz_)
7908 field = &trivial_gz_;
7909 _assert(field != NULL);
7910 [connection release];
7911 *field = nil;
7912
7913 if (
7914 trivial_ == nil &&
7915 trivial_bz2_ == nil &&
7916 trivial_gz_ == nil
7917 ) {
7918 [delegate_ releaseNetworkActivityIndicator];
7919
7920 [delegate_ removeProgressHUD:hud_];
7921 hud_ = nil;
7922
7923 bool defer(false);
7924
7925 if (cydia_) {
7926 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7927 defer = true;
7928
7929 UIAlertView *alert = [[[UIAlertView alloc]
7930 initWithTitle:UCLocalize("SOURCE_WARNING")
7931 message:warning
7932 delegate:self
7933 cancelButtonTitle:UCLocalize("CANCEL")
7934 otherButtonTitles:
7935 UCLocalize("ADD_ANYWAY"),
7936 nil
7937 ] autorelease];
7938
7939 [alert setContext:@"warning"];
7940 [alert setNumberOfRows:1];
7941 [alert show];
7942 } else
7943 [self complete];
7944 } else if (error_ != nil) {
7945 UIAlertView *alert = [[[UIAlertView alloc]
7946 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7947 message:[error_ localizedDescription]
7948 delegate:self
7949 cancelButtonTitle:UCLocalize("OK")
7950 otherButtonTitles:nil
7951 ] autorelease];
7952
7953 [alert setContext:@"urlerror"];
7954 [alert show];
7955 } else {
7956 UIAlertView *alert = [[[UIAlertView alloc]
7957 initWithTitle:UCLocalize("NOT_REPOSITORY")
7958 message:UCLocalize("NOT_REPOSITORY_EX")
7959 delegate:self
7960 cancelButtonTitle:UCLocalize("OK")
7961 otherButtonTitles:nil
7962 ] autorelease];
7963
7964 [alert setContext:@"trivial"];
7965 [alert show];
7966 }
7967
7968 href_ = nil;
7969 error_ = nil;
7970 }
7971 }
7972
7973 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7974 switch ([response statusCode]) {
7975 case 200:
7976 cydia_ = YES;
7977 }
7978 }
7979
7980 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7981 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7982 error_ = error;
7983 [self _endConnection:connection];
7984 }
7985
7986 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7987 [self _endConnection:connection];
7988 }
7989
7990 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7991 NSMutableURLRequest *request = [NSMutableURLRequest
7992 requestWithURL:[NSURL URLWithString:href]
7993 cachePolicy:NSURLRequestUseProtocolCachePolicy
7994 timeoutInterval:120.0
7995 ];
7996
7997 [request setHTTPMethod:method];
7998
7999 if (Machine_ != NULL)
8000 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8001 if (UniqueID_ != nil)
8002 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8003
8004 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8005 }
8006
8007 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8008 NSString *context([alert context]);
8009
8010 if ([context isEqualToString:@"source"]) {
8011 switch (button) {
8012 case 1: {
8013 NSString *href = [[alert textField] text];
8014
8015 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8016
8017 if (![href hasSuffix:@"/"])
8018 href_ = [href stringByAppendingString:@"/"];
8019 else
8020 href_ = href;
8021
8022 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8023 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8024 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8025 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8026
8027 cydia_ = false;
8028
8029 // XXX: this is stupid
8030 hud_ = [delegate_ addProgressHUD];
8031 [hud_ setText:UCLocalize("VERIFYING_URL")];
8032 [delegate_ retainNetworkActivityIndicator];
8033 } break;
8034
8035 case 0:
8036 break;
8037
8038 _nodefault
8039 }
8040
8041 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8042 } else if ([context isEqualToString:@"trivial"])
8043 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8044 else if ([context isEqualToString:@"urlerror"])
8045 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8046 else if ([context isEqualToString:@"warning"]) {
8047 switch (button) {
8048 case 1:
8049 [self complete];
8050 break;
8051
8052 case 0:
8053 break;
8054
8055 _nodefault
8056 }
8057
8058 href_ = nil;
8059
8060 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8061 }
8062 }
8063
8064 - (void) loadView {
8065 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8066
8067 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8068 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8069 [list_ setRowHeight:56];
8070 [(UITableView *) list_ setDataSource:self];
8071 [list_ setDelegate:self];
8072 [[self view] addSubview:list_];
8073 }
8074
8075 - (void) viewDidLoad {
8076 [super viewDidLoad];
8077
8078 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8079 [self updateButtonsForEditingStatus:NO animated:NO];
8080 }
8081
8082 - (void) releaseSubviews {
8083 list_ = nil;
8084 }
8085
8086 - (id) initWithDatabase:(Database *)database {
8087 if ((self = [super init]) != nil) {
8088 database_ = database;
8089 sources_ = [NSMutableArray arrayWithCapacity:16];
8090 } return self;
8091 }
8092
8093 - (void) reloadData {
8094 [super reloadData];
8095
8096 pkgSourceList list;
8097 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8098 return;
8099
8100 [sources_ removeAllObjects];
8101 [sources_ addObjectsFromArray:[database_ sources]];
8102 _trace();
8103 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8104 _trace();
8105
8106 int count([sources_ count]);
8107 offset_ = 0;
8108 for (int i = 0; i != count; i++) {
8109 if ([[sources_ objectAtIndex:i] record] == nil)
8110 break;
8111 offset_++;
8112 }
8113
8114 [list_ setEditing:NO];
8115 [self updateButtonsForEditingStatus:NO animated:NO];
8116 [list_ reloadData];
8117 }
8118
8119 - (void) showAddSourcePrompt {
8120 UIAlertView *alert = [[[UIAlertView alloc]
8121 initWithTitle:UCLocalize("ENTER_APT_URL")
8122 message:nil
8123 delegate:self
8124 cancelButtonTitle:UCLocalize("CANCEL")
8125 otherButtonTitles:
8126 UCLocalize("ADD_SOURCE"),
8127 nil
8128 ] autorelease];
8129
8130 [alert setContext:@"source"];
8131
8132 [alert setNumberOfRows:1];
8133 [alert addTextFieldWithValue:@"http://" label:@""];
8134
8135 UITextInputTraits *traits = [[alert textField] textInputTraits];
8136 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8137 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8138 [traits setKeyboardType:UIKeyboardTypeURL];
8139 // XXX: UIReturnKeyDone
8140 [traits setReturnKeyType:UIReturnKeyNext];
8141
8142 [alert show];
8143 }
8144
8145 - (void) addButtonClicked {
8146 [self showAddSourcePrompt];
8147 }
8148
8149 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8150 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8151 initWithTitle:UCLocalize("ADD")
8152 style:UIBarButtonItemStylePlain
8153 target:self
8154 action:@selector(addButtonClicked)
8155 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8156
8157 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8158 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8159 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8160 target:self
8161 action:@selector(editButtonClicked)
8162 ] autorelease] animated:animated];
8163
8164 if (IsWildcat_ && !editing)
8165 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8166 initWithTitle:UCLocalize("SETTINGS")
8167 style:UIBarButtonItemStylePlain
8168 target:self
8169 action:@selector(settingsButtonClicked)
8170 ] autorelease]];
8171 }
8172
8173 - (void) settingsButtonClicked {
8174 [delegate_ showSettings];
8175 }
8176
8177 - (void) editButtonClicked {
8178 [list_ setEditing:![list_ isEditing] animated:YES];
8179
8180 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8181 }
8182
8183 @end
8184 /* }}} */
8185
8186 /* Settings Controller {{{ */
8187 @interface SettingsController : CyteViewController <
8188 UITableViewDataSource,
8189 UITableViewDelegate
8190 > {
8191 _transient Database *database_;
8192 // XXX: ok, "roledelegate_"?...
8193 _transient id roledelegate_;
8194 _H<UITableView, 2> table_;
8195 _H<UISegmentedControl> segment_;
8196 _H<UIView> container_;
8197 }
8198
8199 - (void) showDoneButton;
8200 - (void) resizeSegmentedControl;
8201
8202 @end
8203
8204 @implementation SettingsController
8205
8206 - (void) loadView {
8207 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8208
8209 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8210 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8211 [table_ setDelegate:self];
8212 [(UITableView *) table_ setDataSource:self];
8213 [[self view] addSubview:table_];
8214
8215 NSArray *items = [NSArray arrayWithObjects:
8216 UCLocalize("USER"),
8217 UCLocalize("HACKER"),
8218 UCLocalize("DEVELOPER"),
8219 nil];
8220 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8221 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8222 [container_ addSubview:segment_];
8223 }
8224
8225 - (void) viewDidLoad {
8226 [super viewDidLoad];
8227
8228 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8229
8230 int index = -1;
8231 if ([Role_ isEqualToString:@"User"]) index = 0;
8232 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8233 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8234 if (index != -1) {
8235 [segment_ setSelectedSegmentIndex:index];
8236 [self showDoneButton];
8237 }
8238
8239 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8240 [self resizeSegmentedControl];
8241 }
8242
8243 - (void) releaseSubviews {
8244 table_ = nil;
8245 segment_ = nil;
8246 container_ = nil;
8247 }
8248
8249 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8250 if ((self = [super init]) != nil) {
8251 database_ = database;
8252 roledelegate_ = delegate;
8253 } return self;
8254 }
8255
8256 - (void) resizeSegmentedControl {
8257 CGFloat width = [[self view] frame].size.width;
8258 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8259 }
8260
8261 - (void) viewWillAppear:(BOOL)animated {
8262 [super viewWillAppear:animated];
8263
8264 [self resizeSegmentedControl];
8265 }
8266
8267 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8268 [self resizeSegmentedControl];
8269 }
8270
8271 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8272 [self resizeSegmentedControl];
8273 }
8274
8275 - (void) save {
8276 NSString *role(nil);
8277
8278 switch ([segment_ selectedSegmentIndex]) {
8279 case 0: role = @"User"; break;
8280 case 1: role = @"Hacker"; break;
8281 case 2: role = @"Developer"; break;
8282
8283 _nodefault
8284 }
8285
8286 if (![role isEqualToString:Role_]) {
8287 bool rolling(Role_ == nil);
8288 Role_ = role;
8289
8290 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8291 Role_, @"Role",
8292 nil];
8293
8294 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8295 Changed_ = true;
8296
8297 if (rolling)
8298 [roledelegate_ loadData];
8299 else
8300 [roledelegate_ updateData];
8301 }
8302 }
8303
8304 - (void) segmentChanged:(UISegmentedControl *)control {
8305 [self showDoneButton];
8306 }
8307
8308 - (void) saveAndClose {
8309 [self save];
8310
8311 [[self navigationItem] setRightBarButtonItem:nil];
8312 [[self navigationController] dismissModalViewControllerAnimated:YES];
8313 }
8314
8315 - (void) doneButtonClicked {
8316 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8317 [spinner startAnimating];
8318 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8319 [[self navigationItem] setRightBarButtonItem:spinItem];
8320
8321 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8322 }
8323
8324 - (void) showDoneButton {
8325 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8326 initWithTitle:UCLocalize("DONE")
8327 style:UIBarButtonItemStyleDone
8328 target:self
8329 action:@selector(doneButtonClicked)
8330 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8331 }
8332
8333 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8334 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8335 return 6;
8336 }
8337
8338 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8339 return 0; // :(
8340 }
8341
8342 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8343 return nil; // This method is required by the protocol.
8344 }
8345
8346 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8347 if (section == 1)
8348 return UCLocalize("ROLE_EX");
8349 if (section == 4)
8350 return [NSString stringWithFormat:
8351 @"%@: %@\n%@: %@\n%@: %@",
8352 UCLocalize("USER"), UCLocalize("USER_EX"),
8353 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8354 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8355 ];
8356 else return nil;
8357 }
8358
8359 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8360 return section == 3 ? 44.0f : 0;
8361 }
8362
8363 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8364 return section == 3 ? container_ : nil;
8365 }
8366
8367 - (void) reloadData {
8368 [super reloadData];
8369
8370 [table_ reloadData];
8371 }
8372
8373 @end
8374 /* }}} */
8375 /* Stash Controller {{{ */
8376 @interface StashController : CyteViewController {
8377 _H<UIActivityIndicatorView> spinner_;
8378 _H<UILabel> status_;
8379 _H<UILabel> caption_;
8380 }
8381
8382 @end
8383
8384 @implementation StashController
8385
8386 - (void) loadView {
8387 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8388 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8389
8390 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8391 CGRect spinrect = [spinner_ frame];
8392 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8393 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8394 [spinner_ setFrame:spinrect];
8395 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8396 [[self view] addSubview:spinner_];
8397 [spinner_ startAnimating];
8398
8399 CGRect captrect;
8400 captrect.size.width = [[self view] frame].size.width;
8401 captrect.size.height = 40.0f;
8402 captrect.origin.x = 0;
8403 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8404 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8405 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8406 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8407 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8408 [caption_ setTextColor:[UIColor whiteColor]];
8409 [caption_ setBackgroundColor:[UIColor clearColor]];
8410 [caption_ setShadowColor:[UIColor blackColor]];
8411 [caption_ setTextAlignment:UITextAlignmentCenter];
8412 [[self view] addSubview:caption_];
8413
8414 CGRect statusrect;
8415 statusrect.size.width = [[self view] frame].size.width;
8416 statusrect.size.height = 30.0f;
8417 statusrect.origin.x = 0;
8418 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8419 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8420 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8421 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8422 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8423 [status_ setTextColor:[UIColor whiteColor]];
8424 [status_ setBackgroundColor:[UIColor clearColor]];
8425 [status_ setShadowColor:[UIColor blackColor]];
8426 [status_ setTextAlignment:UITextAlignmentCenter];
8427 [[self view] addSubview:status_];
8428 }
8429
8430 @end
8431 /* }}} */
8432
8433 @interface CYURLCache : SDURLCache {
8434 }
8435
8436 @end
8437
8438 @implementation CYURLCache
8439
8440 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8441 #if !ForRelease
8442 if (false);
8443 else if ([event isEqualToString:@"no-cache"])
8444 event = @"!!!";
8445 else if ([event isEqualToString:@"store"])
8446 event = @">>>";
8447 else if ([event isEqualToString:@"invalid"])
8448 event = @"???";
8449 else if ([event isEqualToString:@"memory"])
8450 event = @"mem";
8451 else if ([event isEqualToString:@"disk"])
8452 event = @"ssd";
8453 else if ([event isEqualToString:@"miss"])
8454 event = @"---";
8455
8456 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8457 #endif
8458 }
8459
8460 @end
8461
8462 @interface Cydia : UIApplication <
8463 ConfirmationControllerDelegate,
8464 DatabaseDelegate,
8465 CydiaDelegate,
8466 UINavigationControllerDelegate,
8467 UITabBarControllerDelegate
8468 > {
8469 _H<UIWindow> window_;
8470 _H<CYTabBarController> tabbar_;
8471 _H<CYEmulatedLoadingController> emulated_;
8472
8473 _H<NSMutableArray> essential_;
8474 _H<NSMutableArray> broken_;
8475
8476 Database *database_;
8477
8478 _H<NSURL> starturl_;
8479
8480 unsigned locked_;
8481 unsigned activity_;
8482
8483 _H<StashController> stash_;
8484
8485 bool loaded_;
8486 }
8487
8488 - (void) loadData;
8489
8490 @end
8491
8492 @implementation Cydia
8493
8494 - (void) beginUpdate {
8495 [tabbar_ beginUpdate];
8496 }
8497
8498 - (BOOL) updating {
8499 return [tabbar_ updating];
8500 }
8501
8502 - (void) _loaded {
8503 if ([broken_ count] != 0) {
8504 int count = [broken_ count];
8505
8506 UIAlertView *alert = [[[UIAlertView alloc]
8507 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8508 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8509 delegate:self
8510 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8511 otherButtonTitles:
8512 UCLocalize("TEMPORARY_IGNORE"),
8513 nil
8514 ] autorelease];
8515
8516 [alert setContext:@"fixhalf"];
8517 [alert setNumberOfRows:2];
8518 [alert show];
8519 } else if (!Ignored_ && [essential_ count] != 0) {
8520 int count = [essential_ count];
8521
8522 UIAlertView *alert = [[[UIAlertView alloc]
8523 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8524 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8525 delegate:self
8526 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8527 otherButtonTitles:
8528 UCLocalize("UPGRADE_ESSENTIAL"),
8529 UCLocalize("COMPLETE_UPGRADE"),
8530 nil
8531 ] autorelease];
8532
8533 [alert setContext:@"upgrade"];
8534 [alert show];
8535 }
8536 }
8537
8538 - (void) _saveConfig {
8539 _trace();
8540 MetaFile_.Sync();
8541 _trace();
8542
8543 if (Changed_) {
8544 NSString *error(nil);
8545
8546 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8547 _trace();
8548 NSError *error(nil);
8549 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8550 NSLog(@"failure to save metadata data: %@", error);
8551 _trace();
8552
8553 Changed_ = false;
8554 } else {
8555 NSLog(@"failure to serialize metadata: %@", error);
8556 }
8557 }
8558 }
8559
8560 // Navigation controller for the queuing badge.
8561 - (UINavigationController *) queueNavigationController {
8562 NSArray *controllers = [tabbar_ viewControllers];
8563 return [controllers objectAtIndex:3];
8564 }
8565
8566 - (void) unloadData {
8567 [tabbar_ unloadData];
8568 }
8569
8570 - (void) _updateData {
8571 [self _saveConfig];
8572
8573 [self unloadData];
8574
8575 UINavigationController *navigation = [self queueNavigationController];
8576
8577 id queuedelegate = nil;
8578 if ([[navigation viewControllers] count] > 0)
8579 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8580
8581 [queuedelegate queueStatusDidChange];
8582 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8583 }
8584
8585 - (void) _refreshIfPossible:(NSDate *)update {
8586 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8587
8588 bool recently = false;
8589 if (update != nil) {
8590 NSTimeInterval interval([update timeIntervalSinceNow]);
8591 if (interval <= 0 && interval > -(15*60))
8592 recently = true;
8593 }
8594
8595 // Don't automatic refresh if:
8596 // - We already refreshed recently.
8597 // - We already auto-refreshed this launch.
8598 // - Auto-refresh is disabled.
8599 if (recently || loaded_ || ManualRefresh) {
8600 // If we are cancelling, we need to make sure it knows it's already loaded.
8601 loaded_ = true;
8602
8603 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8604 } else {
8605 // We are going to load, so remember that.
8606 loaded_ = true;
8607
8608 SCNetworkReachabilityFlags flags; {
8609 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8610 SCNetworkReachabilityGetFlags(reachability, &flags);
8611 CFRelease(reachability);
8612 }
8613
8614 // XXX: this elaborate mess is what Apple is using to determine this? :(
8615 // XXX: do we care if the user has to intervene? maybe that's ok?
8616 bool reachable(
8617 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8618 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8619 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8620 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8621 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8622 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8623 )
8624 );
8625
8626 // If we can reach the server, auto-refresh!
8627 if (reachable)
8628 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8629 }
8630
8631 [pool release];
8632 }
8633
8634 - (void) refreshIfPossible {
8635 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8636 }
8637
8638 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8639 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8640 [hud setText:UCLocalize("RELOADING_DATA")];
8641
8642 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8643
8644 if (hud != nil)
8645 [self removeProgressHUD:hud];
8646
8647 size_t changes(0);
8648
8649 [essential_ removeAllObjects];
8650 [broken_ removeAllObjects];
8651
8652 NSArray *packages([database_ packages]);
8653 for (Package *package in packages) {
8654 if ([package half])
8655 [broken_ addObject:package];
8656 if ([package upgradableAndEssential:NO]) {
8657 if ([package essential])
8658 [essential_ addObject:package];
8659 ++changes;
8660 }
8661 }
8662
8663 NSLog(@"changes:#%u", changes);
8664
8665 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8666 if (changes != 0) {
8667 _trace();
8668 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8669 [changesItem setBadgeValue:badge];
8670 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8671 [self setApplicationIconBadgeNumber:changes];
8672 } else {
8673 _trace();
8674 [changesItem setBadgeValue:nil];
8675 [changesItem setAnimatedBadge:NO];
8676 [self setApplicationIconBadgeNumber:0];
8677 }
8678
8679 [self _updateData];
8680
8681 [self refreshIfPossible];
8682 }
8683
8684 - (void) updateData {
8685 [self _updateData];
8686 }
8687
8688 - (void) update_ {
8689 [database_ update];
8690 }
8691
8692 - (void) complete {
8693 @synchronized (self) {
8694 [self _reloadDataWithInvocation:nil];
8695 }
8696 }
8697
8698 - (void) disemulate {
8699 if (emulated_ == nil)
8700 return;
8701
8702 [window_ addSubview:[tabbar_ view]];
8703 [[emulated_ view] removeFromSuperview];
8704 emulated_ = nil;
8705 [window_ setUserInteractionEnabled:YES];
8706 }
8707
8708 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8709 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8710 if (IsWildcat_)
8711 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8712
8713 UIViewController *parent;
8714 if (emulated_ == nil)
8715 parent = tabbar_;
8716 else if (!force)
8717 parent = emulated_;
8718 else {
8719 [self disemulate];
8720 parent = tabbar_;
8721 }
8722
8723 [parent presentModalViewController:navigation animated:YES];
8724 }
8725
8726 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8727 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8728
8729 if (navigation != nil)
8730 [navigation pushViewController:progress animated:YES];
8731 else
8732 [self presentModalViewController:progress force:YES];
8733
8734 [progress invoke:invocation withTitle:title];
8735 return progress;
8736 }
8737
8738 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8739 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8740 }
8741
8742 - (void) repairWithInvocation:(NSInvocation *)invocation {
8743 _trace();
8744 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8745 _trace();
8746 }
8747
8748 - (void) repairWithSelector:(SEL)selector {
8749 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8750 }
8751
8752 - (void) syncData {
8753 [self _saveConfig];
8754
8755 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8756 _assert(file != NULL);
8757
8758 for (NSString *key in [Sources_ allKeys]) {
8759 NSDictionary *source([Sources_ objectForKey:key]);
8760
8761 fprintf(file, "%s %s %s\n",
8762 [[source objectForKey:@"Type"] UTF8String],
8763 [[source objectForKey:@"URI"] UTF8String],
8764 [[source objectForKey:@"Distribution"] UTF8String]
8765 );
8766 }
8767
8768 fclose(file);
8769
8770 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8771
8772 [self complete];
8773 }
8774
8775 - (void) addTrivialSource:(NSString *)href {
8776 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8777 @"deb", @"Type",
8778 href, @"URI",
8779 @"./", @"Distribution",
8780 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8781
8782 Changed_ = true;
8783 }
8784
8785 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8786 @synchronized (self) {
8787 [self _reloadDataWithInvocation:invocation];
8788 }
8789 }
8790
8791 - (void) reloadData {
8792 [self reloadDataWithInvocation:nil];
8793 }
8794
8795 - (void) resolve {
8796 pkgProblemResolver *resolver = [database_ resolver];
8797
8798 resolver->InstallProtect();
8799 if (!resolver->Resolve(true))
8800 _error->Discard();
8801 }
8802
8803 - (bool) perform {
8804 // XXX: this is a really crappy way of doing this.
8805 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8806 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8807 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8808 if ([tabbar_ updating])
8809 [tabbar_ cancelUpdate];
8810
8811 if (![database_ prepare])
8812 return false;
8813
8814 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8815 [page setDelegate:self];
8816 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8817
8818 if (IsWildcat_)
8819 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8820 [tabbar_ presentModalViewController:confirm_ animated:YES];
8821
8822 return true;
8823 }
8824
8825 - (void) queue {
8826 @synchronized (self) {
8827 [self perform];
8828 }
8829 }
8830
8831 - (void) clearPackage:(Package *)package {
8832 @synchronized (self) {
8833 [package clear];
8834 [self resolve];
8835 [self perform];
8836 }
8837 }
8838
8839 - (void) installPackages:(NSArray *)packages {
8840 @synchronized (self) {
8841 for (Package *package in packages)
8842 [package install];
8843 [self resolve];
8844 [self perform];
8845 }
8846 }
8847
8848 - (void) installPackage:(Package *)package {
8849 @synchronized (self) {
8850 [package install];
8851 [self resolve];
8852 [self perform];
8853 }
8854 }
8855
8856 - (void) removePackage:(Package *)package {
8857 @synchronized (self) {
8858 [package remove];
8859 [self resolve];
8860 [self perform];
8861 }
8862 }
8863
8864 - (void) distUpgrade {
8865 @synchronized (self) {
8866 if (![database_ upgrade])
8867 return;
8868 [self perform];
8869 }
8870 }
8871
8872 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8873 Queuing_ = false;
8874 ++locked_;
8875 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
8876 --locked_;
8877 [self complete];
8878 }
8879
8880 - (void) showSettings {
8881 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8882 }
8883
8884 - (void) retainNetworkActivityIndicator {
8885 if (activity_++ == 0)
8886 [self setNetworkActivityIndicatorVisible:YES];
8887
8888 #if TraceLogging
8889 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
8890 #endif
8891 }
8892
8893 - (void) releaseNetworkActivityIndicator {
8894 if (--activity_ == 0)
8895 [self setNetworkActivityIndicatorVisible:NO];
8896
8897 #if TraceLogging
8898 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
8899 #endif
8900
8901 }
8902
8903 - (void) cancelAndClear:(bool)clear {
8904 @synchronized (self) {
8905 if (clear) {
8906 [database_ clear];
8907 Queuing_ = false;
8908 } else {
8909 Queuing_ = true;
8910 }
8911
8912 [self _updateData];
8913 }
8914 }
8915
8916 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8917 NSString *context([alert context]);
8918
8919 if ([context isEqualToString:@"conffile"]) {
8920 FILE *input = [database_ input];
8921 if (button == [alert cancelButtonIndex])
8922 fprintf(input, "N\n");
8923 else if (button == [alert firstOtherButtonIndex])
8924 fprintf(input, "Y\n");
8925 fflush(input);
8926
8927 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8928 } else if ([context isEqualToString:@"fixhalf"]) {
8929 if (button == [alert cancelButtonIndex]) {
8930 @synchronized (self) {
8931 for (Package *broken in (id) broken_) {
8932 [broken remove];
8933
8934 NSString *id = [broken id];
8935 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8936 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8937 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8938 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8939 }
8940
8941 [self resolve];
8942 [self perform];
8943 }
8944 } else if (button == [alert firstOtherButtonIndex]) {
8945 [broken_ removeAllObjects];
8946 [self _loaded];
8947 }
8948
8949 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8950 } else if ([context isEqualToString:@"upgrade"]) {
8951 if (button == [alert firstOtherButtonIndex]) {
8952 @synchronized (self) {
8953 for (Package *essential in (id) essential_)
8954 [essential install];
8955
8956 [self resolve];
8957 [self perform];
8958 }
8959 } else if (button == [alert firstOtherButtonIndex] + 1) {
8960 [self distUpgrade];
8961 } else if (button == [alert cancelButtonIndex]) {
8962 Ignored_ = YES;
8963 }
8964
8965 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8966 }
8967 }
8968
8969 - (void) system:(NSString *)command {
8970 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8971
8972 _trace();
8973 system([command UTF8String]);
8974 _trace();
8975
8976 [pool release];
8977 }
8978
8979 - (void) applicationWillSuspend {
8980 [database_ clean];
8981 [super applicationWillSuspend];
8982 }
8983
8984 - (BOOL) isSafeToSuspend {
8985 if (locked_ != 0) {
8986 #if !ForRelease
8987 NSLog(@"isSafeToSuspend: locked_ != 0");
8988 #endif
8989 return false;
8990 }
8991
8992 // Use external process status API internally.
8993 // This is probably a really bad idea.
8994 // XXX: what is the point of this? does this solve anything at all?
8995 uint64_t status = 0;
8996 int notify_token;
8997 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
8998 notify_get_state(notify_token, &status);
8999 notify_cancel(notify_token);
9000 }
9001
9002 if (status != 0) {
9003 #if !ForRelease
9004 NSLog(@"isSafeToSuspend: status != 0");
9005 #endif
9006 return false;
9007 }
9008
9009 #if !ForRelease
9010 NSLog(@"isSafeToSuspend: -> true");
9011 #endif
9012 return true;
9013 }
9014
9015 - (void) applicationSuspend:(__GSEvent *)event {
9016 if ([self isSafeToSuspend])
9017 [super applicationSuspend:event];
9018 }
9019
9020 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9021 if ([self isSafeToSuspend])
9022 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9023 }
9024
9025 - (void) _setSuspended:(BOOL)value {
9026 if ([self isSafeToSuspend])
9027 [super _setSuspended:value];
9028 }
9029
9030 - (UIProgressHUD *) addProgressHUD {
9031 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9032 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9033
9034 [window_ setUserInteractionEnabled:NO];
9035
9036 UIViewController *target(tabbar_);
9037 if (UIViewController *modal = [target modalViewController])
9038 target = modal;
9039
9040 UIView *view([target view]);
9041 [view addSubview:hud];
9042
9043 [hud show:YES];
9044
9045 ++locked_;
9046 return hud;
9047 }
9048
9049 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9050 --locked_;
9051 [hud show:NO];
9052 [hud removeFromSuperview];
9053 [window_ setUserInteractionEnabled:YES];
9054 }
9055
9056 - (CyteViewController *) pageForPackage:(NSString *)name {
9057 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9058 }
9059
9060 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9061 NSString *scheme([[url scheme] lowercaseString]);
9062 if ([[url absoluteString] length] <= [scheme length] + 3)
9063 return nil;
9064 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9065 NSArray *components([path pathComponents]);
9066
9067 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9068 return [self pageForPackage:[components objectAtIndex:1]];
9069
9070 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9071 return nil;
9072
9073 NSString *base([components objectAtIndex:0]);
9074
9075 CyteViewController *controller = nil;
9076
9077 if ([base isEqualToString:@"url"]) {
9078 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9079 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9080 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9081 } else if (!external && [components count] == 1) {
9082 if ([base isEqualToString:@"manage"]) {
9083 controller = [[[ManageController alloc] init] autorelease];
9084 }
9085
9086 if ([base isEqualToString:@"sources"]) {
9087 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9088 }
9089
9090 if ([base isEqualToString:@"home"]) {
9091 controller = [[[HomeController alloc] init] autorelease];
9092 }
9093
9094 if ([base isEqualToString:@"sections"]) {
9095 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9096 }
9097
9098 if ([base isEqualToString:@"search"]) {
9099 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9100 }
9101
9102 if ([base isEqualToString:@"changes"]) {
9103 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9104 }
9105
9106 if ([base isEqualToString:@"installed"]) {
9107 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9108 }
9109 } else if ([components count] == 2) {
9110 NSString *argument = [components objectAtIndex:1];
9111
9112 if ([base isEqualToString:@"package"]) {
9113 controller = [self pageForPackage:argument];
9114 }
9115
9116 if (!external && [base isEqualToString:@"search"]) {
9117 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9118 }
9119
9120 if (!external && [base isEqualToString:@"sections"]) {
9121 if ([argument isEqualToString:@"all"])
9122 argument = nil;
9123 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9124 }
9125
9126 if (!external && [base isEqualToString:@"sources"]) {
9127 if ([argument isEqualToString:@"add"]) {
9128 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9129 [(SourcesController *)controller showAddSourcePrompt];
9130 } else {
9131 Source *source = [database_ sourceWithKey:argument];
9132 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9133 }
9134 }
9135
9136 if (!external && [base isEqualToString:@"launch"]) {
9137 [self launchApplicationWithIdentifier:argument suspended:NO];
9138 return nil;
9139 }
9140 } else if (!external && [components count] == 3) {
9141 NSString *arg1 = [components objectAtIndex:1];
9142 NSString *arg2 = [components objectAtIndex:2];
9143
9144 if ([base isEqualToString:@"package"]) {
9145 if ([arg2 isEqualToString:@"settings"]) {
9146 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9147 } else if ([arg2 isEqualToString:@"files"]) {
9148 if (Package *package = [database_ packageWithName:arg1]) {
9149 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9150 [(FileTable *)controller setPackage:package];
9151 }
9152 }
9153 }
9154 }
9155
9156 [controller setDelegate:self];
9157 return controller;
9158 }
9159
9160 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9161 CyteViewController *page([self pageForURL:url forExternal:external]);
9162
9163 if (page != nil) {
9164 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9165 [nav setViewControllers:[NSArray arrayWithObject:page]];
9166 [tabbar_ setUnselectedViewController:nav];
9167 }
9168
9169 return page != nil;
9170 }
9171
9172 - (void) applicationOpenURL:(NSURL *)url {
9173 [super applicationOpenURL:url];
9174
9175 if (!loaded_)
9176 starturl_ = url;
9177 else
9178 [self openCydiaURL:url forExternal:YES];
9179 }
9180
9181 - (void) applicationWillResignActive:(UIApplication *)application {
9182 // Stop refreshing if you get a phone call or lock the device.
9183 if ([tabbar_ updating])
9184 [tabbar_ cancelUpdate];
9185
9186 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9187 [super applicationWillResignActive:application];
9188 }
9189
9190 - (void) applicationWillTerminate:(UIApplication *)application {
9191 Changed_ = true;
9192 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9193 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9194 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9195
9196 [self _saveConfig];
9197 }
9198
9199 - (void) setConfigurationData:(NSString *)data {
9200 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9201
9202 if (!conffile_r(data)) {
9203 lprintf("E:invalid conffile\n");
9204 return;
9205 }
9206
9207 NSString *ofile = conffile_r[1];
9208 //NSString *nfile = conffile_r[2];
9209
9210 UIAlertView *alert = [[[UIAlertView alloc]
9211 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9212 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9213 delegate:self
9214 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9215 otherButtonTitles:
9216 UCLocalize("ACCEPT_NEW_COPY"),
9217 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9218 nil
9219 ] autorelease];
9220
9221 [alert setContext:@"conffile"];
9222 [alert setNumberOfRows:2];
9223 [alert show];
9224 }
9225
9226 - (void) addStashController {
9227 ++locked_;
9228 stash_ = [[[StashController alloc] init] autorelease];
9229 [window_ addSubview:[stash_ view]];
9230 }
9231
9232 - (void) removeStashController {
9233 [[stash_ view] removeFromSuperview];
9234 stash_ = nil;
9235 --locked_;
9236 }
9237
9238 - (void) stash {
9239 [self setIdleTimerDisabled:YES];
9240
9241 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9242 UpdateExternalStatus(1);
9243 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9244 UpdateExternalStatus(0);
9245
9246 [self removeStashController];
9247
9248 if (ExecFork() == 0) {
9249 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9250 perror("launchctl stop");
9251 }
9252 }
9253
9254 - (void) setupViewControllers {
9255 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9256
9257 NSMutableArray *items([NSMutableArray arrayWithObjects:
9258 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9259 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9260 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9261 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9262 nil]);
9263
9264 if (IsWildcat_) {
9265 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9266 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9267 } else {
9268 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9269 }
9270
9271 NSMutableArray *controllers([NSMutableArray array]);
9272 for (UITabBarItem *item in items) {
9273 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9274 [controller setTabBarItem:item];
9275 [controllers addObject:controller];
9276 }
9277 [tabbar_ setViewControllers:controllers];
9278
9279 [tabbar_ setUpdateDelegate:self];
9280 }
9281
9282 - (void) applicationDidFinishLaunching:(id)unused {
9283 _trace();
9284 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9285 [self setApplicationSupportsShakeToEdit:NO];
9286
9287 @synchronized (HostConfig_) {
9288 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9289 }
9290
9291 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9292 initWithMemoryCapacity:524288
9293 diskCapacity:10485760
9294 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9295 ] autorelease]];
9296
9297 [CydiaWebViewController _initialize];
9298
9299 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9300
9301 // this would disallow http{,s} URLs from accessing this data
9302 //[WebView registerURLSchemeAsLocal:@"cydia"];
9303
9304 Font12_ = [UIFont systemFontOfSize:12];
9305 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9306 Font14_ = [UIFont systemFontOfSize:14];
9307 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9308 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9309
9310 essential_ = [NSMutableArray arrayWithCapacity:4];
9311 broken_ = [NSMutableArray arrayWithCapacity:4];
9312
9313 // XXX: I really need this thing... like, seriously... I'm sorry
9314 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9315
9316 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9317 [window_ orderFront:self];
9318 [window_ makeKey:self];
9319 [window_ setHidden:NO];
9320
9321 if (
9322 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9323 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9324 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9325 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9326 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9327 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9328 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9329 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9330 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9331 false
9332 ) {
9333 [self addStashController];
9334 // XXX: this would be much cleaner as a yieldToSelector:
9335 // that way the removeStashController could happen right here inline
9336 // we also could no longer require the useless stash_ field anymore
9337 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9338 return;
9339 }
9340
9341 database_ = [Database sharedInstance];
9342 [database_ setDelegate:self];
9343
9344 [window_ setUserInteractionEnabled:NO];
9345 [self setupViewControllers];
9346
9347 emulated_ = [[[CYEmulatedLoadingController alloc] init] autorelease];
9348 [window_ addSubview:[emulated_ view]];
9349
9350 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9351 _trace();
9352 }
9353
9354 - (NSArray *) defaultStartPages {
9355 NSMutableArray *standard = [NSMutableArray array];
9356 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9357 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9358 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9359 if (!IsWildcat_) {
9360 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9361 } else {
9362 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9363 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9364 }
9365 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9366 return standard;
9367 }
9368
9369 - (void) loadData {
9370 _trace();
9371 if (Role_ == nil) {
9372 [window_ setUserInteractionEnabled:YES];
9373 [self showSettings];
9374 return;
9375 } else {
9376 if ([emulated_ modalViewController] != nil)
9377 [emulated_ dismissModalViewControllerAnimated:YES];
9378 [window_ setUserInteractionEnabled:NO];
9379 }
9380
9381 [self reloadData];
9382 PrintTimes();
9383
9384 [self disemulate];
9385
9386 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9387 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9388 int standardIndex = 0;
9389 NSArray *standard = [self defaultStartPages];
9390
9391 BOOL valid = YES;
9392
9393 if (saved == nil)
9394 valid = NO;
9395
9396 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9397 if (valid && closed != nil) {
9398 NSTimeInterval interval([closed timeIntervalSinceNow]);
9399 // XXX: Is 15 minutes the optimal time here?
9400 if (interval > 0 && interval <= -(15*60))
9401 valid = NO;
9402 }
9403
9404 if (valid && [saved count] != [standard count])
9405 valid = NO;
9406
9407 if (valid) {
9408 for (unsigned int i = 0; i < [standard count]; i++) {
9409 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9410 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9411 // but it's good enough for now.
9412 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9413 valid = NO;
9414 break;
9415 }
9416 }
9417 }
9418
9419 NSArray *items = nil;
9420 if (valid) {
9421 [tabbar_ setSelectedIndex:savedIndex];
9422 items = saved;
9423 } else {
9424 [tabbar_ setSelectedIndex:standardIndex];
9425 items = standard;
9426 }
9427
9428 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9429 NSArray *stack = [items objectAtIndex:tab];
9430 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9431 NSMutableArray *current = [NSMutableArray array];
9432
9433 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9434 NSString *addr = [stack objectAtIndex:nav];
9435 NSURL *url = [NSURL URLWithString:addr];
9436 CyteViewController *page = [self pageForURL:url forExternal:NO];
9437 if (page != nil)
9438 [current addObject:page];
9439 }
9440
9441 [navigation setViewControllers:current];
9442 }
9443
9444 // (Try to) show the startup URL.
9445 if (starturl_ != nil) {
9446 [self openCydiaURL:starturl_ forExternal:NO];
9447 starturl_ = nil;
9448 }
9449 }
9450
9451 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9452 if (item != nil && IsWildcat_) {
9453 [sheet showFromBarButtonItem:item animated:YES];
9454 } else {
9455 [sheet showInView:window_];
9456 }
9457 }
9458
9459 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9460 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9461 [progress setTitle:task];
9462 [progress addProgressEvent:event];
9463 }
9464
9465 - (void) addProgressEventForTask:(NSArray *)data {
9466 CydiaProgressEvent *event([data objectAtIndex:0]);
9467 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9468 [self addProgressEvent:event forTask:task];
9469 }
9470
9471 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9472 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9473 }
9474
9475 @end
9476
9477 /*IMP alloc_;
9478 id Alloc_(id self, SEL selector) {
9479 id object = alloc_(self, selector);
9480 lprintf("[%s]A-%p\n", self->isa->name, object);
9481 return object;
9482 }*/
9483
9484 /*IMP dealloc_;
9485 id Dealloc_(id self, SEL selector) {
9486 id object = dealloc_(self, selector);
9487 lprintf("[%s]D-%p\n", self->isa->name, object);
9488 return object;
9489 }*/
9490
9491 Class $WebDefaultUIKitDelegate;
9492
9493 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9494 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9495 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9496 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9497 }
9498
9499 static NSSet *MobilizedFiles_;
9500
9501 static NSURL *MobilizeURL(NSURL *url) {
9502 NSString *path([url path]);
9503 if ([path hasPrefix:@"/var/root/"]) {
9504 NSString *file([path substringFromIndex:10]);
9505 if ([MobilizedFiles_ containsObject:file])
9506 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9507 }
9508
9509 return url;
9510 }
9511
9512 Class $CFXPreferencesPropertyListSource;
9513 @class CFXPreferencesPropertyListSource;
9514
9515 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9516 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9517 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9518 url = MobilizeURL(url);
9519 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9520 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9521 url = old;
9522 [pool release];
9523 return value;
9524 }
9525
9526 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9527 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9528 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9529 url = MobilizeURL(url);
9530 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9531 //NSLog(@"%@ %@", [url absoluteString], value);
9532 url = old;
9533 [pool release];
9534 return value;
9535 }
9536
9537 Class $NSURLConnection;
9538
9539 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9540 NSMutableURLRequest *copy([request mutableCopy]);
9541
9542 NSURL *url([copy URL]);
9543 NSString *host([url host]);
9544 NSString *scheme([[url scheme] lowercaseString]);
9545
9546 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9547
9548 @synchronized (HostConfig_) {
9549 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9550 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9551 [copy setHTTPShouldUsePipelining:YES];
9552 }
9553
9554 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9555 } return self;
9556 }
9557
9558 int main(int argc, char *argv[]) {
9559 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9560
9561 _trace();
9562
9563 UpdateExternalStatus(0);
9564
9565 if (Class $UIDevice = objc_getClass("UIDevice")) {
9566 UIDevice *device([$UIDevice currentDevice]);
9567 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9568 } else
9569 IsWildcat_ = false;
9570
9571 UIScreen *screen([UIScreen mainScreen]);
9572 if ([screen respondsToSelector:@selector(scale)])
9573 ScreenScale_ = [screen scale];
9574 else
9575 ScreenScale_ = 1;
9576
9577 UIDevice *device([UIDevice currentDevice]);
9578 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9579 Idiom_ = @"iphone";
9580 else {
9581 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9582 if (idiom == UIUserInterfaceIdiomPhone)
9583 Idiom_ = @"iphone";
9584 else if (idiom == UIUserInterfaceIdiomPad)
9585 Idiom_ = @"ipad";
9586 else
9587 NSLog(@"unknown UIUserInterfaceIdiom!");
9588 }
9589
9590 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9591
9592 HostConfig_ = [[[NSObject alloc] init] autorelease];
9593 @synchronized (HostConfig_) {
9594 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9595 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9596 }
9597
9598 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9599
9600 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9601
9602 MobilizedFiles_ = [NSMutableSet setWithObjects:
9603 @"Library/Preferences/com.apple.Accessibility.plist",
9604 @"Library/Preferences/com.apple.preferences.sounds.plist",
9605 nil];
9606
9607 /* Library Hacks {{{ */
9608 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9609
9610 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9611
9612 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9613 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9614 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9615 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9616 }
9617
9618 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9619 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9620 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9621 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9622 }
9623
9624 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9625 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9626 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9627 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9628 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9629 }
9630
9631 $NSURLConnection = objc_getClass("NSURLConnection");
9632 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9633 if (NSURLConnection$init$ != NULL) {
9634 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9635 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9636 }
9637 /* }}} */
9638 /* Set Locale {{{ */
9639 Locale_ = CFLocaleCopyCurrent();
9640 Languages_ = [NSLocale preferredLanguages];
9641
9642 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9643 //NSLog(@"%@", [Languages_ description]);
9644
9645 const char *lang;
9646 if (Locale_ != NULL)
9647 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9648 else if (Languages_ != nil && [Languages_ count] != 0)
9649 lang = [[Languages_ objectAtIndex:0] UTF8String];
9650 else
9651 // XXX: consider just setting to C and then falling through?
9652 lang = NULL;
9653
9654 if (lang != NULL) {
9655 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9656 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9657 }
9658
9659 NSLog(@"Setting Language: %s", lang);
9660
9661 if (lang != NULL) {
9662 setenv("LANG", lang, true);
9663 std::setlocale(LC_ALL, lang);
9664 }
9665 /* }}} */
9666
9667 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9668
9669 /* Parse Arguments {{{ */
9670 bool substrate(false);
9671
9672 if (argc != 0) {
9673 char **args(argv);
9674 int arge(1);
9675
9676 for (int argi(1); argi != argc; ++argi)
9677 if (strcmp(argv[argi], "--") == 0) {
9678 arge = argi;
9679 argv[argi] = argv[0];
9680 argv += argi;
9681 argc -= argi;
9682 break;
9683 }
9684
9685 for (int argi(1); argi != arge; ++argi)
9686 if (strcmp(args[argi], "--substrate") == 0)
9687 substrate = true;
9688 else
9689 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9690 }
9691 /* }}} */
9692
9693 App_ = [[NSBundle mainBundle] bundlePath];
9694 Advanced_ = YES;
9695
9696 setuid(0);
9697 setgid(0);
9698
9699 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9700 alloc_ = alloc->method_imp;
9701 alloc->method_imp = (IMP) &Alloc_;*/
9702
9703 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9704 dealloc_ = dealloc->method_imp;
9705 dealloc->method_imp = (IMP) &Dealloc_;*/
9706
9707 /* System Information {{{ */
9708 size_t size;
9709
9710 int maxproc;
9711 size = sizeof(maxproc);
9712 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9713 perror("sysctlbyname(\"kern.maxproc\", ?)");
9714 else if (maxproc < 64) {
9715 maxproc = 64;
9716 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9717 perror("sysctlbyname(\"kern.maxproc\", #)");
9718 }
9719
9720 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9721 char *osversion = new char[size];
9722 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9723 perror("sysctlbyname(\"kern.osversion\", ?)");
9724 else
9725 System_ = [NSString stringWithUTF8String:osversion];
9726
9727 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9728 char *machine = new char[size];
9729 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9730 perror("sysctlbyname(\"hw.machine\", ?)");
9731 else
9732 Machine_ = machine;
9733
9734 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9735 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9736 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9737
9738 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9739
9740 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9741 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9742 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9743
9744 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9745 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9746 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9747
9748 if (mcc != NULL && mnc != NULL)
9749 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9750
9751 if (mnc != NULL)
9752 CFRelease(mnc);
9753 if (mcc != NULL)
9754 CFRelease(mcc);
9755
9756 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9757 Build_ = [system objectForKey:@"ProductBuildVersion"];
9758 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9759 Product_ = [info objectForKey:@"SafariProductVersion"];
9760 Safari_ = [info objectForKey:@"CFBundleVersion"];
9761 }
9762 /* }}} */
9763 /* Load Database {{{ */
9764 _trace();
9765 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9766 _trace();
9767 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9768
9769 if (Metadata_ == NULL)
9770 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9771 else {
9772 Settings_ = [Metadata_ objectForKey:@"Settings"];
9773
9774 Packages_ = [Metadata_ objectForKey:@"Packages"];
9775 Sections_ = [Metadata_ objectForKey:@"Sections"];
9776 Sources_ = [Metadata_ objectForKey:@"Sources"];
9777
9778 Token_ = [Metadata_ objectForKey:@"Token"];
9779 }
9780
9781 if (Settings_ != nil)
9782 Role_ = [Settings_ objectForKey:@"Role"];
9783
9784 if (Sections_ == nil) {
9785 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9786 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9787 }
9788
9789 if (Sources_ == nil) {
9790 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9791 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9792 }
9793 /* }}} */
9794
9795 _trace();
9796 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9797 _trace();
9798
9799 if (Packages_ != nil) {
9800 bool fail(false);
9801 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9802 _trace();
9803
9804 if (!fail) {
9805 [Metadata_ removeObjectForKey:@"Packages"];
9806 Packages_ = nil;
9807 Changed_ = true;
9808 }
9809 }
9810
9811 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9812
9813 #define MobileSubstrate_(name) \
9814 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9815 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9816 if (handle == NULL) \
9817 NSLog(@"%s", dlerror()); \
9818 }
9819
9820 MobileSubstrate_(Activator)
9821 MobileSubstrate_(libstatusbar)
9822 MobileSubstrate_(SimulatedKeyEvents)
9823 MobileSubstrate_(WinterBoard)
9824
9825 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9826 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9827
9828 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9829
9830 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9831 unlink("/tmp/.cydia.fw");
9832 goto firmware;
9833 } else if (access("/User", F_OK) != 0 || version < 4) {
9834 firmware:
9835 _trace();
9836 system("/usr/libexec/cydia/firmware.sh");
9837 _trace();
9838 }
9839
9840 _assert([[NSFileManager defaultManager]
9841 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9842 withIntermediateDirectories:YES
9843 attributes:nil
9844 error:NULL
9845 ]);
9846
9847 if (access("/tmp/cydia.chk", F_OK) == 0) {
9848 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9849 _assert(errno == ENOENT);
9850 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9851 _assert(errno == ENOENT);
9852 }
9853
9854 /* APT Initialization {{{ */
9855 _assert(pkgInitConfig(*_config));
9856 _assert(pkgInitSystem(*_config, _system));
9857
9858 if (lang != NULL)
9859 _config->Set("APT::Acquire::Translation", lang);
9860
9861 // XXX: this timeout might be important :(
9862 //_config->Set("Acquire::http::Timeout", 15);
9863
9864 _config->Set("Acquire::http::MaxParallel", 3);
9865 /* }}} */
9866 /* Color Choices {{{ */
9867 space_ = CGColorSpaceCreateDeviceRGB();
9868
9869 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9870 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9871 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9872 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9873 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9874 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9875 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9876 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9877 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9878
9879 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9880 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9881 /* }}}*/
9882 /* UIKit Configuration {{{ */
9883 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9884 if ($GSFontSetUseLegacyFontMetrics != NULL)
9885 $GSFontSetUseLegacyFontMetrics(YES);
9886
9887 // XXX: I have a feeling this was important
9888 //UIKeyboardDisableAutomaticAppearance();
9889 /* }}} */
9890
9891 Colon_ = UCLocalize("COLON_DELIMITED");
9892 Elision_ = UCLocalize("ELISION");
9893 Error_ = UCLocalize("ERROR");
9894 Warning_ = UCLocalize("WARNING");
9895
9896 _trace();
9897 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9898
9899 CGColorSpaceRelease(space_);
9900 CFRelease(Locale_);
9901
9902 [pool release];
9903 return value;
9904 }