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