]> git.saurik.com Git - cydia.git/blob - Cydia.mm
21f126419c3c4358c2df9cc3608c99303717b29f
[cydia.git] / Cydia.mm
1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2009 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 #import "UICaboodle/UCPlatform.h"
45 #import "UICaboodle/UCLocalize.h"
46
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
49
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <GraphicsServices/GraphicsServices.h>
52 #include <Foundation/Foundation.h>
53
54 #if 0
55 #define DEPLOYMENT_TARGET_MACOSX 1
56 #define CF_BUILDING_CF 1
57 #include <CoreFoundation/CFInternal.h>
58 #endif
59
60 #include <CoreFoundation/CFPriv.h>
61 #include <CoreFoundation/CFUniChar.h>
62
63 #import <UIKit/UIKit.h>
64
65 #include <WebCore/WebCoreThread.h>
66 #import <WebKit/WebDefaultUIKitDelegate.h>
67
68 #include <algorithm>
69 #include <iomanip>
70 #include <sstream>
71 #include <string>
72
73 #include <ext/stdio_filebuf.h>
74
75 #include <apt-pkg/acquire.h>
76 #include <apt-pkg/acquire-item.h>
77 #include <apt-pkg/algorithms.h>
78 #include <apt-pkg/cachefile.h>
79 #include <apt-pkg/clean.h>
80 #include <apt-pkg/configuration.h>
81 #include <apt-pkg/debindexfile.h>
82 #include <apt-pkg/debmetaindex.h>
83 #include <apt-pkg/error.h>
84 #include <apt-pkg/init.h>
85 #include <apt-pkg/mmap.h>
86 #include <apt-pkg/pkgrecords.h>
87 #include <apt-pkg/sha1.h>
88 #include <apt-pkg/sourcelist.h>
89 #include <apt-pkg/sptr.h>
90 #include <apt-pkg/strutl.h>
91 #include <apt-pkg/tagfile.h>
92
93 #include <apr-1/apr_pools.h>
94
95 #include <sys/types.h>
96 #include <sys/stat.h>
97 #include <sys/sysctl.h>
98 #include <sys/param.h>
99 #include <sys/mount.h>
100
101 #include <notify.h>
102 #include <dlfcn.h>
103
104 extern "C" {
105 #include <mach-o/nlist.h>
106 }
107
108 #include <cstdio>
109 #include <cstdlib>
110 #include <cstring>
111
112 #include <errno.h>
113 #include <pcre.h>
114
115 #include <ext/hash_map>
116
117 #import "UICaboodle/BrowserView.h"
118 #import "UICaboodle/ResetView.h"
119
120 #import "substrate.h"
121 /* }}} */
122
123 /* Profiler {{{ */
124 struct timeval _ltv;
125 bool _itv;
126
127 #define _timestamp ({ \
128 struct timeval tv; \
129 gettimeofday(&tv, NULL); \
130 tv.tv_sec * 1000000 + tv.tv_usec; \
131 })
132
133 typedef std::vector<class ProfileTime *> TimeList;
134 TimeList times_;
135
136 class ProfileTime {
137 private:
138 const char *name_;
139 uint64_t total_;
140 uint64_t count_;
141
142 public:
143 ProfileTime(const char *name) :
144 name_(name),
145 total_(0)
146 {
147 times_.push_back(this);
148 }
149
150 void AddTime(uint64_t time) {
151 total_ += time;
152 ++count_;
153 }
154
155 void Print() {
156 if (total_ != 0)
157 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
158 total_ = 0;
159 count_ = 0;
160 }
161 };
162
163 class ProfileTimer {
164 private:
165 ProfileTime &time_;
166 uint64_t start_;
167
168 public:
169 ProfileTimer(ProfileTime &time) :
170 time_(time),
171 start_(_timestamp)
172 {
173 }
174
175 ~ProfileTimer() {
176 time_.AddTime(_timestamp - start_);
177 }
178 };
179
180 void PrintTimes() {
181 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
182 (*i)->Print();
183 std::cerr << "========" << std::endl;
184 }
185
186 #define _profile(name) { \
187 static ProfileTime name(#name); \
188 ProfileTimer _ ## name(name);
189
190 #define _end }
191 /* }}} */
192 /* Objective-C Handle<> {{{ */
193 template <typename Type_>
194 class _H {
195 typedef _H<Type_> This_;
196
197 private:
198 Type_ *value_;
199
200 _finline void Retain_() {
201 if (value_ != nil)
202 [value_ retain];
203 }
204
205 _finline void Clear_() {
206 if (value_ != nil)
207 [value_ release];
208 }
209
210 public:
211 _finline _H(const This_ &rhs) :
212 value_(rhs.value_ == nil ? nil : [rhs.value_ retain])
213 {
214 }
215
216 _finline _H(Type_ *value = NULL, bool mended = false) :
217 value_(value)
218 {
219 if (!mended)
220 Retain_();
221 }
222
223 _finline ~_H() {
224 Clear_();
225 }
226
227 _finline operator Type_ *() const {
228 return value_;
229 }
230
231 _finline This_ &operator =(Type_ *value) {
232 if (value_ != value) {
233 Type_ *old(value_);
234 value_ = value;
235 Retain_();
236 if (old != nil)
237 [old release];
238 } return *this;
239 }
240 };
241 /* }}} */
242
243 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
244
245 void NSLogPoint(const char *fix, const CGPoint &point) {
246 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
247 }
248
249 void NSLogRect(const char *fix, const CGRect &rect) {
250 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
251 }
252
253 /* [NSObject yieldToSelector:(withObject:)] {{{*/
254 @interface NSObject (Cydia)
255 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
256 - (id) yieldToSelector:(SEL)selector;
257 @end
258
259 @implementation NSObject (Cydia)
260
261 - (void) doNothing {
262 }
263
264 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
265 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
266 id object([[context objectAtIndex:1] nonretainedObjectValue]);
267 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
268
269 /* XXX: deal with exceptions */
270 id value([self performSelector:selector withObject:object]);
271
272 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
273 [context removeAllObjects];
274 if ([signature methodReturnLength] != 0 && value != nil)
275 [context addObject:value];
276
277 stopped = true;
278
279 [self
280 performSelectorOnMainThread:@selector(doNothing)
281 withObject:nil
282 waitUntilDone:NO
283 ];
284 }
285
286 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
287 /*return [self performSelector:selector withObject:object];*/
288
289 volatile bool stopped(false);
290
291 NSMutableArray *context([NSMutableArray arrayWithObjects:
292 [NSValue valueWithPointer:selector],
293 [NSValue valueWithNonretainedObject:object],
294 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
295 nil]);
296
297 NSThread *thread([[[NSThread alloc]
298 initWithTarget:self
299 selector:@selector(_yieldToContext:)
300 object:context
301 ] autorelease]);
302
303 [thread start];
304
305 NSRunLoop *loop([NSRunLoop currentRunLoop]);
306 NSDate *future([NSDate distantFuture]);
307
308 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
309
310 return [context count] == 0 ? nil : [context objectAtIndex:0];
311 }
312
313 - (id) yieldToSelector:(SEL)selector {
314 return [self yieldToSelector:selector withObject:nil];
315 }
316
317 @end
318 /* }}} */
319
320 /* NSForcedOrderingSearch doesn't work on the iPhone */
321 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
322 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
323 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
324
325 /* Information Dictionaries {{{ */
326 @interface NSMutableArray (Cydia)
327 - (void) addInfoDictionary:(NSDictionary *)info;
328 @end
329
330 @implementation NSMutableArray (Cydia)
331
332 - (void) addInfoDictionary:(NSDictionary *)info {
333 [self addObject:info];
334 }
335
336 @end
337
338 @interface NSMutableDictionary (Cydia)
339 - (void) addInfoDictionary:(NSDictionary *)info;
340 @end
341
342 @implementation NSMutableDictionary (Cydia)
343
344 - (void) addInfoDictionary:(NSDictionary *)info {
345 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
346 }
347
348 @end
349 /* }}} */
350 /* Pop Transitions {{{ */
351 @interface PopTransitionView : UITransitionView {
352 }
353
354 @end
355
356 @implementation PopTransitionView
357
358 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
359 if (from != nil && to == nil)
360 [self removeFromSuperview];
361 }
362
363 @end
364
365 @implementation UIView (PopUpView)
366
367 - (void) popFromSuperviewAnimated:(BOOL)animated {
368 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
369 }
370
371 - (void) popSubview:(UIView *)view {
372 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
373 [transition setDelegate:transition];
374 [self addSubview:transition];
375
376 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
377 [transition transition:UITransitionNone toView:blank];
378 [transition transition:UITransitionPushFromBottom toView:view];
379 }
380
381 @end
382 /* }}} */
383
384 #define lprintf(args...) fprintf(stderr, args)
385
386 #define ForRelease 0
387 #define TraceLogging (1 && !ForRelease)
388 #define HistogramInsertionSort (0 && !ForRelease)
389 #define ProfileTimes (0 && !ForRelease)
390 #define ForSaurik (0 && !ForRelease)
391 #define LogBrowser (1 && !ForRelease)
392 #define TrackResize (0 && !ForRelease)
393 #define ManualRefresh (1 && !ForRelease)
394 #define ShowInternals (0 && !ForRelease)
395 #define IgnoreInstall (0 && !ForRelease)
396 #define RecycleWebViews 0
397 #define RecyclePackageViews 1
398 #define AlwaysReload (0 && !ForRelease)
399
400 #if !TraceLogging
401 #undef _trace
402 #define _trace(args...)
403 #endif
404
405 #if !ProfileTimes
406 #undef _profile
407 #define _profile(name) {
408 #undef _end
409 #define _end }
410 #define PrintTimes() do {} while (false)
411 #endif
412
413 /* Radix Sort {{{ */
414 typedef uint32_t (*SKRadixFunction)(id, void *);
415
416 @interface NSMutableArray (Radix)
417 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
418 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
419 @end
420
421 struct RadixItem_ {
422 size_t index;
423 uint32_t key;
424 };
425
426 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
427 struct RadixItem_ *lhs(swap), *rhs(swap + count);
428
429 static const size_t width = 32;
430 static const size_t bits = 11;
431 static const size_t slots = 1 << bits;
432 static const size_t passes = (width + (bits - 1)) / bits;
433
434 size_t *hist(new size_t[slots]);
435
436 for (size_t pass(0); pass != passes; ++pass) {
437 memset(hist, 0, sizeof(size_t) * slots);
438
439 for (size_t i(0); i != count; ++i) {
440 uint32_t key(lhs[i].key);
441 key >>= pass * bits;
442 key &= _not(uint32_t) >> width - bits;
443 ++hist[key];
444 }
445
446 size_t offset(0);
447 for (size_t i(0); i != slots; ++i) {
448 size_t local(offset);
449 offset += hist[i];
450 hist[i] = local;
451 }
452
453 for (size_t i(0); i != count; ++i) {
454 uint32_t key(lhs[i].key);
455 key >>= pass * bits;
456 key &= _not(uint32_t) >> width - bits;
457 rhs[hist[key]++] = lhs[i];
458 }
459
460 RadixItem_ *tmp(lhs);
461 lhs = rhs;
462 rhs = tmp;
463 }
464
465 delete [] hist;
466
467 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
468 for (size_t i(0); i != count; ++i)
469 [values addObject:[self objectAtIndex:lhs[i].index]];
470 [self setArray:values];
471
472 delete [] swap;
473 }
474
475 @implementation NSMutableArray (Radix)
476
477 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
478 size_t count([self count]);
479 if (count == 0)
480 return;
481
482 #if 0
483 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
484 [invocation setSelector:selector];
485 [invocation setArgument:&object atIndex:2];
486 #else
487 /* XXX: this is an unsafe optimization of doomy hell */
488 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
489 _assert(method != NULL);
490 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
491 _assert(imp != NULL);
492 #endif
493
494 struct RadixItem_ *swap(new RadixItem_[count * 2]);
495
496 for (size_t i(0); i != count; ++i) {
497 RadixItem_ &item(swap[i]);
498 item.index = i;
499
500 id object([self objectAtIndex:i]);
501
502 #if 0
503 [invocation setTarget:object];
504 [invocation invoke];
505 [invocation getReturnValue:&item.key];
506 #else
507 item.key = imp(object, selector, object);
508 #endif
509 }
510
511 RadixSort_(self, count, swap);
512 }
513
514 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
515 size_t count([self count]);
516 struct RadixItem_ *swap(new RadixItem_[count * 2]);
517
518 for (size_t i(0); i != count; ++i) {
519 RadixItem_ &item(swap[i]);
520 item.index = i;
521
522 id object([self objectAtIndex:i]);
523 item.key = function(object, argument);
524 }
525
526 RadixSort_(self, count, swap);
527 }
528
529 @end
530 /* }}} */
531 /* Insertion Sort {{{ */
532
533 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
534 const char *ptr = (const char *)list;
535 while (0 < count) {
536 CFIndex half = count / 2;
537 const char *probe = ptr + elementSize * half;
538 CFComparisonResult cr = comparator(element, probe, context);
539 if (0 == cr) return (probe - (const char *)list) / elementSize;
540 ptr = (cr < 0) ? ptr : probe + elementSize;
541 count = (cr < 0) ? half : (half + (count & 1) - 1);
542 }
543 return (ptr - (const char *)list) / elementSize;
544 }
545
546 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
547 const char *ptr = (const char *)list;
548 while (0 < count) {
549 CFIndex half = count / 2;
550 const char *probe = ptr + elementSize * half;
551 CFComparisonResult cr = comparator(element, probe, context);
552 if (0 == cr) return (probe - (const char *)list) / elementSize;
553 ptr = (cr < 0) ? ptr : probe + elementSize;
554 count = (cr < 0) ? half : (half + (count & 1) - 1);
555 }
556 return (ptr - (const char *)list) / elementSize;
557 }
558
559 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
560 if (range.length == 0)
561 return;
562 const void **values(new const void *[range.length]);
563 CFArrayGetValues(array, range, values);
564
565 #if HistogramInsertionSort
566 uint32_t total(0), *offsets(new uint32_t[range.length]);
567 #endif
568
569 for (CFIndex index(1); index != range.length; ++index) {
570 const void *value(values[index]);
571 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
572 CFIndex correct(index);
573 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
574 if (--correct == 0)
575 break;
576 if (correct != index) {
577 size_t offset(index - correct);
578 #if HistogramInsertionSort
579 total += offset;
580 ++offsets[offset];
581 if (offset > 10)
582 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
583 #endif
584 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
585 values[correct] = value;
586 }
587 }
588
589 CFArrayReplaceValues(array, range, values, range.length);
590 delete [] values;
591
592 #if HistogramInsertionSort
593 for (CFIndex index(0); index != range.length; ++index)
594 if (offsets[index] != 0)
595 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
596 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
597 delete [] offsets;
598 #endif
599 }
600
601 /* }}} */
602
603 /* Apple Bug Fixes {{{ */
604 @implementation UIWebDocumentView (Cydia)
605
606 - (void) _setScrollerOffset:(CGPoint)offset {
607 UIScroller *scroller([self _scroller]);
608
609 CGSize size([scroller contentSize]);
610 CGSize bounds([scroller bounds].size);
611
612 CGPoint max;
613 max.x = size.width - bounds.width;
614 max.y = size.height - bounds.height;
615
616 // wtf Apple?!
617 if (max.x < 0)
618 max.x = 0;
619 if (max.y < 0)
620 max.y = 0;
621
622 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
623 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
624
625 [scroller setOffset:offset];
626 }
627
628 @end
629 /* }}} */
630
631 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
632 size_t length([self length] - state->state);
633 if (length <= 0)
634 return 0;
635 else if (length > count)
636 length = count;
637 for (size_t i(0); i != length; ++i)
638 objects[i] = [self item:state->state++];
639 state->itemsPtr = objects;
640 state->mutationsPtr = (unsigned long *) self;
641 return length;
642 }
643
644 @interface NSString (UIKit)
645 - (NSString *) stringByAddingPercentEscapes;
646 @end
647
648 /* Cydia NSString Additions {{{ */
649 @interface NSString (Cydia)
650 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
651 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
652 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
653 - (NSComparisonResult) compareByPath:(NSString *)other;
654 - (NSString *) stringByCachingURLWithCurrentCDN;
655 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
656 @end
657
658 @implementation NSString (Cydia)
659
660 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
661 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
662 }
663
664 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
665 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
666 memcpy(data, bytes, length);
667 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
668 }
669
670 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
671 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
672 }
673
674 - (NSComparisonResult) compareByPath:(NSString *)other {
675 NSString *prefix = [self commonPrefixWithString:other options:0];
676 size_t length = [prefix length];
677
678 NSRange lrange = NSMakeRange(length, [self length] - length);
679 NSRange rrange = NSMakeRange(length, [other length] - length);
680
681 lrange = [self rangeOfString:@"/" options:0 range:lrange];
682 rrange = [other rangeOfString:@"/" options:0 range:rrange];
683
684 NSComparisonResult value;
685
686 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
687 value = NSOrderedSame;
688 else if (lrange.location == NSNotFound)
689 value = NSOrderedAscending;
690 else if (rrange.location == NSNotFound)
691 value = NSOrderedDescending;
692 else
693 value = NSOrderedSame;
694
695 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
696 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
697 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
698 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
699
700 NSComparisonResult result = [lpath compare:rpath];
701 return result == NSOrderedSame ? value : result;
702 }
703
704 - (NSString *) stringByCachingURLWithCurrentCDN {
705 return [self
706 stringByReplacingOccurrencesOfString:@"://"
707 withString:@"://ne.edgecastcdn.net/8003A4/"
708 options:0
709 /* XXX: this is somewhat inaccurate */
710 range:NSMakeRange(0, 10)
711 ];
712 }
713
714 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
715 return [(id)CFURLCreateStringByAddingPercentEscapes(
716 kCFAllocatorDefault,
717 (CFStringRef) self,
718 NULL,
719 CFSTR(";/?:@&=+$,"),
720 kCFStringEncodingUTF8
721 ) autorelease];
722 }
723
724 @end
725 /* }}} */
726
727 /* C++ NSString Wrapper Cache {{{ */
728 class CYString {
729 private:
730 char *data_;
731 size_t size_;
732 CFStringRef cache_;
733
734 _finline void clear_() {
735 if (cache_ != NULL) {
736 CFRelease(cache_);
737 cache_ = NULL;
738 }
739 }
740
741 public:
742 _finline bool empty() const {
743 return size_ == 0;
744 }
745
746 _finline size_t size() const {
747 return size_;
748 }
749
750 _finline char *data() const {
751 return data_;
752 }
753
754 _finline void clear() {
755 size_ = 0;
756 clear_();
757 }
758
759 _finline CYString() :
760 data_(0),
761 size_(0),
762 cache_(NULL)
763 {
764 }
765
766 _finline ~CYString() {
767 clear_();
768 }
769
770 void operator =(const CYString &rhs) {
771 data_ = rhs.data_;
772 size_ = rhs.size_;
773
774 if (rhs.cache_ == nil)
775 cache_ = NULL;
776 else
777 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
778 }
779
780 void set(apr_pool_t *pool, const char *data, size_t size) {
781 if (size == 0)
782 clear();
783 else {
784 clear_();
785
786 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
787 memcpy(temp, data, size);
788 temp[size] = '\0';
789 data_ = temp;
790 size_ = size;
791 }
792 }
793
794 _finline void set(apr_pool_t *pool, const char *data) {
795 set(pool, data, data == NULL ? 0 : strlen(data));
796 }
797
798 _finline void set(apr_pool_t *pool, const std::string &rhs) {
799 set(pool, rhs.data(), rhs.size());
800 }
801
802 bool operator ==(const CYString &rhs) const {
803 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
804 }
805
806 operator CFStringRef() {
807 if (cache_ == NULL) {
808 if (size_ == 0)
809 return nil;
810 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
811 } return cache_;
812 }
813
814 _finline operator id() {
815 return (NSString *) static_cast<CFStringRef>(*this);
816 }
817 };
818 /* }}} */
819 /* C++ NSString Algorithm Adapters {{{ */
820 extern "C" {
821 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
822 }
823
824 struct NSStringMapHash :
825 std::unary_function<NSString *, size_t>
826 {
827 _finline size_t operator ()(NSString *value) const {
828 return CFStringHashNSString((CFStringRef) value);
829 }
830 };
831
832 struct NSStringMapLess :
833 std::binary_function<NSString *, NSString *, bool>
834 {
835 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
836 return [lhs compare:rhs] == NSOrderedAscending;
837 }
838 };
839
840 struct NSStringMapEqual :
841 std::binary_function<NSString *, NSString *, bool>
842 {
843 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
844 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
845 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
846 //[lhs isEqualToString:rhs];
847 }
848 };
849 /* }}} */
850
851 /* Perl-Compatible RegEx {{{ */
852 class Pcre {
853 private:
854 pcre *code_;
855 pcre_extra *study_;
856 int capture_;
857 int *matches_;
858 const char *data_;
859
860 public:
861 Pcre(const char *regex) :
862 study_(NULL)
863 {
864 const char *error;
865 int offset;
866 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
867
868 if (code_ == NULL) {
869 lprintf("%d:%s\n", offset, error);
870 _assert(false);
871 }
872
873 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
874 matches_ = new int[(capture_ + 1) * 3];
875 }
876
877 ~Pcre() {
878 pcre_free(code_);
879 delete matches_;
880 }
881
882 NSString *operator [](size_t match) {
883 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
884 }
885
886 bool operator ()(NSString *data) {
887 // XXX: length is for characters, not for bytes
888 return operator ()([data UTF8String], [data length]);
889 }
890
891 bool operator ()(const char *data, size_t size) {
892 data_ = data;
893 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
894 }
895 };
896 /* }}} */
897 /* Mime Addresses {{{ */
898 @interface Address : NSObject {
899 NSString *name_;
900 NSString *address_;
901 }
902
903 - (NSString *) name;
904 - (NSString *) address;
905
906 - (void) setAddress:(NSString *)address;
907
908 + (Address *) addressWithString:(NSString *)string;
909 - (Address *) initWithString:(NSString *)string;
910 @end
911
912 @implementation Address
913
914 - (void) dealloc {
915 [name_ release];
916 if (address_ != nil)
917 [address_ release];
918 [super dealloc];
919 }
920
921 - (NSString *) name {
922 return name_;
923 }
924
925 - (NSString *) address {
926 return address_;
927 }
928
929 - (void) setAddress:(NSString *)address {
930 if (address_ != nil)
931 [address_ autorelease];
932 if (address == nil)
933 address_ = nil;
934 else
935 address_ = [address retain];
936 }
937
938 + (Address *) addressWithString:(NSString *)string {
939 return [[[Address alloc] initWithString:string] autorelease];
940 }
941
942 + (NSArray *) _attributeKeys {
943 return [NSArray arrayWithObjects:@"address", @"name", nil];
944 }
945
946 - (NSArray *) attributeKeys {
947 return [[self class] _attributeKeys];
948 }
949
950 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
951 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
952 }
953
954 - (Address *) initWithString:(NSString *)string {
955 if ((self = [super init]) != nil) {
956 const char *data = [string UTF8String];
957 size_t size = [string length];
958
959 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
960
961 if (address_r(data, size)) {
962 name_ = [address_r[1] retain];
963 address_ = [address_r[2] retain];
964 } else {
965 name_ = [string retain];
966 address_ = nil;
967 }
968 } return self;
969 }
970
971 @end
972 /* }}} */
973 /* CoreGraphics Primitives {{{ */
974 class CGColor {
975 private:
976 CGColorRef color_;
977
978 public:
979 CGColor() :
980 color_(NULL)
981 {
982 }
983
984 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
985 color_(NULL)
986 {
987 Set(space, red, green, blue, alpha);
988 }
989
990 void Clear() {
991 if (color_ != NULL)
992 CGColorRelease(color_);
993 }
994
995 ~CGColor() {
996 Clear();
997 }
998
999 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1000 Clear();
1001 float color[] = {red, green, blue, alpha};
1002 color_ = CGColorCreate(space, color);
1003 }
1004
1005 operator CGColorRef() {
1006 return color_;
1007 }
1008 };
1009 /* }}} */
1010
1011 /* Random Global Variables {{{ */
1012 static const int PulseInterval_ = 50000;
1013 static const int ButtonBarHeight_ = 48;
1014 static const float KeyboardTime_ = 0.3f;
1015
1016 static int Finish_;
1017 static NSArray *Finishes_;
1018
1019 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1020 #define NotifyConfig_ "/etc/notify.conf"
1021
1022 static bool Queuing_;
1023
1024 static CGColor Blue_;
1025 static CGColor Blueish_;
1026 static CGColor Black_;
1027 static CGColor Off_;
1028 static CGColor White_;
1029 static CGColor Gray_;
1030 static CGColor Green_;
1031 static CGColor Purple_;
1032 static CGColor Purplish_;
1033
1034 static UIColor *InstallingColor_;
1035 static UIColor *RemovingColor_;
1036
1037 static NSString *App_;
1038 static NSString *Home_;
1039
1040 static BOOL Advanced_;
1041 static BOOL Loaded_;
1042 static BOOL Ignored_;
1043
1044 static UIFont *Font12_;
1045 static UIFont *Font12Bold_;
1046 static UIFont *Font14_;
1047 static UIFont *Font18Bold_;
1048 static UIFont *Font22Bold_;
1049
1050 static const char *Machine_ = NULL;
1051 static const NSString *System_ = NULL;
1052 static const NSString *SerialNumber_ = nil;
1053 static const NSString *ChipID_ = nil;
1054 static const NSString *UniqueID_ = nil;
1055 static const NSString *Build_ = nil;
1056 static const NSString *Product_ = nil;
1057 static const NSString *Safari_ = nil;
1058
1059 static CFLocaleRef Locale_;
1060 static NSArray *Languages_;
1061 static CGColorSpaceRef space_;
1062
1063 static bool reload_;
1064
1065 static NSDictionary *SectionMap_;
1066 static NSMutableDictionary *Metadata_;
1067 static _transient NSMutableDictionary *Settings_;
1068 static _transient NSString *Role_;
1069 static _transient NSMutableDictionary *Packages_;
1070 static _transient NSMutableDictionary *Sections_;
1071 static _transient NSMutableDictionary *Sources_;
1072 static bool Changed_;
1073 static NSDate *now_;
1074
1075 #if RecycleWebViews
1076 static NSMutableArray *Documents_;
1077 #endif
1078 /* }}} */
1079
1080 /* Display Helpers {{{ */
1081 inline float Interpolate(float begin, float end, float fraction) {
1082 return (end - begin) * fraction + begin;
1083 }
1084
1085 /* XXX: localize this! */
1086 NSString *SizeString(double size) {
1087 bool negative = size < 0;
1088 if (negative)
1089 size = -size;
1090
1091 unsigned power = 0;
1092 while (size > 1024) {
1093 size /= 1024;
1094 ++power;
1095 }
1096
1097 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1098
1099 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1100 }
1101
1102 static _finline CFStringRef CFCString(const char *value) {
1103 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1104 }
1105
1106 const char *StripVersion_(const char *version) {
1107 const char *colon(strchr(version, ':'));
1108 if (colon != NULL)
1109 version = colon + 1;
1110 return version;
1111 }
1112
1113 CFStringRef StripVersion(const char *version) {
1114 const char *colon(strchr(version, ':'));
1115 if (colon != NULL)
1116 version = colon + 1;
1117 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1118 // XXX: performance
1119 return CFCString(version);
1120 }
1121
1122 NSString *LocalizeSection(NSString *section) {
1123 static Pcre title_r("^(.*?) \\((.*)\\)$");
1124 if (title_r(section)) {
1125 NSString *parent(title_r[1]);
1126 NSString *child(title_r[2]);
1127
1128 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1129 LocalizeSection(parent),
1130 LocalizeSection(child)
1131 ];
1132 }
1133
1134 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1135 }
1136
1137 NSString *Simplify(NSString *title) {
1138 const char *data = [title UTF8String];
1139 size_t size = [title length];
1140
1141 static Pcre square_r("^\\[(.*)\\]$");
1142 if (square_r(data, size))
1143 return Simplify(square_r[1]);
1144
1145 static Pcre paren_r("^\\((.*)\\)$");
1146 if (paren_r(data, size))
1147 return Simplify(paren_r[1]);
1148
1149 static Pcre title_r("^(.*?) \\((.*)\\)$");
1150 if (title_r(data, size))
1151 return Simplify(title_r[1]);
1152
1153 return title;
1154 }
1155 /* }}} */
1156
1157 NSString *GetLastUpdate() {
1158 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1159
1160 if (update == nil)
1161 return UCLocalize("NEVER_OR_UNKNOWN");
1162
1163 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1164 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1165
1166 CFRelease(formatter);
1167
1168 return [(NSString *) formatted autorelease];
1169 }
1170
1171 bool isSectionVisible(NSString *section) {
1172 NSDictionary *metadata([Sections_ objectForKey:section]);
1173 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1174 return hidden == nil || ![hidden boolValue];
1175 }
1176
1177 /* Delegate Prototypes {{{ */
1178 @class Package;
1179 @class Source;
1180
1181 @interface NSObject (ProgressDelegate)
1182 @end
1183
1184 @implementation NSObject(ProgressDelegate)
1185
1186 - (void) _setProgressError:(NSArray *)args {
1187 [self performSelector:@selector(setProgressError:forPackage:)
1188 withObject:[args objectAtIndex:0]
1189 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1190 ];
1191 }
1192
1193 @end
1194
1195 @protocol ProgressDelegate
1196 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1197 - (void) setProgressTitle:(NSString *)title;
1198 - (void) setProgressPercent:(float)percent;
1199 - (void) startProgress;
1200 - (void) addProgressOutput:(NSString *)output;
1201 - (bool) isCancelling:(size_t)received;
1202 @end
1203
1204 @protocol ConfigurationDelegate
1205 - (void) repairWithSelector:(SEL)selector;
1206 - (void) setConfigurationData:(NSString *)data;
1207 @end
1208
1209 @class PackageView;
1210
1211 @protocol CydiaDelegate
1212 - (void) setPackageView:(PackageView *)view;
1213 - (void) clearPackage:(Package *)package;
1214 - (void) installPackage:(Package *)package;
1215 - (void) removePackage:(Package *)package;
1216 - (void) slideUp:(UIActionSheet *)alert;
1217 - (void) distUpgrade;
1218 - (void) updateData;
1219 - (void) syncData;
1220 - (void) askForSettings;
1221 - (UIProgressHUD *) addProgressHUD;
1222 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1223 - (RVPage *) pageForPackage:(NSString *)name;
1224 - (PackageView *) packageView;
1225 @end
1226 /* }}} */
1227
1228 /* Status Delegation {{{ */
1229 class Status :
1230 public pkgAcquireStatus
1231 {
1232 private:
1233 _transient NSObject<ProgressDelegate> *delegate_;
1234
1235 public:
1236 Status() :
1237 delegate_(nil)
1238 {
1239 }
1240
1241 void setDelegate(id delegate) {
1242 delegate_ = delegate;
1243 }
1244
1245 virtual bool MediaChange(std::string media, std::string drive) {
1246 return false;
1247 }
1248
1249 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1250 }
1251
1252 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1253 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1254 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1255 }
1256
1257 virtual void Done(pkgAcquire::ItemDesc &item) {
1258 }
1259
1260 virtual void Fail(pkgAcquire::ItemDesc &item) {
1261 if (
1262 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1263 item.Owner->Status == pkgAcquire::Item::StatDone
1264 )
1265 return;
1266
1267 std::string &error(item.Owner->ErrorText);
1268 if (error.empty())
1269 return;
1270
1271 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1272 NSArray *fields([description componentsSeparatedByString:@" "]);
1273 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1274
1275 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1276 withObject:[NSArray arrayWithObjects:
1277 [NSString stringWithUTF8String:error.c_str()],
1278 source,
1279 nil]
1280 waitUntilDone:YES
1281 ];
1282 }
1283
1284 virtual bool Pulse(pkgAcquire *Owner) {
1285 bool value = pkgAcquireStatus::Pulse(Owner);
1286
1287 float percent(
1288 double(CurrentBytes + CurrentItems) /
1289 double(TotalBytes + TotalItems)
1290 );
1291
1292 [delegate_ setProgressPercent:percent];
1293 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1294 }
1295
1296 virtual void Start() {
1297 [delegate_ startProgress];
1298 }
1299
1300 virtual void Stop() {
1301 }
1302 };
1303 /* }}} */
1304 /* Progress Delegation {{{ */
1305 class Progress :
1306 public OpProgress
1307 {
1308 private:
1309 _transient id<ProgressDelegate> delegate_;
1310 float percent_;
1311
1312 protected:
1313 virtual void Update() {
1314 if (abs(Percent - percent_) > 2) {
1315 NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1316 percent_ = Percent;
1317 }
1318
1319 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1320 [delegate_ setProgressPercent:(Percent / 100)];*/
1321 }
1322
1323 public:
1324 Progress() :
1325 delegate_(nil),
1326 percent_(0)
1327 {
1328 }
1329
1330 void setDelegate(id delegate) {
1331 delegate_ = delegate;
1332 }
1333
1334 virtual void Done() {
1335 NSLog(@"DONE");
1336 //[delegate_ setProgressPercent:1];
1337 }
1338 };
1339 /* }}} */
1340
1341 /* Database Interface {{{ */
1342 typedef std::map< unsigned long, _H<Source> > SourceMap;
1343
1344 @interface Database : NSObject {
1345 NSZone *zone_;
1346 apr_pool_t *pool_;
1347
1348 unsigned era_;
1349
1350 pkgCacheFile cache_;
1351 pkgDepCache::Policy *policy_;
1352 pkgRecords *records_;
1353 pkgProblemResolver *resolver_;
1354 pkgAcquire *fetcher_;
1355 FileFd *lock_;
1356 SPtr<pkgPackageManager> manager_;
1357 pkgSourceList *list_;
1358
1359 SourceMap sources_;
1360 NSMutableArray *packages_;
1361
1362 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1363 Status status_;
1364 Progress progress_;
1365
1366 int cydiafd_;
1367 int statusfd_;
1368 FILE *input_;
1369 }
1370
1371 + (Database *) sharedInstance;
1372 - (unsigned) era;
1373
1374 - (void) _readCydia:(NSNumber *)fd;
1375 - (void) _readStatus:(NSNumber *)fd;
1376 - (void) _readOutput:(NSNumber *)fd;
1377
1378 - (FILE *) input;
1379
1380 - (Package *) packageWithName:(NSString *)name;
1381
1382 - (pkgCacheFile &) cache;
1383 - (pkgDepCache::Policy *) policy;
1384 - (pkgRecords *) records;
1385 - (pkgProblemResolver *) resolver;
1386 - (pkgAcquire &) fetcher;
1387 - (pkgSourceList &) list;
1388 - (NSArray *) packages;
1389 - (NSArray *) sources;
1390 - (void) reloadData;
1391
1392 - (void) configure;
1393 - (void) prepare;
1394 - (void) perform;
1395 - (void) upgrade;
1396 - (void) update;
1397
1398 - (void) setVisible;
1399
1400 - (NSString *) updateWithStatus:(Status &)status;
1401
1402 - (void) setDelegate:(id)delegate;
1403 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1404 @end
1405 /* }}} */
1406
1407 /* Source Class {{{ */
1408 @interface Source : NSObject {
1409 CYString depiction_;
1410 CYString description_;
1411 CYString label_;
1412 CYString origin_;
1413 CYString support_;
1414
1415 CYString uri_;
1416 CYString distribution_;
1417 CYString type_;
1418 CYString version_;
1419
1420 NSString *host_;
1421 NSString *authority_;
1422
1423 CYString defaultIcon_;
1424
1425 NSDictionary *record_;
1426 BOOL trusted_;
1427 }
1428
1429 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1430
1431 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1432
1433 - (NSString *) depictionForPackage:(NSString *)package;
1434 - (NSString *) supportForPackage:(NSString *)package;
1435
1436 - (NSDictionary *) record;
1437 - (BOOL) trusted;
1438
1439 - (NSString *) uri;
1440 - (NSString *) distribution;
1441 - (NSString *) type;
1442 - (NSString *) key;
1443 - (NSString *) host;
1444
1445 - (NSString *) name;
1446 - (NSString *) description;
1447 - (NSString *) label;
1448 - (NSString *) origin;
1449 - (NSString *) version;
1450
1451 - (NSString *) defaultIcon;
1452
1453 @end
1454
1455 @implementation Source
1456
1457 - (void) _clear {
1458 uri_.clear();
1459 distribution_.clear();
1460 type_.clear();
1461
1462 description_.clear();
1463 label_.clear();
1464 origin_.clear();
1465 depiction_.clear();
1466 support_.clear();
1467 version_.clear();
1468 defaultIcon_.clear();
1469
1470 if (record_ != nil) {
1471 [record_ release];
1472 record_ = nil;
1473 }
1474
1475 if (host_ != nil) {
1476 [host_ release];
1477 host_ = nil;
1478 }
1479
1480 if (authority_ != nil) {
1481 [authority_ release];
1482 authority_ = nil;
1483 }
1484 }
1485
1486 - (void) dealloc {
1487 [self _clear];
1488 [super dealloc];
1489 }
1490
1491 + (NSArray *) _attributeKeys {
1492 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1493 }
1494
1495 - (NSArray *) attributeKeys {
1496 return [[self class] _attributeKeys];
1497 }
1498
1499 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1500 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1501 }
1502
1503 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1504 [self _clear];
1505
1506 trusted_ = index->IsTrusted();
1507
1508 uri_.set(pool, index->GetURI());
1509 distribution_.set(pool, index->GetDist());
1510 type_.set(pool, index->GetType());
1511
1512 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1513 if (dindex != NULL) {
1514 FileFd fd;
1515 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1516 _error->Discard();
1517 else {
1518 pkgTagFile tags(&fd);
1519
1520 pkgTagSection section;
1521 tags.Step(section);
1522
1523 struct {
1524 const char *name_;
1525 CYString *value_;
1526 } names[] = {
1527 {"default-icon", &defaultIcon_},
1528 {"depiction", &depiction_},
1529 {"description", &description_},
1530 {"label", &label_},
1531 {"origin", &origin_},
1532 {"support", &support_},
1533 {"version", &version_},
1534 };
1535
1536 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1537 const char *start, *end;
1538
1539 if (section.Find(names[i].name_, start, end)) {
1540 CYString &value(*names[i].value_);
1541 value.set(pool, start, end - start);
1542 }
1543 }
1544 }
1545 }
1546
1547 record_ = [Sources_ objectForKey:[self key]];
1548 if (record_ != nil)
1549 record_ = [record_ retain];
1550
1551 NSURL *url([NSURL URLWithString:uri_]);
1552
1553 host_ = [url host];
1554 if (host_ != nil)
1555 host_ = [[host_ lowercaseString] retain];
1556
1557 if (host_ != nil)
1558 authority_ = [host_ retain];
1559 else
1560 authority_ = [url path];
1561 }
1562
1563 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1564 if ((self = [super init]) != nil) {
1565 [self setMetaIndex:index inPool:pool];
1566 } return self;
1567 }
1568
1569 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1570 NSDictionary *lhr = [self record];
1571 NSDictionary *rhr = [source record];
1572
1573 if (lhr != rhr)
1574 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1575
1576 NSString *lhs = [self name];
1577 NSString *rhs = [source name];
1578
1579 if ([lhs length] != 0 && [rhs length] != 0) {
1580 unichar lhc = [lhs characterAtIndex:0];
1581 unichar rhc = [rhs characterAtIndex:0];
1582
1583 if (isalpha(lhc) && !isalpha(rhc))
1584 return NSOrderedAscending;
1585 else if (!isalpha(lhc) && isalpha(rhc))
1586 return NSOrderedDescending;
1587 }
1588
1589 return [lhs compare:rhs options:LaxCompareOptions_];
1590 }
1591
1592 - (NSString *) depictionForPackage:(NSString *)package {
1593 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1594 }
1595
1596 - (NSString *) supportForPackage:(NSString *)package {
1597 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1598 }
1599
1600 - (NSDictionary *) record {
1601 return record_;
1602 }
1603
1604 - (BOOL) trusted {
1605 return trusted_;
1606 }
1607
1608 - (NSString *) uri {
1609 return uri_;
1610 }
1611
1612 - (NSString *) distribution {
1613 return distribution_;
1614 }
1615
1616 - (NSString *) type {
1617 return type_;
1618 }
1619
1620 - (NSString *) key {
1621 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1622 }
1623
1624 - (NSString *) host {
1625 return host_;
1626 }
1627
1628 - (NSString *) name {
1629 return origin_.empty() ? authority_ : origin_;
1630 }
1631
1632 - (NSString *) description {
1633 return description_;
1634 }
1635
1636 - (NSString *) label {
1637 return label_.empty() ? authority_ : label_;
1638 }
1639
1640 - (NSString *) origin {
1641 return origin_;
1642 }
1643
1644 - (NSString *) version {
1645 return version_;
1646 }
1647
1648 - (NSString *) defaultIcon {
1649 return defaultIcon_;
1650 }
1651
1652 @end
1653 /* }}} */
1654 /* Relationship Class {{{ */
1655 @interface Relationship : NSObject {
1656 NSString *type_;
1657 NSString *id_;
1658 }
1659
1660 - (NSString *) type;
1661 - (NSString *) id;
1662 - (NSString *) name;
1663
1664 @end
1665
1666 @implementation Relationship
1667
1668 - (void) dealloc {
1669 [type_ release];
1670 [id_ release];
1671 [super dealloc];
1672 }
1673
1674 - (NSString *) type {
1675 return type_;
1676 }
1677
1678 - (NSString *) id {
1679 return id_;
1680 }
1681
1682 - (NSString *) name {
1683 _assert(false);
1684 return nil;
1685 }
1686
1687 @end
1688 /* }}} */
1689 /* Package Class {{{ */
1690 @interface Package : NSObject {
1691 unsigned era_;
1692 apr_pool_t *pool_;
1693
1694 pkgCache::VerIterator version_;
1695 pkgCache::PkgIterator iterator_;
1696 _transient Database *database_;
1697 pkgCache::VerFileIterator file_;
1698
1699 Source *source_;
1700 bool cached_;
1701 bool parsed_;
1702
1703 CYString section_;
1704 NSString *section$_;
1705 bool essential_;
1706 bool required_;
1707 bool visible_;
1708
1709 NSString *latest_;
1710 CYString installed_;
1711
1712 CYString id_;
1713 CYString name_;
1714 CYString tagline_;
1715 CYString icon_;
1716 CYString depiction_;
1717 CYString homepage_;
1718
1719 CYString sponsor_;
1720 Address *sponsor$_;
1721
1722 CYString author_;
1723 Address *author$_;
1724
1725 CYString bugs_;
1726 CYString support_;
1727 NSMutableArray *tags_;
1728 NSString *role_;
1729
1730 NSArray *relationships_;
1731
1732 NSMutableDictionary *metadata_;
1733 _transient NSDate *firstSeen_;
1734 _transient NSDate *lastSeen_;
1735 bool subscribed_;
1736 }
1737
1738 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1739 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1740
1741 - (pkgCache::PkgIterator) iterator;
1742 - (void) parse;
1743
1744 - (NSString *) section;
1745 - (NSString *) simpleSection;
1746
1747 - (NSString *) longSection;
1748 - (NSString *) shortSection;
1749
1750 - (NSString *) uri;
1751
1752 - (Address *) maintainer;
1753 - (size_t) size;
1754 - (NSString *) longDescription;
1755 - (NSString *) shortDescription;
1756 - (unichar) index;
1757
1758 - (NSMutableDictionary *) metadata;
1759 - (NSDate *) seen;
1760 - (BOOL) subscribed;
1761 - (BOOL) ignored;
1762
1763 - (NSString *) latest;
1764 - (NSString *) installed;
1765 - (BOOL) uninstalled;
1766
1767 - (BOOL) valid;
1768 - (BOOL) upgradableAndEssential:(BOOL)essential;
1769 - (BOOL) essential;
1770 - (BOOL) broken;
1771 - (BOOL) unfiltered;
1772 - (BOOL) visible;
1773
1774 - (BOOL) half;
1775 - (BOOL) halfConfigured;
1776 - (BOOL) halfInstalled;
1777 - (BOOL) hasMode;
1778 - (NSString *) mode;
1779
1780 - (void) setVisible;
1781
1782 - (NSString *) id;
1783 - (NSString *) name;
1784 - (UIImage *) icon;
1785 - (NSString *) homepage;
1786 - (NSString *) depiction;
1787 - (Address *) author;
1788
1789 - (NSString *) support;
1790
1791 - (NSArray *) files;
1792 - (NSArray *) relationships;
1793 - (NSArray *) warnings;
1794 - (NSArray *) applications;
1795
1796 - (Source *) source;
1797 - (NSString *) role;
1798
1799 - (BOOL) matches:(NSString *)text;
1800
1801 - (bool) hasSupportingRole;
1802 - (BOOL) hasTag:(NSString *)tag;
1803 - (NSString *) primaryPurpose;
1804 - (NSArray *) purposes;
1805 - (bool) isCommercial;
1806
1807 - (CYString &) cyname;
1808
1809 - (uint32_t) compareBySection:(NSArray *)sections;
1810
1811 - (uint32_t) compareForChanges;
1812
1813 - (void) install;
1814 - (void) remove;
1815
1816 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1817 - (bool) isInstalledAndVisible:(NSNumber *)number;
1818 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1819 - (bool) isVisibleInSource:(Source *)source;
1820
1821 @end
1822
1823 uint32_t PackageChangesRadix(Package *self, void *) {
1824 union {
1825 uint32_t key;
1826
1827 struct {
1828 uint32_t timestamp : 30;
1829 uint32_t ignored : 1;
1830 uint32_t upgradable : 1;
1831 } bits;
1832 } value;
1833
1834 bool upgradable([self upgradableAndEssential:YES]);
1835 value.bits.upgradable = upgradable ? 1 : 0;
1836
1837 if (upgradable) {
1838 value.bits.timestamp = 0;
1839 value.bits.ignored = [self ignored] ? 0 : 1;
1840 value.bits.upgradable = 1;
1841 } else {
1842 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1843 value.bits.ignored = 0;
1844 value.bits.upgradable = 0;
1845 }
1846
1847 return _not(uint32_t) - value.key;
1848 }
1849
1850 _finline static void Stifle(uint8_t &value) {
1851 }
1852
1853 uint32_t PackagePrefixRadix(Package *self, void *context) {
1854 size_t offset(reinterpret_cast<size_t>(context));
1855 CYString &name([self cyname]);
1856
1857 size_t size(name.size());
1858 if (size == 0)
1859 return 0;
1860 char *text(name.data());
1861
1862 size_t zeros;
1863 if (!isdigit(text[0]))
1864 zeros = 0;
1865 else {
1866 size_t digits(1);
1867 while (size != digits && isdigit(text[digits]))
1868 if (++digits == 4)
1869 break;
1870 zeros = 4 - digits;
1871 }
1872
1873 uint8_t data[4];
1874
1875 // 0.607997
1876
1877 if (offset == 0 && zeros != 0) {
1878 memset(data, '0', zeros);
1879 memcpy(data + zeros, text, 4 - zeros);
1880 } else {
1881 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1882 if (size <= offset - zeros)
1883 return 0;
1884
1885 text += offset - zeros;
1886 size -= offset - zeros;
1887
1888 if (size >= 4)
1889 memcpy(data, text, 4);
1890 else {
1891 memcpy(data, text, size);
1892 memset(data + size, 0, 4 - size);
1893 }
1894
1895 for (size_t i(0); i != 4; ++i)
1896 if (isalpha(data[i]))
1897 data[i] &= 0xdf;
1898 }
1899
1900 if (offset == 0)
1901 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1902
1903 /* XXX: ntohl may be more honest */
1904 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1905 }
1906
1907 CYString &(*PackageName)(Package *self, SEL sel);
1908
1909 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1910 _profile(PackageNameCompare)
1911 CYString &lhi(PackageName(lhs, @selector(cyname)));
1912 CYString &rhi(PackageName(rhs, @selector(cyname)));
1913 CFStringRef lhn(lhi), rhn(rhi);
1914
1915 _profile(PackageNameCompare$NumbersLast)
1916 if (!lhi.empty() && !rhi.empty()) {
1917 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1918 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1919 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1920 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1921 return lha ? NSOrderedAscending : NSOrderedDescending;
1922 }
1923 _end
1924
1925 CFIndex length = CFStringGetLength(lhn);
1926
1927 _profile(PackageNameCompare$Compare)
1928 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1929 _end
1930 _end
1931 }
1932
1933 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1934 return PackageNameCompare(*lhs, *rhs, context);
1935 }
1936
1937 struct PackageNameOrdering :
1938 std::binary_function<Package *, Package *, bool>
1939 {
1940 _finline bool operator ()(Package *lhs, Package *rhs) const {
1941 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1942 }
1943 };
1944
1945 @implementation Package
1946
1947 - (NSString *) description {
1948 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1949 }
1950
1951 - (void) dealloc {
1952 if (source_ != nil)
1953 [source_ release];
1954 if (section$_ != nil)
1955 [section$_ release];
1956
1957 if (latest_ != nil)
1958 [latest_ release];
1959
1960 if (sponsor$_ != nil)
1961 [sponsor$_ release];
1962 if (author$_ != nil)
1963 [author$_ release];
1964 if (tags_ != nil)
1965 [tags_ release];
1966 if (role_ != nil)
1967 [role_ release];
1968
1969 if (relationships_ != nil)
1970 [relationships_ release];
1971 if (metadata_ != nil)
1972 [metadata_ release];
1973
1974 [super dealloc];
1975 }
1976
1977 + (NSString *) webScriptNameForSelector:(SEL)selector {
1978 if (selector == @selector(hasTag:))
1979 return @"hasTag";
1980 else
1981 return nil;
1982 }
1983
1984 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1985 return [self webScriptNameForSelector:selector] == nil;
1986 }
1987
1988 + (NSArray *) _attributeKeys {
1989 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
1990 }
1991
1992 - (NSArray *) attributeKeys {
1993 return [[self class] _attributeKeys];
1994 }
1995
1996 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1997 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1998 }
1999
2000 - (void) parse {
2001 if (parsed_)
2002 return;
2003 parsed_ = true;
2004 if (file_.end())
2005 return;
2006
2007 _profile(Package$parse)
2008 pkgRecords::Parser *parser;
2009
2010 _profile(Package$parse$Lookup)
2011 parser = &[database_ records]->Lookup(file_);
2012 _end
2013
2014 CYString website;
2015
2016 _profile(Package$parse$Find)
2017 struct {
2018 const char *name_;
2019 CYString *value_;
2020 } names[] = {
2021 {"icon", &icon_},
2022 {"depiction", &depiction_},
2023 {"homepage", &homepage_},
2024 {"website", &website},
2025 {"bugs", &bugs_},
2026 {"support", &support_},
2027 {"sponsor", &sponsor_},
2028 {"author", &author_},
2029 };
2030
2031 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2032 const char *start, *end;
2033
2034 if (parser->Find(names[i].name_, start, end)) {
2035 CYString &value(*names[i].value_);
2036 _profile(Package$parse$Value)
2037 value.set(pool_, start, end - start);
2038 _end
2039 }
2040 }
2041 _end
2042
2043 _profile(Package$parse$Tagline)
2044 const char *start, *end;
2045 if (parser->ShortDesc(start, end)) {
2046 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2047 if (stop == NULL)
2048 stop = end;
2049 while (stop != start && stop[-1] == '\r')
2050 --stop;
2051 tagline_.set(pool_, start, stop - start);
2052 }
2053 _end
2054
2055 _profile(Package$parse$Retain)
2056 if (homepage_.empty())
2057 homepage_ = website;
2058 if (homepage_ == depiction_)
2059 homepage_.clear();
2060 _end
2061 _end
2062 }
2063
2064 - (void) setVisible {
2065 visible_ = required_ && [self hasSupportingRole] && [self unfiltered];
2066 }
2067
2068 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2069 if ((self = [super init]) != nil) {
2070 _profile(Package$initWithVersion)
2071 @synchronized (database) {
2072 era_ = [database era];
2073 pool_ = pool;
2074
2075 version_ = version;
2076 iterator_ = version.ParentPkg();
2077 database_ = database;
2078
2079 _profile(Package$initWithVersion$Latest)
2080 latest_ = (NSString *) StripVersion(version_.VerStr());
2081 _end
2082
2083 pkgCache::VerIterator current;
2084 _profile(Package$initWithVersion$Versions)
2085 current = iterator_.CurrentVer();
2086 if (!current.end())
2087 installed_.set(pool_, StripVersion_(current.VerStr()));
2088
2089 if (!version_.end())
2090 file_ = version_.FileList();
2091 else {
2092 pkgCache &cache([database_ cache]);
2093 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2094 }
2095 _end
2096
2097 _profile(Package$initWithVersion$Name)
2098 id_.set(pool_, iterator_.Name());
2099 name_.set(pool, iterator_.Display());
2100 _end
2101
2102 if (!file_.end()) {
2103 _profile(Package$initWithVersion$Source)
2104 source_ = [database_ getSource:file_.File()];
2105 if (source_ != nil)
2106 [source_ retain];
2107 cached_ = true;
2108 _end
2109 }
2110
2111 required_ = true;
2112
2113 _profile(Package$initWithVersion$Tags)
2114 pkgCache::TagIterator tag(iterator_.TagList());
2115 if (!tag.end()) {
2116 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2117 do {
2118 const char *name(tag.Name());
2119 [tags_ addObject:(NSString *)CFCString(name)];
2120 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2121 role_ = (NSString *) CFCString(name + 6);
2122 if (required_ && strncmp(name, "require::", 9) == 0 && (
2123 true
2124 ))
2125 required_ = false;
2126 ++tag;
2127 } while (!tag.end());
2128 }
2129 _end
2130
2131 bool changed(false);
2132 NSString *key([id_ lowercaseString]);
2133
2134 _profile(Package$initWithVersion$Metadata)
2135 metadata_ = [Packages_ objectForKey:key];
2136
2137 if (metadata_ == nil) {
2138 firstSeen_ = now_;
2139
2140 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2141 firstSeen_, @"FirstSeen",
2142 latest_, @"LastVersion",
2143 nil] mutableCopy];
2144
2145 changed = true;
2146 } else {
2147 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2148 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2149
2150 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2151 subscribed_ = [subscribed boolValue];
2152
2153 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2154
2155 if (firstSeen_ == nil) {
2156 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2157 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2158 changed = true;
2159 }
2160
2161 if (version == nil) {
2162 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2163 changed = true;
2164 } else {
2165 if (![version isEqualToString:latest_]) {
2166 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2167 lastSeen_ = now_;
2168 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2169 changed = true;
2170 } }
2171 }
2172
2173 metadata_ = [metadata_ retain];
2174
2175 if (changed) {
2176 [Packages_ setObject:metadata_ forKey:key];
2177 Changed_ = true;
2178 }
2179 _end
2180
2181 _profile(Package$initWithVersion$Section)
2182 section_.set(pool_, iterator_.Section());
2183 _end
2184
2185 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2186 [self setVisible];
2187 } _end } return self;
2188 }
2189
2190 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2191 @synchronized ([Database class]) {
2192 pkgCache::VerIterator version;
2193
2194 _profile(Package$packageWithIterator$GetCandidateVer)
2195 version = [database policy]->GetCandidateVer(iterator);
2196 _end
2197
2198 if (version.end())
2199 return nil;
2200
2201 return [[[Package alloc]
2202 initWithVersion:version
2203 withZone:zone
2204 inPool:pool
2205 database:database
2206 ] autorelease];
2207 } }
2208
2209 - (pkgCache::PkgIterator) iterator {
2210 return iterator_;
2211 }
2212
2213 - (NSString *) section {
2214 if (section$_ == nil) {
2215 if (section_.empty())
2216 return nil;
2217
2218 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2219 NSString *name(section_);
2220
2221 lookup:
2222 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2223 if (NSString *rename = [value objectForKey:@"Rename"]) {
2224 name = rename;
2225 goto lookup;
2226 }
2227
2228 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2229 } return section$_;
2230 }
2231
2232 - (NSString *) simpleSection {
2233 if (NSString *section = [self section])
2234 return Simplify(section);
2235 else
2236 return nil;
2237 }
2238
2239 - (NSString *) longSection {
2240 return LocalizeSection([self section]);
2241 }
2242
2243 - (NSString *) shortSection {
2244 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2245 }
2246
2247 - (NSString *) uri {
2248 return nil;
2249 #if 0
2250 pkgIndexFile *index;
2251 pkgCache::PkgFileIterator file(file_.File());
2252 if (![database_ list].FindIndex(file, index))
2253 return nil;
2254 return [NSString stringWithUTF8String:iterator_->Path];
2255 //return [NSString stringWithUTF8String:file.Site()];
2256 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2257 #endif
2258 }
2259
2260 - (Address *) maintainer {
2261 if (file_.end())
2262 return nil;
2263 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2264 const std::string &maintainer(parser->Maintainer());
2265 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2266 }
2267
2268 - (size_t) size {
2269 return version_.end() ? 0 : version_->InstalledSize;
2270 }
2271
2272 - (NSString *) longDescription {
2273 if (file_.end())
2274 return nil;
2275 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2276 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2277
2278 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2279 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2280 if ([lines count] < 2)
2281 return nil;
2282
2283 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2284 for (size_t i(1), e([lines count]); i != e; ++i) {
2285 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2286 [trimmed addObject:trim];
2287 }
2288
2289 return [trimmed componentsJoinedByString:@"\n"];
2290 }
2291
2292 - (NSString *) shortDescription {
2293 return tagline_;
2294 }
2295
2296 - (unichar) index {
2297 _profile(Package$index)
2298 CFStringRef name((CFStringRef) [self name]);
2299 if (CFStringGetLength(name) == 0)
2300 return '#';
2301 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2302 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2303 return '#';
2304 return toupper(character);
2305 _end
2306 }
2307
2308 - (NSMutableDictionary *) metadata {
2309 return metadata_;
2310 }
2311
2312 - (NSDate *) seen {
2313 if (subscribed_ && lastSeen_ != nil)
2314 return lastSeen_;
2315 return firstSeen_;
2316 }
2317
2318 - (BOOL) subscribed {
2319 return subscribed_;
2320 }
2321
2322 - (BOOL) ignored {
2323 NSDictionary *metadata([self metadata]);
2324 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2325 return [ignored boolValue];
2326 else
2327 return false;
2328 }
2329
2330 - (NSString *) latest {
2331 return latest_;
2332 }
2333
2334 - (NSString *) installed {
2335 return installed_;
2336 }
2337
2338 - (BOOL) uninstalled {
2339 return installed_.empty();
2340 }
2341
2342 - (BOOL) valid {
2343 return !version_.end();
2344 }
2345
2346 - (BOOL) upgradableAndEssential:(BOOL)essential {
2347 _profile(Package$upgradableAndEssential)
2348 pkgCache::VerIterator current(iterator_.CurrentVer());
2349 if (current.end())
2350 return essential && essential_ && visible_;
2351 else
2352 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2353 _end
2354 }
2355
2356 - (BOOL) essential {
2357 return essential_;
2358 }
2359
2360 - (BOOL) broken {
2361 return [database_ cache][iterator_].InstBroken();
2362 }
2363
2364 - (BOOL) unfiltered {
2365 NSString *section([self section]);
2366 return section == nil || isSectionVisible(section);
2367 }
2368
2369 - (BOOL) visible {
2370 return visible_;
2371 }
2372
2373 - (BOOL) half {
2374 unsigned char current(iterator_->CurrentState);
2375 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2376 }
2377
2378 - (BOOL) halfConfigured {
2379 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2380 }
2381
2382 - (BOOL) halfInstalled {
2383 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2384 }
2385
2386 - (BOOL) hasMode {
2387 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2388 return state.Mode != pkgDepCache::ModeKeep;
2389 }
2390
2391 - (NSString *) mode {
2392 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2393
2394 switch (state.Mode) {
2395 case pkgDepCache::ModeDelete:
2396 if ((state.iFlags & pkgDepCache::Purge) != 0)
2397 return @"PURGE";
2398 else
2399 return @"REMOVE";
2400 case pkgDepCache::ModeKeep:
2401 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2402 return @"REINSTALL";
2403 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2404 return nil;*/
2405 else
2406 return nil;
2407 case pkgDepCache::ModeInstall:
2408 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2409 return @"REINSTALL";
2410 else*/ switch (state.Status) {
2411 case -1:
2412 return @"DOWNGRADE";
2413 case 0:
2414 return @"INSTALL";
2415 case 1:
2416 return @"UPGRADE";
2417 case 2:
2418 return @"NEW_INSTALL";
2419 default:
2420 _assert(false);
2421 }
2422 default:
2423 _assert(false);
2424 }
2425 }
2426
2427 - (NSString *) id {
2428 return id_;
2429 }
2430
2431 - (NSString *) name {
2432 return name_.empty() ? id_ : name_;
2433 }
2434
2435 - (UIImage *) icon {
2436 NSString *section = [self simpleSection];
2437
2438 UIImage *icon(nil);
2439 if (!icon_.empty())
2440 if ([icon_ hasPrefix:@"file:///"])
2441 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2442 if (icon == nil) if (section != nil)
2443 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2444 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2445 if ([dicon hasPrefix:@"file:///"])
2446 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2447 if (icon == nil)
2448 icon = [UIImage applicationImageNamed:@"unknown.png"];
2449 return icon;
2450 }
2451
2452 - (NSString *) homepage {
2453 return homepage_;
2454 }
2455
2456 - (NSString *) depiction {
2457 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2458 }
2459
2460 - (Address *) sponsor {
2461 if (sponsor$_ == nil) {
2462 if (sponsor_.empty())
2463 return nil;
2464 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2465 } return sponsor$_;
2466 }
2467
2468 - (Address *) author {
2469 if (author$_ == nil) {
2470 if (author_.empty())
2471 return nil;
2472 author$_ = [[Address addressWithString:author_] retain];
2473 } return author$_;
2474 }
2475
2476 - (NSString *) support {
2477 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2478 }
2479
2480 - (NSArray *) files {
2481 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2482 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2483
2484 std::ifstream fin;
2485 fin.open([path UTF8String]);
2486 if (!fin.is_open())
2487 return nil;
2488
2489 std::string line;
2490 while (std::getline(fin, line))
2491 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2492
2493 return files;
2494 }
2495
2496 - (NSArray *) relationships {
2497 return relationships_;
2498 }
2499
2500 - (NSArray *) warnings {
2501 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2502 const char *name(iterator_.Name());
2503
2504 size_t length(strlen(name));
2505 if (length < 2) invalid:
2506 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2507 else for (size_t i(0); i != length; ++i)
2508 if (
2509 /* XXX: technically this is not allowed */
2510 (name[i] < 'A' || name[i] > 'Z') &&
2511 (name[i] < 'a' || name[i] > 'z') &&
2512 (name[i] < '0' || name[i] > '9') &&
2513 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2514 ) goto invalid;
2515
2516 if (strcmp(name, "cydia") != 0) {
2517 bool cydia = false;
2518 bool user = false;
2519 bool _private = false;
2520 bool stash = false;
2521
2522 bool repository = [[self section] isEqualToString:@"Repositories"];
2523
2524 if (NSArray *files = [self files])
2525 for (NSString *file in files)
2526 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2527 cydia = true;
2528 else if (!user && [file isEqualToString:@"/User"])
2529 user = true;
2530 else if (!_private && [file isEqualToString:@"/private"])
2531 _private = true;
2532 else if (!stash && [file isEqualToString:@"/var/stash"])
2533 stash = true;
2534
2535 /* XXX: this is not sensitive enough. only some folders are valid. */
2536 if (cydia && !repository)
2537 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2538 if (user)
2539 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2540 if (_private)
2541 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2542 if (stash)
2543 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2544 }
2545
2546 return [warnings count] == 0 ? nil : warnings;
2547 }
2548
2549 - (NSArray *) applications {
2550 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2551
2552 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2553
2554 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2555 if (NSArray *files = [self files])
2556 for (NSString *file in files)
2557 if (application_r(file)) {
2558 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2559 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2560 if ([id isEqualToString:me])
2561 continue;
2562
2563 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2564 if (display == nil)
2565 display = application_r[1];
2566
2567 NSString *bundle([file stringByDeletingLastPathComponent]);
2568 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2569 if (icon == nil || [icon length] == 0)
2570 icon = @"icon.png";
2571 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2572
2573 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2574 [applications addObject:application];
2575
2576 [application addObject:id];
2577 [application addObject:display];
2578 [application addObject:url];
2579 }
2580
2581 return [applications count] == 0 ? nil : applications;
2582 }
2583
2584 - (Source *) source {
2585 if (!cached_) {
2586 @synchronized (database_) {
2587 if ([database_ era] != era_ || file_.end())
2588 source_ = nil;
2589 else {
2590 source_ = [database_ getSource:file_.File()];
2591 if (source_ != nil)
2592 [source_ retain];
2593 }
2594
2595 cached_ = true;
2596 }
2597 }
2598
2599 return source_;
2600 }
2601
2602 - (NSString *) role {
2603 return role_;
2604 }
2605
2606 - (BOOL) matches:(NSString *)text {
2607 if (text == nil)
2608 return NO;
2609
2610 NSRange range;
2611
2612 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2613 if (range.location != NSNotFound)
2614 return YES;
2615
2616 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2617 if (range.location != NSNotFound)
2618 return YES;
2619
2620 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2621 if (range.location != NSNotFound)
2622 return YES;
2623
2624 return NO;
2625 }
2626
2627 - (bool) hasSupportingRole {
2628 if (role_ == nil)
2629 return true;
2630 if ([role_ isEqualToString:@"enduser"])
2631 return true;
2632 if ([Role_ isEqualToString:@"User"])
2633 return false;
2634 if ([role_ isEqualToString:@"hacker"])
2635 return true;
2636 if ([Role_ isEqualToString:@"Hacker"])
2637 return false;
2638 if ([role_ isEqualToString:@"developer"])
2639 return true;
2640 if ([Role_ isEqualToString:@"Developer"])
2641 return false;
2642 _assert(false);
2643 }
2644
2645 - (BOOL) hasTag:(NSString *)tag {
2646 return tags_ == nil ? NO : [tags_ containsObject:tag];
2647 }
2648
2649 - (NSString *) primaryPurpose {
2650 for (NSString *tag in tags_)
2651 if ([tag hasPrefix:@"purpose::"])
2652 return [tag substringFromIndex:9];
2653 return nil;
2654 }
2655
2656 - (NSArray *) purposes {
2657 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2658 for (NSString *tag in tags_)
2659 if ([tag hasPrefix:@"purpose::"])
2660 [purposes addObject:[tag substringFromIndex:9]];
2661 return [purposes count] == 0 ? nil : purposes;
2662 }
2663
2664 - (bool) isCommercial {
2665 return [self hasTag:@"cydia::commercial"];
2666 }
2667
2668 - (CYString &) cyname {
2669 return name_.empty() ? id_ : name_;
2670 }
2671
2672 - (uint32_t) compareBySection:(NSArray *)sections {
2673 NSString *section([self section]);
2674 for (size_t i(0), e([sections count]); i != e; ++i) {
2675 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2676 return i;
2677 }
2678
2679 return _not(uint32_t);
2680 }
2681
2682 - (uint32_t) compareForChanges {
2683 union {
2684 uint32_t key;
2685
2686 struct {
2687 uint32_t timestamp : 30;
2688 uint32_t ignored : 1;
2689 uint32_t upgradable : 1;
2690 } bits;
2691 } value;
2692
2693 bool upgradable([self upgradableAndEssential:YES]);
2694 value.bits.upgradable = upgradable ? 1 : 0;
2695
2696 if (upgradable) {
2697 value.bits.timestamp = 0;
2698 value.bits.ignored = [self ignored] ? 0 : 1;
2699 value.bits.upgradable = 1;
2700 } else {
2701 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2702 value.bits.ignored = 0;
2703 value.bits.upgradable = 0;
2704 }
2705
2706 return _not(uint32_t) - value.key;
2707 }
2708
2709 - (void) clear {
2710 pkgProblemResolver *resolver = [database_ resolver];
2711 resolver->Clear(iterator_);
2712 resolver->Protect(iterator_);
2713 }
2714
2715 - (void) install {
2716 pkgProblemResolver *resolver = [database_ resolver];
2717 resolver->Clear(iterator_);
2718 resolver->Protect(iterator_);
2719 pkgCacheFile &cache([database_ cache]);
2720 cache->MarkInstall(iterator_, false);
2721 pkgDepCache::StateCache &state((*cache)[iterator_]);
2722 if (!state.Install())
2723 cache->SetReInstall(iterator_, true);
2724 }
2725
2726 - (void) remove {
2727 pkgProblemResolver *resolver = [database_ resolver];
2728 resolver->Clear(iterator_);
2729 resolver->Protect(iterator_);
2730 resolver->Remove(iterator_);
2731 [database_ cache]->MarkDelete(iterator_, true);
2732 }
2733
2734 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2735 _profile(Package$isUnfilteredAndSearchedForBy)
2736 bool value(true);
2737
2738 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2739 value &= [self unfiltered];
2740 _end
2741
2742 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2743 value &= [self matches:search];
2744 _end
2745
2746 return value;
2747 _end
2748 }
2749
2750 - (bool) isInstalledAndVisible:(NSNumber *)number {
2751 return (![number boolValue] || [self visible]) && ![self uninstalled];
2752 }
2753
2754 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2755 NSString *section = [self section];
2756
2757 return
2758 [self visible] &&
2759 [self uninstalled] && (
2760 name == nil ||
2761 section == nil && [name length] == 0 ||
2762 [name isEqualToString:section]
2763 );
2764 }
2765
2766 - (bool) isVisibleInSource:(Source *)source {
2767 return [self source] == source && [self visible];
2768 }
2769
2770 @end
2771 /* }}} */
2772 /* Section Class {{{ */
2773 @interface Section : NSObject {
2774 NSString *name_;
2775 unichar index_;
2776 size_t row_;
2777 size_t count_;
2778 NSString *localized_;
2779 }
2780
2781 - (NSComparisonResult) compareByLocalized:(Section *)section;
2782 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2783 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2784 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2785 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2786 - (NSString *) name;
2787 - (unichar) index;
2788
2789 - (size_t) row;
2790 - (size_t) count;
2791
2792 - (void) addToRow;
2793 - (void) addToCount;
2794
2795 - (void) setCount:(size_t)count;
2796 - (NSString *) localized;
2797
2798 @end
2799
2800 @implementation Section
2801
2802 - (void) dealloc {
2803 [name_ release];
2804 if (localized_ != nil)
2805 [localized_ release];
2806 [super dealloc];
2807 }
2808
2809 - (NSComparisonResult) compareByLocalized:(Section *)section {
2810 NSString *lhs(localized_);
2811 NSString *rhs([section localized]);
2812
2813 /*if ([lhs length] != 0 && [rhs length] != 0) {
2814 unichar lhc = [lhs characterAtIndex:0];
2815 unichar rhc = [rhs characterAtIndex:0];
2816
2817 if (isalpha(lhc) && !isalpha(rhc))
2818 return NSOrderedAscending;
2819 else if (!isalpha(lhc) && isalpha(rhc))
2820 return NSOrderedDescending;
2821 }*/
2822
2823 return [lhs compare:rhs options:LaxCompareOptions_];
2824 }
2825
2826 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2827 if ((self = [self initWithName:name localize:NO]) != nil) {
2828 if (localized != nil)
2829 localized_ = [localized retain];
2830 } return self;
2831 }
2832
2833 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2834 return [self initWithName:name row:0 localize:localize];
2835 }
2836
2837 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2838 if ((self = [super init]) != nil) {
2839 name_ = [name retain];
2840 index_ = '\0';
2841 row_ = row;
2842 if (localize)
2843 localized_ = [LocalizeSection(name_) retain];
2844 } return self;
2845 }
2846
2847 /* XXX: localize the index thingees */
2848 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2849 if ((self = [super init]) != nil) {
2850 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2851 index_ = index;
2852 row_ = row;
2853 } return self;
2854 }
2855
2856 - (NSString *) name {
2857 return name_;
2858 }
2859
2860 - (unichar) index {
2861 return index_;
2862 }
2863
2864 - (size_t) row {
2865 return row_;
2866 }
2867
2868 - (size_t) count {
2869 return count_;
2870 }
2871
2872 - (void) addToRow {
2873 ++row_;
2874 }
2875
2876 - (void) addToCount {
2877 ++count_;
2878 }
2879
2880 - (void) setCount:(size_t)count {
2881 count_ = count;
2882 }
2883
2884 - (NSString *) localized {
2885 return localized_;
2886 }
2887
2888 @end
2889 /* }}} */
2890
2891 /* Database Implementation {{{ */
2892 @implementation Database
2893
2894 + (Database *) sharedInstance {
2895 static Database *instance;
2896 if (instance == nil)
2897 instance = [[Database alloc] init];
2898 return instance;
2899 }
2900
2901 - (unsigned) era {
2902 return era_;
2903 }
2904
2905 - (void) dealloc {
2906 _assert(false);
2907 NSRecycleZone(zone_);
2908 // XXX: malloc_destroy_zone(zone_);
2909 apr_pool_destroy(pool_);
2910 [super dealloc];
2911 }
2912
2913 - (void) _readCydia:(NSNumber *)fd { _pooled
2914 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2915 std::istream is(&ib);
2916 std::string line;
2917
2918 static Pcre finish_r("^finish:([^:]*)$");
2919
2920 while (std::getline(is, line)) {
2921 const char *data(line.c_str());
2922 size_t size = line.size();
2923 lprintf("C:%s\n", data);
2924
2925 if (finish_r(data, size)) {
2926 NSString *finish = finish_r[1];
2927 int index = [Finishes_ indexOfObject:finish];
2928 if (index != INT_MAX && index > Finish_)
2929 Finish_ = index;
2930 }
2931 }
2932
2933 _assert(false);
2934 }
2935
2936 - (void) _readStatus:(NSNumber *)fd { _pooled
2937 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2938 std::istream is(&ib);
2939 std::string line;
2940
2941 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2942 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2943
2944 while (std::getline(is, line)) {
2945 const char *data(line.c_str());
2946 size_t size = line.size();
2947 lprintf("S:%s\n", data);
2948
2949 if (conffile_r(data, size)) {
2950 [delegate_ setConfigurationData:conffile_r[1]];
2951 } else if (strncmp(data, "status: ", 8) == 0) {
2952 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2953 [delegate_ setProgressTitle:string];
2954 } else if (pmstatus_r(data, size)) {
2955 std::string type([pmstatus_r[1] UTF8String]);
2956 NSString *id = pmstatus_r[2];
2957
2958 float percent([pmstatus_r[3] floatValue]);
2959 [delegate_ setProgressPercent:(percent / 100)];
2960
2961 NSString *string = pmstatus_r[4];
2962
2963 if (type == "pmerror")
2964 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2965 withObject:[NSArray arrayWithObjects:string, id, nil]
2966 waitUntilDone:YES
2967 ];
2968 else if (type == "pmstatus") {
2969 [delegate_ setProgressTitle:string];
2970 } else if (type == "pmconffile")
2971 [delegate_ setConfigurationData:string];
2972 else _assert(false);
2973 } else _assert(false);
2974 }
2975
2976 _assert(false);
2977 }
2978
2979 - (void) _readOutput:(NSNumber *)fd { _pooled
2980 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2981 std::istream is(&ib);
2982 std::string line;
2983
2984 while (std::getline(is, line)) {
2985 lprintf("O:%s\n", line.c_str());
2986 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2987 }
2988
2989 _assert(false);
2990 }
2991
2992 - (FILE *) input {
2993 return input_;
2994 }
2995
2996 - (Package *) packageWithName:(NSString *)name {
2997 @synchronized ([Database class]) {
2998 if (static_cast<pkgDepCache *>(cache_) == NULL)
2999 return nil;
3000 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3001 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3002 } }
3003
3004 - (Database *) init {
3005 if ((self = [super init]) != nil) {
3006 policy_ = NULL;
3007 records_ = NULL;
3008 resolver_ = NULL;
3009 fetcher_ = NULL;
3010 lock_ = NULL;
3011
3012 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3013 apr_pool_create(&pool_, NULL);
3014
3015 packages_ = [[NSMutableArray alloc] init];
3016
3017 int fds[2];
3018
3019 _assert(pipe(fds) != -1);
3020 cydiafd_ = fds[1];
3021
3022 _config->Set("APT::Keep-Fds::", cydiafd_);
3023 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3024
3025 [NSThread
3026 detachNewThreadSelector:@selector(_readCydia:)
3027 toTarget:self
3028 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3029 ];
3030
3031 _assert(pipe(fds) != -1);
3032 statusfd_ = fds[1];
3033
3034 [NSThread
3035 detachNewThreadSelector:@selector(_readStatus:)
3036 toTarget:self
3037 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3038 ];
3039
3040 _assert(pipe(fds) != -1);
3041 _assert(dup2(fds[0], 0) != -1);
3042 _assert(close(fds[0]) != -1);
3043
3044 input_ = fdopen(fds[1], "a");
3045
3046 _assert(pipe(fds) != -1);
3047 _assert(dup2(fds[1], 1) != -1);
3048 _assert(close(fds[1]) != -1);
3049
3050 [NSThread
3051 detachNewThreadSelector:@selector(_readOutput:)
3052 toTarget:self
3053 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3054 ];
3055 } return self;
3056 }
3057
3058 - (pkgCacheFile &) cache {
3059 return cache_;
3060 }
3061
3062 - (pkgDepCache::Policy *) policy {
3063 return policy_;
3064 }
3065
3066 - (pkgRecords *) records {
3067 return records_;
3068 }
3069
3070 - (pkgProblemResolver *) resolver {
3071 return resolver_;
3072 }
3073
3074 - (pkgAcquire &) fetcher {
3075 return *fetcher_;
3076 }
3077
3078 - (pkgSourceList &) list {
3079 return *list_;
3080 }
3081
3082 - (NSArray *) packages {
3083 return packages_;
3084 }
3085
3086 - (NSArray *) sources {
3087 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3088 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3089 [sources addObject:i->second];
3090 return sources;
3091 }
3092
3093 - (NSArray *) issues {
3094 if (cache_->BrokenCount() == 0)
3095 return nil;
3096
3097 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3098
3099 for (Package *package in packages_) {
3100 if (![package broken])
3101 continue;
3102 pkgCache::PkgIterator pkg([package iterator]);
3103
3104 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3105 [entry addObject:[package name]];
3106 [issues addObject:entry];
3107
3108 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3109 if (ver.end())
3110 continue;
3111
3112 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3113 pkgCache::DepIterator start;
3114 pkgCache::DepIterator end;
3115 dep.GlobOr(start, end); // ++dep
3116
3117 if (!cache_->IsImportantDep(end))
3118 continue;
3119 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3120 continue;
3121
3122 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3123 [entry addObject:failure];
3124 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3125
3126 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3127 if (Package *package = [self packageWithName:name])
3128 name = [package name];
3129 [failure addObject:name];
3130
3131 pkgCache::PkgIterator target(start.TargetPkg());
3132 if (target->ProvidesList != 0)
3133 [failure addObject:@"?"];
3134 else {
3135 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3136 if (!ver.end())
3137 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3138 else if (!cache_[target].CandidateVerIter(cache_).end())
3139 [failure addObject:@"-"];
3140 else if (target->ProvidesList == 0)
3141 [failure addObject:@"!"];
3142 else
3143 [failure addObject:@"%"];
3144 }
3145
3146 _forever {
3147 if (start.TargetVer() != 0)
3148 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3149 if (start == end)
3150 break;
3151 ++start;
3152 }
3153 }
3154 }
3155
3156 return issues;
3157 }
3158
3159 - (void) reloadData { _pooled
3160 @synchronized ([Database class]) {
3161
3162 @synchronized (self) {
3163 ++era_;
3164 }
3165
3166 [packages_ removeAllObjects];
3167 sources_.clear();
3168
3169 _error->Discard();
3170
3171 delete list_;
3172 list_ = NULL;
3173 manager_ = NULL;
3174 delete lock_;
3175 lock_ = NULL;
3176 delete fetcher_;
3177 fetcher_ = NULL;
3178 delete resolver_;
3179 resolver_ = NULL;
3180 delete records_;
3181 records_ = NULL;
3182 delete policy_;
3183 policy_ = NULL;
3184
3185 if (now_ != nil) {
3186 [now_ release];
3187 now_ = nil;
3188 }
3189
3190 cache_.Close();
3191
3192 apr_pool_clear(pool_);
3193 NSRecycleZone(zone_);
3194
3195 int chk(creat("/tmp/cydia.chk", 0644));
3196 if (chk != -1)
3197 close(chk);
3198
3199 _trace();
3200 if (!cache_.Open(progress_, true)) {
3201 std::string error;
3202 if (!_error->PopMessage(error))
3203 _assert(false);
3204 _error->Discard();
3205 lprintf("cache_.Open():[%s]\n", error.c_str());
3206
3207 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3208 [delegate_ repairWithSelector:@selector(configure)];
3209 else if (error == "The package lists or status file could not be parsed or opened.")
3210 [delegate_ repairWithSelector:@selector(update)];
3211 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3212 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3213 // else if (error == "The list of sources could not be read.")
3214 else _assert(false);
3215
3216 return;
3217 }
3218 _trace();
3219
3220 unlink("/tmp/cydia.chk");
3221
3222 now_ = [[NSDate date] retain];
3223
3224 policy_ = new pkgDepCache::Policy();
3225 records_ = new pkgRecords(cache_);
3226 resolver_ = new pkgProblemResolver(cache_);
3227 fetcher_ = new pkgAcquire(&status_);
3228 lock_ = NULL;
3229
3230 list_ = new pkgSourceList();
3231 _assert(list_->ReadMainList());
3232
3233 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3234 _assert(pkgApplyStatus(cache_));
3235
3236 if (cache_->BrokenCount() != 0) {
3237 _assert(pkgFixBroken(cache_));
3238 _assert(cache_->BrokenCount() == 0);
3239 _assert(pkgMinimizeUpgrade(cache_));
3240 }
3241
3242 _trace();
3243
3244 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3245 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3246 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3247 // XXX: this could be more intelligent
3248 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3249 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3250 if (!cached.end())
3251 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3252 }
3253 }
3254
3255 _trace();
3256
3257 {
3258 /*std::vector<Package *> packages;
3259 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3260 [packages_ release];
3261 packages_ = nil;*/
3262
3263 _trace();
3264
3265 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3266 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3267 //packages.push_back(package);
3268 [packages_ addObject:package];
3269
3270 _trace();
3271
3272 /*if (packages.empty())
3273 packages_ = [[NSArray alloc] init];
3274 else
3275 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3276 _trace();*/
3277
3278 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3279 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3280 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3281
3282 /*_trace();
3283 PrintTimes();
3284 _trace();*/
3285
3286 _trace();
3287
3288 /*if (!packages.empty())
3289 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3290 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3291
3292 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3293
3294 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3295
3296 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3297
3298 _trace();
3299 }
3300 } }
3301
3302 - (void) configure {
3303 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3304 system([dpkg UTF8String]);
3305 }
3306
3307 - (void) clean {
3308 if (lock_ != NULL)
3309 return;
3310
3311 FileFd Lock;
3312 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3313 _assert(!_error->PendingError());
3314
3315 pkgAcquire fetcher;
3316 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3317
3318 class LogCleaner :
3319 public pkgArchiveCleaner
3320 {
3321 protected:
3322 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3323 unlink(File);
3324 }
3325 } cleaner;
3326
3327 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3328 std::string error;
3329 while (_error->PopMessage(error))
3330 lprintf("ArchiveCleaner: %s\n", error.c_str());
3331 }
3332 }
3333
3334 - (void) prepare {
3335 fetcher_->Shutdown();
3336
3337 pkgRecords records(cache_);
3338
3339 lock_ = new FileFd();
3340 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3341 _assert(!_error->PendingError());
3342
3343 pkgSourceList list;
3344 // XXX: explain this with an error message
3345 _assert(list.ReadMainList());
3346
3347 manager_ = (_system->CreatePM(cache_));
3348 _assert(manager_->GetArchives(fetcher_, &list, &records));
3349 _assert(!_error->PendingError());
3350 }
3351
3352 - (void) perform {
3353 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3354 pkgSourceList list;
3355 _assert(list.ReadMainList());
3356 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3357 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3358 }
3359
3360 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3361 _trace();
3362 return;
3363 }
3364
3365 bool failed = false;
3366 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3367 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3368 continue;
3369 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3370 continue;
3371
3372 std::string uri = (*item)->DescURI();
3373 std::string error = (*item)->ErrorText;
3374
3375 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3376 failed = true;
3377
3378 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3379 withObject:[NSArray arrayWithObjects:
3380 [NSString stringWithUTF8String:error.c_str()],
3381 nil]
3382 waitUntilDone:YES
3383 ];
3384 }
3385
3386 if (failed) {
3387 _trace();
3388 return;
3389 }
3390
3391 _system->UnLock();
3392 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3393
3394 if (_error->PendingError()) {
3395 _trace();
3396 return;
3397 }
3398
3399 if (result == pkgPackageManager::Failed) {
3400 _trace();
3401 return;
3402 }
3403
3404 if (result != pkgPackageManager::Completed) {
3405 _trace();
3406 return;
3407 }
3408
3409 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3410 pkgSourceList list;
3411 _assert(list.ReadMainList());
3412 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3413 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3414 }
3415
3416 if (![before isEqualToArray:after])
3417 [self update];
3418 }
3419
3420 - (void) upgrade {
3421 _assert(pkgDistUpgrade(cache_));
3422 }
3423
3424 - (void) update {
3425 [self updateWithStatus:status_];
3426 }
3427
3428 - (void) setVisible {
3429 for (Package *package in packages_)
3430 [package setVisible];
3431 }
3432
3433 - (NSString *) updateWithStatus:(Status &)status {
3434 pkgSourceList list;
3435 _assert(list.ReadMainList());
3436
3437 FileFd lock;
3438 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3439
3440 if (_error->PendingError()) error: {
3441 std::string error;
3442 if (!_error->PopMessage(error))
3443 _assert(false);
3444 _error->Discard();
3445 return [NSString stringWithUTF8String:error.c_str()];
3446 }
3447
3448 if (!ListUpdate(status, list, PulseInterval_))
3449 goto error;
3450
3451 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3452 Changed_ = true;
3453
3454 return nil;
3455 }
3456
3457 - (void) setDelegate:(id)delegate {
3458 delegate_ = delegate;
3459 status_.setDelegate(delegate);
3460 progress_.setDelegate(delegate);
3461 }
3462
3463 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3464 SourceMap::const_iterator i(sources_.find(file->ID));
3465 return i == sources_.end() ? nil : i->second;
3466 }
3467
3468 @end
3469 /* }}} */
3470
3471 /* Confirmation View {{{ */
3472 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3473 if (!iterator.end())
3474 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3475 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3476 continue;
3477 pkgCache::PkgIterator package(dep.TargetPkg());
3478 if (package.end())
3479 continue;
3480 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3481 return true;
3482 }
3483
3484 return false;
3485 }
3486
3487 /* Web Scripting {{{ */
3488 @interface CydiaObject : NSObject {
3489 id indirect_;
3490 }
3491
3492 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3493 @end
3494
3495 @implementation CydiaObject
3496
3497 - (void) dealloc {
3498 [indirect_ release];
3499 [super dealloc];
3500 }
3501
3502 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3503 if ((self = [super init]) != nil) {
3504 indirect_ = [indirect retain];
3505 } return self;
3506 }
3507
3508 + (NSArray *) _attributeKeys {
3509 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3510 }
3511
3512 - (NSArray *) attributeKeys {
3513 return [[self class] _attributeKeys];
3514 }
3515
3516 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3517 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3518 }
3519
3520 - (NSString *) device {
3521 return [[UIDevice currentDevice] uniqueIdentifier];
3522 }
3523
3524 #if 0 // XXX: implement!
3525 - (NSString *) mac {
3526 if (![indirect_ promptForSensitive:@"Mac Address"])
3527 return nil;
3528 }
3529
3530 - (NSString *) serial {
3531 if (![indirect_ promptForSensitive:@"Serial #"])
3532 return nil;
3533 }
3534
3535 - (NSString *) firewire {
3536 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3537 return nil;
3538 }
3539
3540 - (NSString *) imei {
3541 if (![indirect_ promptForSensitive:@"IMEI"])
3542 return nil;
3543 }
3544 #endif
3545
3546 + (NSString *) webScriptNameForSelector:(SEL)selector {
3547 if (selector == @selector(close))
3548 return @"close";
3549 else if (selector == @selector(getPackageById:))
3550 return @"getPackageById";
3551 else if (selector == @selector(setAutoPopup:))
3552 return @"setAutoPopup";
3553 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3554 return @"setButtonImage";
3555 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3556 return @"setButtonTitle";
3557 else if (selector == @selector(setFinishHook:))
3558 return @"setFinishHook";
3559 else if (selector == @selector(setPopupHook:))
3560 return @"setPopupHook";
3561 else if (selector == @selector(setSpecial:))
3562 return @"setSpecial";
3563 else if (selector == @selector(setViewportWidth:))
3564 return @"setViewportWidth";
3565 else if (selector == @selector(supports:))
3566 return @"supports";
3567 else if (selector == @selector(stringWithFormat:arguments:))
3568 return @"format";
3569 else if (selector == @selector(localizedStringForKey:value:table:))
3570 return @"localize";
3571 else if (selector == @selector(du:))
3572 return @"du";
3573 else if (selector == @selector(statfs:))
3574 return @"statfs";
3575 else
3576 return nil;
3577 }
3578
3579 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3580 return [self webScriptNameForSelector:selector] == nil;
3581 }
3582
3583 - (BOOL) supports:(NSString *)feature {
3584 return [feature isEqualToString:@"window.open"];
3585 }
3586
3587 - (Package *) getPackageById:(NSString *)id {
3588 Package *package([[Database sharedInstance] packageWithName:id]);
3589 [package parse];
3590 return package;
3591 }
3592
3593 - (NSArray *) statfs:(NSString *)path {
3594 struct statfs stat;
3595
3596 if (path == nil || statfs([path UTF8String], &stat) == -1)
3597 return nil;
3598
3599 return [NSArray arrayWithObjects:
3600 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3601 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3602 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3603 nil];
3604 }
3605
3606 - (NSNumber *) du:(NSString *)path {
3607 NSNumber *value(nil);
3608
3609 int fds[2];
3610 _assert(pipe(fds) != -1);
3611
3612 pid_t pid(ExecFork());
3613 if (pid == 0) {
3614 _assert(dup2(fds[1], 1) != -1);
3615 _assert(close(fds[0]) != -1);
3616 _assert(close(fds[1]) != -1);
3617 /* XXX: this should probably not use du */
3618 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3619 exit(1);
3620 _assert(false);
3621 }
3622
3623 _assert(close(fds[1]) != -1);
3624
3625 if (FILE *du = fdopen(fds[0], "r")) {
3626 char line[1024];
3627 while (fgets(line, sizeof(line), du) != NULL) {
3628 size_t length(strlen(line));
3629 while (length != 0 && line[length - 1] == '\n')
3630 line[--length] = '\0';
3631 if (char *tab = strchr(line, '\t')) {
3632 *tab = '\0';
3633 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3634 }
3635 }
3636
3637 fclose(du);
3638 } else _assert(close(fds[0]));
3639
3640 int status;
3641 wait:
3642 if (waitpid(pid, &status, 0) == -1)
3643 if (errno == EINTR)
3644 goto wait;
3645 else _assert(false);
3646
3647 return value;
3648 }
3649
3650 - (void) close {
3651 [indirect_ close];
3652 }
3653
3654 - (void) setAutoPopup:(BOOL)popup {
3655 [indirect_ setAutoPopup:popup];
3656 }
3657
3658 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3659 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3660 }
3661
3662 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3663 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3664 }
3665
3666 - (void) setSpecial:(id)function {
3667 [indirect_ setSpecial:function];
3668 }
3669
3670 - (void) setFinishHook:(id)function {
3671 [indirect_ setFinishHook:function];
3672 }
3673
3674 - (void) setPopupHook:(id)function {
3675 [indirect_ setPopupHook:function];
3676 }
3677
3678 - (void) setViewportWidth:(float)width {
3679 [indirect_ setViewportWidth:width];
3680 }
3681
3682 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3683 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3684 unsigned count([arguments count]);
3685 id values[count];
3686 for (unsigned i(0); i != count; ++i)
3687 values[i] = [arguments objectAtIndex:i];
3688 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3689 }
3690
3691 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3692 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3693 value = nil;
3694 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3695 table = nil;
3696 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3697 }
3698
3699 @end
3700 /* }}} */
3701
3702 @interface CydiaBrowserView : BrowserView {
3703 CydiaObject *cydia_;
3704 }
3705
3706 @end
3707
3708 @implementation CydiaBrowserView
3709
3710 - (void) dealloc {
3711 [cydia_ release];
3712 [super dealloc];
3713 }
3714
3715 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3716 [super webView:sender didClearWindowObject:window forFrame:frame];
3717 [window setValue:cydia_ forKey:@"cydia"];
3718 }
3719
3720 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3721 if (System_ != NULL)
3722 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3723 if (Machine_ != NULL)
3724 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3725 if (UniqueID_ != nil)
3726 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
3727 if (Role_ != nil)
3728 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3729 }
3730
3731 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3732 NSMutableURLRequest *copy = [request mutableCopy];
3733 [self _setMoreHeaders:copy];
3734 return copy;
3735 }
3736
3737 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3738 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3739 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3740
3741 WebView *webview([webview_ webView]);
3742
3743 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3744
3745 NSString *application = package == nil ? @"Cydia" : [NSString
3746 stringWithFormat:@"Cydia/%@",
3747 [package installed]
3748 ];
3749
3750 if (Safari_ != nil)
3751 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3752 if (Build_ != nil)
3753 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3754 if (Product_ != nil)
3755 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3756
3757 [webview setApplicationNameForUserAgent:application];
3758 } return self;
3759 }
3760
3761 @end
3762
3763 @protocol ConfirmationViewDelegate
3764 - (void) cancel;
3765 - (void) confirm;
3766 - (void) queue;
3767 @end
3768
3769 @interface ConfirmationView : CydiaBrowserView {
3770 _transient Database *database_;
3771 UIActionSheet *essential_;
3772 NSArray *changes_;
3773 NSArray *issues_;
3774 NSArray *sizes_;
3775 BOOL substrate_;
3776 }
3777
3778 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3779
3780 @end
3781
3782 @implementation ConfirmationView
3783
3784 - (void) dealloc {
3785 [changes_ release];
3786 if (issues_ != nil)
3787 [issues_ release];
3788 [sizes_ release];
3789 if (essential_ != nil)
3790 [essential_ release];
3791 [super dealloc];
3792 }
3793
3794 - (void) cancel {
3795 [delegate_ cancel];
3796 [book_ popFromSuperviewAnimated:YES];
3797 }
3798
3799 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3800 NSString *context([sheet context]);
3801
3802 if ([context isEqualToString:@"remove"]) {
3803 switch (button) {
3804 case 1:
3805 [self cancel];
3806 break;
3807 case 2:
3808 if (substrate_)
3809 Finish_ = 2;
3810 [delegate_ confirm];
3811 break;
3812 default:
3813 _assert(false);
3814 }
3815
3816 [sheet dismiss];
3817 } else if ([context isEqualToString:@"unable"]) {
3818 [self cancel];
3819 [sheet dismiss];
3820 } else
3821 [super alertSheet:sheet buttonClicked:button];
3822 }
3823
3824 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3825 [super webView:sender didClearWindowObject:window forFrame:frame];
3826 [window setValue:changes_ forKey:@"changes"];
3827 [window setValue:issues_ forKey:@"issues"];
3828 [window setValue:sizes_ forKey:@"sizes"];
3829 }
3830
3831 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3832 if ((self = [super initWithBook:book]) != nil) {
3833 database_ = database;
3834
3835 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3836 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3837 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3838 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3839 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3840
3841 bool remove(false);
3842
3843 pkgDepCache::Policy *policy([database_ policy]);
3844
3845 pkgCacheFile &cache([database_ cache]);
3846 NSArray *packages = [database_ packages];
3847 for (Package *package in packages) {
3848 pkgCache::PkgIterator iterator = [package iterator];
3849 pkgDepCache::StateCache &state(cache[iterator]);
3850
3851 NSString *name([package name]);
3852
3853 if (state.NewInstall())
3854 [installing addObject:name];
3855 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3856 [reinstalling addObject:name];
3857 else if (state.Upgrade())
3858 [upgrading addObject:name];
3859 else if (state.Downgrade())
3860 [downgrading addObject:name];
3861 else if (state.Delete()) {
3862 if ([package essential])
3863 remove = true;
3864 [removing addObject:name];
3865 } else continue;
3866
3867 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3868 substrate_ |= DepSubstrate(iterator.CurrentVer());
3869 }
3870
3871 if (!remove)
3872 essential_ = nil;
3873 else if (Advanced_) {
3874 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
3875
3876 essential_ = [[UIActionSheet alloc]
3877 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
3878 buttons:[NSArray arrayWithObjects:
3879 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
3880 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
3881 nil]
3882 defaultButtonIndex:0
3883 delegate:self
3884 context:@"remove"
3885 ];
3886
3887 [essential_ setDestructiveButtonIndex:1];
3888 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
3889 } else {
3890 essential_ = [[UIActionSheet alloc]
3891 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
3892 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
3893 defaultButtonIndex:0
3894 delegate:self
3895 context:@"unable"
3896 ];
3897
3898 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
3899 }
3900
3901 changes_ = [[NSArray alloc] initWithObjects:
3902 installing,
3903 reinstalling,
3904 upgrading,
3905 downgrading,
3906 removing,
3907 nil];
3908
3909 issues_ = [database_ issues];
3910 if (issues_ != nil)
3911 issues_ = [issues_ retain];
3912
3913 sizes_ = [[NSArray alloc] initWithObjects:
3914 SizeString([database_ fetcher].FetchNeeded()),
3915 SizeString([database_ fetcher].PartialPresent()),
3916 SizeString([database_ cache]->UsrSize()),
3917 nil];
3918
3919 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3920 } return self;
3921 }
3922
3923 - (NSString *) backButtonTitle {
3924 return UCLocalize("CONFIRM");
3925 }
3926
3927 - (NSString *) leftButtonTitle {
3928 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
3929 }
3930
3931 - (id) rightButtonTitle {
3932 return issues_ != nil ? nil : [super rightButtonTitle];
3933 }
3934
3935 - (id) _rightButtonTitle {
3936 #if AlwaysReload || IgnoreInstall
3937 return [super _rightButtonTitle];
3938 #else
3939 return UCLocalize("CONFIRM");
3940 #endif
3941 }
3942
3943 - (void) _leftButtonClicked {
3944 [self cancel];
3945 }
3946
3947 #if !AlwaysReload
3948 - (void) _rightButtonClicked {
3949 #if IgnoreInstall
3950 return [super _rightButtonClicked];
3951 #endif
3952 if (essential_ != nil)
3953 [essential_ popupAlertAnimated:YES];
3954 else {
3955 if (substrate_)
3956 Finish_ = 2;
3957 [delegate_ confirm];
3958 }
3959 }
3960 #endif
3961
3962 @end
3963 /* }}} */
3964
3965 /* Progress Data {{{ */
3966 @interface ProgressData : NSObject {
3967 SEL selector_;
3968 id target_;
3969 id object_;
3970 }
3971
3972 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3973
3974 - (SEL) selector;
3975 - (id) target;
3976 - (id) object;
3977 @end
3978
3979 @implementation ProgressData
3980
3981 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3982 if ((self = [super init]) != nil) {
3983 selector_ = selector;
3984 target_ = target;
3985 object_ = object;
3986 } return self;
3987 }
3988
3989 - (SEL) selector {
3990 return selector_;
3991 }
3992
3993 - (id) target {
3994 return target_;
3995 }
3996
3997 - (id) object {
3998 return object_;
3999 }
4000
4001 @end
4002 /* }}} */
4003 /* Progress View {{{ */
4004 @interface ProgressView : UIView <
4005 ConfigurationDelegate,
4006 ProgressDelegate
4007 > {
4008 _transient Database *database_;
4009 UIView *view_;
4010 UIView *background_;
4011 UITransitionView *transition_;
4012 UIView *overlay_;
4013 UINavigationBar *navbar_;
4014 UIProgressBar *progress_;
4015 UITextView *output_;
4016 UITextLabel *status_;
4017 UIPushButton *close_;
4018 id delegate_;
4019 BOOL running_;
4020 SHA1SumValue springlist_;
4021 SHA1SumValue notifyconf_;
4022 }
4023
4024 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4025 - (void) setContentView:(UIView *)view;
4026 - (void) resetView;
4027
4028 - (void) _retachThread;
4029 - (void) _detachNewThreadData:(ProgressData *)data;
4030 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4031
4032 - (BOOL) isRunning;
4033
4034 @end
4035
4036 @protocol ProgressViewDelegate
4037 - (void) progressViewIsComplete:(ProgressView *)sender;
4038 @end
4039
4040 @implementation ProgressView
4041
4042 - (void) dealloc {
4043 [transition_ setDelegate:nil];
4044 [navbar_ setDelegate:nil];
4045
4046 [view_ release];
4047 if (background_ != nil)
4048 [background_ release];
4049 [transition_ release];
4050 [overlay_ release];
4051 [navbar_ release];
4052 [progress_ release];
4053 [output_ release];
4054 [status_ release];
4055 [close_ release];
4056 [super dealloc];
4057 }
4058
4059 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4060 if ((self = [super initWithFrame:frame]) != nil) {
4061 database_ = database;
4062 delegate_ = delegate;
4063
4064 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4065 [transition_ setDelegate:self];
4066
4067 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4068
4069 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4070 [background_ setBackgroundColor:[UIColor blackColor]];
4071 [self addSubview:background_];
4072
4073 [self addSubview:transition_];
4074
4075 CGSize navsize = [UINavigationBar defaultSize];
4076 CGRect navrect = {{0, 0}, navsize};
4077
4078 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4079 [overlay_ addSubview:navbar_];
4080
4081 [navbar_ setBarStyle:1];
4082 [navbar_ setDelegate:self];
4083
4084 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4085 [navbar_ pushNavigationItem:navitem];
4086
4087 CGRect bounds = [overlay_ bounds];
4088 CGSize prgsize = [UIProgressBar defaultSize];
4089
4090 CGRect prgrect = {{
4091 (bounds.size.width - prgsize.width) / 2,
4092 bounds.size.height - prgsize.height - 20
4093 }, prgsize};
4094
4095 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4096 [progress_ setStyle:0];
4097
4098 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4099 10,
4100 bounds.size.height - prgsize.height - 50,
4101 bounds.size.width - 20,
4102 24
4103 )];
4104
4105 [status_ setColor:[UIColor whiteColor]];
4106 [status_ setBackgroundColor:[UIColor clearColor]];
4107
4108 [status_ setCentersHorizontally:YES];
4109 //[status_ setFont:font];
4110
4111 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4112 10,
4113 navrect.size.height + 20,
4114 bounds.size.width - 20,
4115 bounds.size.height - navsize.height - 62 - navrect.size.height
4116 )];
4117
4118 //[output_ setTextFont:@"Courier New"];
4119 [output_ setFont:[[output_ font] fontWithSize:12]];
4120
4121 [output_ setTextColor:[UIColor whiteColor]];
4122 [output_ setBackgroundColor:[UIColor clearColor]];
4123
4124 [output_ setMarginTop:0];
4125 [output_ setAllowsRubberBanding:YES];
4126 [output_ setEditable:NO];
4127
4128 [overlay_ addSubview:output_];
4129
4130 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4131 10,
4132 bounds.size.height - prgsize.height - 50,
4133 bounds.size.width - 20,
4134 32 + prgsize.height
4135 )];
4136
4137 [close_ setAutosizesToFit:NO];
4138 [close_ setDrawsShadow:YES];
4139 [close_ setStretchBackground:YES];
4140 [close_ setEnabled:YES];
4141
4142 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4143 [close_ setTitleFont:bold];
4144
4145 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4146 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4147 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4148 } return self;
4149 }
4150
4151 - (void) setContentView:(UIView *)view {
4152 view_ = [view retain];
4153 }
4154
4155 - (void) resetView {
4156 [transition_ transition:6 toView:view_];
4157 }
4158
4159 - (void) _checkError {
4160 if (_error->PendingError()) {
4161 std::string error;
4162 if (!_error->PopMessage(error))
4163 _assert(false);
4164
4165 UIActionSheet *sheet = [[[UIActionSheet alloc]
4166 initWithTitle:UCLocalize("ERROR")
4167 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4168 defaultButtonIndex:0
4169 delegate:self
4170 context:@"_error"
4171 ] autorelease];
4172
4173 [sheet setBodyText:[NSString stringWithUTF8String:error.c_str()]];
4174 [sheet popupAlertAnimated:YES];
4175
4176 return;
4177 }
4178
4179 [delegate_ progressViewIsComplete:self];
4180
4181 if (Finish_ < 4) {
4182 FileFd file;
4183 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4184 _error->Discard();
4185 else {
4186 MMap mmap(file, MMap::ReadOnly);
4187 SHA1Summation sha1;
4188 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4189 if (!(notifyconf_ == sha1.Result()))
4190 Finish_ = 4;
4191 }
4192 }
4193
4194 if (Finish_ < 3) {
4195 FileFd file;
4196 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4197 _error->Discard();
4198 else {
4199 MMap mmap(file, MMap::ReadOnly);
4200 SHA1Summation sha1;
4201 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4202 if (!(springlist_ == sha1.Result()))
4203 Finish_ = 3;
4204 }
4205 }
4206
4207 switch (Finish_) {
4208 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4209 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4210 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4211 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4212 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4213 }
4214
4215 #define ListCache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4216 #define IconCache_ "/User/Library/Caches/com.apple.springboard-imagecache-icons.plist"
4217
4218 unlink(IconCache_);
4219
4220 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ListCache_]) {
4221 [cache autorelease];
4222
4223 NSFileManager *manager = [NSFileManager defaultManager];
4224 NSError *error = nil;
4225
4226 id system = [cache objectForKey:@"System"];
4227 if (system == nil)
4228 goto error;
4229
4230 struct stat info;
4231 if (stat(ListCache_, &info) == -1)
4232 goto error;
4233
4234 [system removeAllObjects];
4235
4236 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4237 for (NSString *app in apps)
4238 if ([app hasSuffix:@".app"]) {
4239 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4240 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4241 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4242 [info autorelease];
4243 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4244 [info setObject:path forKey:@"Path"];
4245 [info setObject:@"System" forKey:@"ApplicationType"];
4246 [system addInfoDictionary:info];
4247 }
4248 }
4249 }
4250 } else goto error;
4251
4252 [cache writeToFile:@ListCache_ atomically:YES];
4253
4254 if (chown(ListCache_, info.st_uid, info.st_gid) == -1)
4255 goto error;
4256 if (chmod(ListCache_, info.st_mode) == -1)
4257 goto error;
4258
4259 if (false) error:
4260 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4261 }
4262
4263 notify_post("com.apple.mobile.application_installed");
4264
4265 [delegate_ setStatusBarShowsProgress:NO];
4266 }
4267
4268 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4269 NSString *context([sheet context]);
4270
4271 if ([context isEqualToString:@"error"])
4272 [sheet dismiss];
4273 else if ([context isEqualToString:@"_error"]) {
4274 [sheet dismiss];
4275 [self _checkError];
4276 } else if ([context isEqualToString:@"conffile"]) {
4277 FILE *input = [database_ input];
4278
4279 switch (button) {
4280 case 1:
4281 fprintf(input, "N\n");
4282 fflush(input);
4283 break;
4284 case 2:
4285 fprintf(input, "Y\n");
4286 fflush(input);
4287 break;
4288 default:
4289 _assert(false);
4290 }
4291
4292 [sheet dismiss];
4293 }
4294 }
4295
4296 - (void) closeButtonPushed {
4297 running_ = NO;
4298
4299 switch (Finish_) {
4300 case 0:
4301 [self resetView];
4302 break;
4303
4304 case 1:
4305 [delegate_ suspendWithAnimation:YES];
4306 break;
4307
4308 case 2:
4309 system("launchctl stop com.apple.SpringBoard");
4310 break;
4311
4312 case 3:
4313 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4314 break;
4315
4316 case 4:
4317 system("reboot");
4318 break;
4319 }
4320 }
4321
4322 - (void) _retachThread {
4323 UINavigationItem *item = [navbar_ topItem];
4324 [item setTitle:UCLocalize("COMPLETE")];
4325
4326 [overlay_ addSubview:close_];
4327 [progress_ removeFromSuperview];
4328 [status_ removeFromSuperview];
4329
4330 [self _checkError];
4331 }
4332
4333 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4334 [[data target] performSelector:[data selector] withObject:[data object]];
4335 [data release];
4336
4337 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4338 }
4339
4340 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4341 UINavigationItem *item = [navbar_ topItem];
4342 [item setTitle:title];
4343
4344 [status_ setText:nil];
4345 [output_ setText:@""];
4346 [progress_ setProgress:0];
4347
4348 [close_ removeFromSuperview];
4349 [overlay_ addSubview:progress_];
4350 [overlay_ addSubview:status_];
4351
4352 [delegate_ setStatusBarShowsProgress:YES];
4353 running_ = YES;
4354
4355 {
4356 FileFd file;
4357 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4358 _error->Discard();
4359 else {
4360 MMap mmap(file, MMap::ReadOnly);
4361 SHA1Summation sha1;
4362 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4363 notifyconf_ = sha1.Result();
4364 }
4365 }
4366
4367 {
4368 FileFd file;
4369 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4370 _error->Discard();
4371 else {
4372 MMap mmap(file, MMap::ReadOnly);
4373 SHA1Summation sha1;
4374 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4375 springlist_ = sha1.Result();
4376 }
4377 }
4378
4379 [transition_ transition:6 toView:overlay_];
4380
4381 [NSThread
4382 detachNewThreadSelector:@selector(_detachNewThreadData:)
4383 toTarget:self
4384 withObject:[[ProgressData alloc]
4385 initWithSelector:selector
4386 target:target
4387 object:object
4388 ]
4389 ];
4390 }
4391
4392 - (void) repairWithSelector:(SEL)selector {
4393 [self
4394 detachNewThreadSelector:selector
4395 toTarget:database_
4396 withObject:nil
4397 title:UCLocalize("REPAIRING")
4398 ];
4399 }
4400
4401 - (void) setConfigurationData:(NSString *)data {
4402 [self
4403 performSelectorOnMainThread:@selector(_setConfigurationData:)
4404 withObject:data
4405 waitUntilDone:YES
4406 ];
4407 }
4408
4409 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4410 Package *package = id == nil ? nil : [database_ packageWithName:id];
4411
4412 UIActionSheet *sheet = [[[UIActionSheet alloc]
4413 initWithTitle:(package == nil ? id : [package name])
4414 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4415 defaultButtonIndex:0
4416 delegate:self
4417 context:@"error"
4418 ] autorelease];
4419
4420 [sheet setBodyText:error];
4421 [sheet popupAlertAnimated:YES];
4422 }
4423
4424 - (void) setProgressTitle:(NSString *)title {
4425 [self
4426 performSelectorOnMainThread:@selector(_setProgressTitle:)
4427 withObject:title
4428 waitUntilDone:YES
4429 ];
4430 }
4431
4432 - (void) setProgressPercent:(float)percent {
4433 [self
4434 performSelectorOnMainThread:@selector(_setProgressPercent:)
4435 withObject:[NSNumber numberWithFloat:percent]
4436 waitUntilDone:YES
4437 ];
4438 }
4439
4440 - (void) startProgress {
4441 }
4442
4443 - (void) addProgressOutput:(NSString *)output {
4444 [self
4445 performSelectorOnMainThread:@selector(_addProgressOutput:)
4446 withObject:output
4447 waitUntilDone:YES
4448 ];
4449 }
4450
4451 - (bool) isCancelling:(size_t)received {
4452 return false;
4453 }
4454
4455 - (void) _setConfigurationData:(NSString *)data {
4456 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4457
4458 _assert(conffile_r(data));
4459
4460 NSString *ofile = conffile_r[1];
4461 //NSString *nfile = conffile_r[2];
4462
4463 UIActionSheet *sheet = [[[UIActionSheet alloc]
4464 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4465 buttons:[NSArray arrayWithObjects:
4466 UCLocalize("KEEP_OLD_COPY"),
4467 UCLocalize("ACCEPT_NEW_COPY"),
4468 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4469 nil]
4470 defaultButtonIndex:0
4471 delegate:self
4472 context:@"conffile"
4473 ] autorelease];
4474
4475 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4476 [sheet popupAlertAnimated:YES];
4477 }
4478
4479 - (void) _setProgressTitle:(NSString *)title {
4480 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4481 for (size_t i(0), e([words count]); i != e; ++i) {
4482 NSString *word([words objectAtIndex:i]);
4483 if (Package *package = [database_ packageWithName:word])
4484 [words replaceObjectAtIndex:i withObject:[package name]];
4485 }
4486
4487 [status_ setText:[words componentsJoinedByString:@" "]];
4488 }
4489
4490 - (void) _setProgressPercent:(NSNumber *)percent {
4491 [progress_ setProgress:[percent floatValue]];
4492 }
4493
4494 - (void) _addProgressOutput:(NSString *)output {
4495 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4496 CGSize size = [output_ contentSize];
4497 CGRect rect = {{0, size.height}, {size.width, 0}};
4498 [output_ scrollRectToVisible:rect animated:YES];
4499 }
4500
4501 - (BOOL) isRunning {
4502 return running_;
4503 }
4504
4505 @end
4506 /* }}} */
4507
4508 /* Package Cell {{{ */
4509 @interface ContentView : UIView {
4510 _transient id delegate_;
4511 }
4512
4513 @end
4514
4515 @interface PackageCell : UITableViewCell {
4516 UIImage *icon_;
4517 NSString *name_;
4518 NSString *description_;
4519 bool commercial_;
4520 NSString *source_;
4521 UIImage *badge_;
4522 Package *package_;
4523 UIColor *color_;
4524 ContentView *content_;
4525 BOOL faded_;
4526 float fade_;
4527 }
4528
4529 - (PackageCell *) init;
4530 - (void) setPackage:(Package *)package;
4531
4532 + (int) heightForPackage:(Package *)package;
4533 - (void) drawContentRect:(CGRect)rect;
4534
4535 @end
4536
4537 @implementation ContentView
4538
4539 - (id) initWithFrame:(CGRect)frame {
4540 if ((self = [super initWithFrame:frame]) != nil) {
4541 } return self;
4542 }
4543
4544 - (void) setDelegate:(id)delegate {
4545 delegate_ = delegate;
4546 }
4547
4548 - (void) drawRect:(CGRect)rect {
4549 [super drawRect:rect];
4550 [delegate_ drawContentRect:rect];
4551 }
4552
4553 @end
4554
4555 @implementation PackageCell
4556
4557 - (void) clearPackage {
4558 if (icon_ != nil) {
4559 [icon_ release];
4560 icon_ = nil;
4561 }
4562
4563 if (name_ != nil) {
4564 [name_ release];
4565 name_ = nil;
4566 }
4567
4568 if (description_ != nil) {
4569 [description_ release];
4570 description_ = nil;
4571 }
4572
4573 if (source_ != nil) {
4574 [source_ release];
4575 source_ = nil;
4576 }
4577
4578 if (badge_ != nil) {
4579 [badge_ release];
4580 badge_ = nil;
4581 }
4582
4583 [package_ release];
4584 package_ = nil;
4585 }
4586
4587 - (void) dealloc {
4588 [self clearPackage];
4589 [content_ release];
4590 [color_ release];
4591 [super dealloc];
4592 }
4593
4594 - (float) fade {
4595 return faded_ ? [self selectionPercent] : fade_;
4596 }
4597
4598 - (PackageCell *) init {
4599 CGRect frame(CGRectMake(0, 0, 320, 74));
4600 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4601 UIView *content([self contentView]);
4602 CGRect bounds([content bounds]);
4603 content_ = [[ContentView alloc] initWithFrame:bounds];
4604 [content_ setDelegate:self];
4605 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4606 [content_ setOpaque:YES];
4607 [content addSubview:content_];
4608 if ([self respondsToSelector:@selector(selectionPercent)])
4609 faded_ = YES;
4610 } return self;
4611 }
4612
4613 - (void) _setBackgroundColor {
4614 UIColor *color;
4615 if (NSString *mode = [package_ mode]) {
4616 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4617 color = remove ? RemovingColor_ : InstallingColor_;
4618 } else
4619 color = [UIColor whiteColor];
4620
4621 [content_ setBackgroundColor:color];
4622 [self setNeedsDisplay];
4623 }
4624
4625 - (void) setPackage:(Package *)package {
4626 [self clearPackage];
4627 [package parse];
4628
4629 Source *source = [package source];
4630
4631 icon_ = [[package icon] retain];
4632 name_ = [[package name] retain];
4633 description_ = [[package shortDescription] retain];
4634 commercial_ = [package isCommercial];
4635
4636 package_ = [package retain];
4637
4638 NSString *label = nil;
4639 bool trusted = false;
4640
4641 if (source != nil) {
4642 label = [source label];
4643 trusted = [source trusted];
4644 } else if ([[package id] isEqualToString:@"firmware"])
4645 label = UCLocalize("APPLE");
4646 else
4647 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4648
4649 NSString *from(label);
4650
4651 NSString *section = [package simpleSection];
4652 if (section != nil && ![section isEqualToString:label]) {
4653 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4654 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4655 }
4656
4657 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4658 source_ = [from retain];
4659
4660 if (NSString *purpose = [package primaryPurpose])
4661 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4662 badge_ = [badge_ retain];
4663
4664 [self _setBackgroundColor];
4665 [content_ setNeedsDisplay];
4666 }
4667
4668 - (void) drawContentRect:(CGRect)rect {
4669 bool selected([self isSelected]);
4670
4671 #if 0
4672 CGContextRef context(UIGraphicsGetCurrentContext());
4673 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4674 CGContextFillRect(context, rect);
4675 #endif
4676
4677 if (icon_ != nil) {
4678 CGRect rect;
4679 rect.size = [icon_ size];
4680
4681 rect.size.width /= 2;
4682 rect.size.height /= 2;
4683
4684 rect.origin.x = 25 - rect.size.width / 2;
4685 rect.origin.y = 25 - rect.size.height / 2;
4686
4687 [icon_ drawInRect:rect];
4688 }
4689
4690 if (badge_ != nil) {
4691 CGSize size = [badge_ size];
4692
4693 [badge_ drawAtPoint:CGPointMake(
4694 36 - size.width / 2,
4695 36 - size.height / 2
4696 )];
4697 }
4698
4699 if (selected)
4700 UISetColor(White_);
4701
4702 if (!selected)
4703 UISetColor(commercial_ ? Purple_ : Black_);
4704 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4705 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4706
4707 if (!selected)
4708 UISetColor(commercial_ ? Purplish_ : Gray_);
4709 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4710 }
4711
4712 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4713 //[self _setBackgroundColor];
4714 [super setSelected:selected animated:fade];
4715 [content_ setNeedsDisplay];
4716 }
4717
4718 + (int) heightForPackage:(Package *)package {
4719 return 73;
4720 }
4721
4722 @end
4723 /* }}} */
4724 /* Section Cell {{{ */
4725 @interface SectionCell : UISimpleTableCell {
4726 NSString *section_;
4727 NSString *name_;
4728 NSString *count_;
4729 UIImage *icon_;
4730 _UISwitchSlider *switch_;
4731 BOOL editing_;
4732 }
4733
4734 - (id) init;
4735 - (void) setSection:(Section *)section editing:(BOOL)editing;
4736
4737 @end
4738
4739 @implementation SectionCell
4740
4741 - (void) clearSection {
4742 if (section_ != nil) {
4743 [section_ release];
4744 section_ = nil;
4745 }
4746
4747 if (name_ != nil) {
4748 [name_ release];
4749 name_ = nil;
4750 }
4751
4752 if (count_ != nil) {
4753 [count_ release];
4754 count_ = nil;
4755 }
4756 }
4757
4758 - (void) dealloc {
4759 [self clearSection];
4760 [icon_ release];
4761 [switch_ release];
4762 [super dealloc];
4763 }
4764
4765 - (id) init {
4766 if ((self = [super init]) != nil) {
4767 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4768
4769 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4770 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4771 } return self;
4772 }
4773
4774 - (void) onSwitch:(id)sender {
4775 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4776 if (metadata == nil) {
4777 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4778 [Sections_ setObject:metadata forKey:section_];
4779 }
4780
4781 Changed_ = true;
4782 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4783 }
4784
4785 - (void) setSection:(Section *)section editing:(BOOL)editing {
4786 if (editing != editing_) {
4787 if (editing_)
4788 [switch_ removeFromSuperview];
4789 else
4790 [self addSubview:switch_];
4791 editing_ = editing;
4792 }
4793
4794 [self clearSection];
4795
4796 if (section == nil) {
4797 name_ = [UCLocalize("ALL_PACKAGES") retain];
4798 count_ = nil;
4799 } else {
4800 section_ = [section localized];
4801 if (section_ != nil)
4802 section_ = [section_ retain];
4803 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4804 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4805
4806 if (editing_)
4807 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4808 }
4809 }
4810
4811 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4812 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4813
4814 if (selected)
4815 UISetColor(White_);
4816
4817 if (!selected)
4818 UISetColor(Black_);
4819 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4820
4821 CGSize size = [count_ sizeWithFont:Font14_];
4822
4823 UISetColor(White_);
4824 if (count_ != nil)
4825 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4826
4827 [super drawContentInRect:rect selected:selected];
4828 }
4829
4830 @end
4831 /* }}} */
4832
4833 /* File Table {{{ */
4834 @interface FileTable : RVPage {
4835 _transient Database *database_;
4836 Package *package_;
4837 NSString *name_;
4838 NSMutableArray *files_;
4839 UITable *list_;
4840 }
4841
4842 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4843 - (void) setPackage:(Package *)package;
4844
4845 @end
4846
4847 @implementation FileTable
4848
4849 - (void) dealloc {
4850 if (package_ != nil)
4851 [package_ release];
4852 if (name_ != nil)
4853 [name_ release];
4854 [files_ release];
4855 [list_ release];
4856 [super dealloc];
4857 }
4858
4859 - (int) numberOfRowsInTable:(UITable *)table {
4860 return files_ == nil ? 0 : [files_ count];
4861 }
4862
4863 - (float) table:(UITable *)table heightForRow:(int)row {
4864 return 24;
4865 }
4866
4867 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4868 if (reusing == nil) {
4869 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4870 UIFont *font = [UIFont systemFontOfSize:16];
4871 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4872 }
4873 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4874 return reusing;
4875 }
4876
4877 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4878 return NO;
4879 }
4880
4881 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4882 if ((self = [super initWithBook:book]) != nil) {
4883 database_ = database;
4884
4885 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4886
4887 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4888 [self addSubview:list_];
4889
4890 UITableColumn *column = [[[UITableColumn alloc]
4891 initWithTitle:UCLocalize("NAME")
4892 identifier:@"name"
4893 width:[self frame].size.width
4894 ] autorelease];
4895
4896 [list_ setDataSource:self];
4897 [list_ setSeparatorStyle:1];
4898 [list_ addTableColumn:column];
4899 [list_ setDelegate:self];
4900 [list_ setReusesTableCells:YES];
4901 } return self;
4902 }
4903
4904 - (void) setPackage:(Package *)package {
4905 if (package_ != nil) {
4906 [package_ autorelease];
4907 package_ = nil;
4908 }
4909
4910 if (name_ != nil) {
4911 [name_ release];
4912 name_ = nil;
4913 }
4914
4915 [files_ removeAllObjects];
4916
4917 if (package != nil) {
4918 package_ = [package retain];
4919 name_ = [[package id] retain];
4920
4921 if (NSArray *files = [package files])
4922 [files_ addObjectsFromArray:files];
4923
4924 if ([files_ count] != 0) {
4925 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4926 [files_ removeObjectAtIndex:0];
4927 [files_ sortUsingSelector:@selector(compareByPath:)];
4928
4929 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4930 [stack addObject:@"/"];
4931
4932 for (int i(0), e([files_ count]); i != e; ++i) {
4933 NSString *file = [files_ objectAtIndex:i];
4934 while (![file hasPrefix:[stack lastObject]])
4935 [stack removeLastObject];
4936 NSString *directory = [stack lastObject];
4937 [stack addObject:[file stringByAppendingString:@"/"]];
4938 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4939 ([stack count] - 2) * 3, "",
4940 [file substringFromIndex:[directory length]]
4941 ]];
4942 }
4943 }
4944 }
4945
4946 [list_ reloadData];
4947 }
4948
4949 - (void) resetViewAnimated:(BOOL)animated {
4950 [list_ resetViewAnimated:animated];
4951 }
4952
4953 - (void) reloadData {
4954 [self setPackage:[database_ packageWithName:name_]];
4955 [self reloadButtons];
4956 }
4957
4958 - (NSString *) title {
4959 return UCLocalize("INSTALLED_FILES");
4960 }
4961
4962 - (NSString *) backButtonTitle {
4963 return UCLocalize("FILES");
4964 }
4965
4966 @end
4967 /* }}} */
4968 /* Package View {{{ */
4969 @interface PackageView : CydiaBrowserView {
4970 _transient Database *database_;
4971 Package *package_;
4972 NSString *name_;
4973 bool commercial_;
4974 NSMutableArray *buttons_;
4975 }
4976
4977 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4978 - (void) setPackage:(Package *)package;
4979
4980 @end
4981
4982 @implementation PackageView
4983
4984 - (void) dealloc {
4985 if (package_ != nil)
4986 [package_ release];
4987 if (name_ != nil)
4988 [name_ release];
4989 [buttons_ release];
4990 [super dealloc];
4991 }
4992
4993 - (void) release {
4994 if ([self retainCount] == 1)
4995 [delegate_ setPackageView:self];
4996 [super release];
4997 }
4998
4999 /* XXX: this is not safe at all... localization of /fail/ */
5000 - (void) _clickButtonWithName:(NSString *)name {
5001 if ([name isEqualToString:UCLocalize("CLEAR")])
5002 [delegate_ clearPackage:package_];
5003 else if ([name isEqualToString:UCLocalize("INSTALL")])
5004 [delegate_ installPackage:package_];
5005 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5006 [delegate_ installPackage:package_];
5007 else if ([name isEqualToString:UCLocalize("REMOVE")])
5008 [delegate_ removePackage:package_];
5009 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5010 [delegate_ installPackage:package_];
5011 else _assert(false);
5012 }
5013
5014 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5015 NSString *context([sheet context]);
5016
5017 if ([context isEqualToString:@"modify"]) {
5018 int count = [buttons_ count];
5019 _assert(count != 0);
5020 _assert(button <= count + 1);
5021
5022 if (count != button - 1)
5023 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5024
5025 [sheet dismiss];
5026 } else
5027 [super alertSheet:sheet buttonClicked:button];
5028 }
5029
5030 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5031 return [super webView:sender didFinishLoadForFrame:frame];
5032 }
5033
5034 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5035 [super webView:sender didClearWindowObject:window forFrame:frame];
5036 [window setValue:package_ forKey:@"package"];
5037 }
5038
5039 - (bool) _allowJavaScriptPanel {
5040 return commercial_;
5041 }
5042
5043 #if !AlwaysReload
5044 - (void) __rightButtonClicked {
5045 int count = [buttons_ count];
5046 _assert(count != 0);
5047
5048 if (count == 1)
5049 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5050 else {
5051 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5052 [buttons addObjectsFromArray:buttons_];
5053 [buttons addObject:UCLocalize("CANCEL")];
5054
5055 [delegate_ slideUp:[[[UIActionSheet alloc]
5056 initWithTitle:nil
5057 buttons:buttons
5058 defaultButtonIndex:([buttons count] - 1)
5059 delegate:self
5060 context:@"modify"
5061 ] autorelease]];
5062 }
5063 }
5064
5065 - (void) _rightButtonClicked {
5066 if (commercial_)
5067 [super _rightButtonClicked];
5068 else
5069 [self __rightButtonClicked];
5070 }
5071 #endif
5072
5073 - (id) _rightButtonTitle {
5074 int count = [buttons_ count];
5075 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5076 }
5077
5078 - (NSString *) backButtonTitle {
5079 return @"Details";
5080 }
5081
5082 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5083 if ((self = [super initWithBook:book]) != nil) {
5084 database_ = database;
5085 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5086 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5087 } return self;
5088 }
5089
5090 - (void) setPackage:(Package *)package {
5091 if (package_ != nil) {
5092 [package_ autorelease];
5093 package_ = nil;
5094 }
5095
5096 if (name_ != nil) {
5097 [name_ release];
5098 name_ = nil;
5099 }
5100
5101 [buttons_ removeAllObjects];
5102
5103 if (package != nil) {
5104 [package parse];
5105
5106 package_ = [package retain];
5107 name_ = [[package id] retain];
5108 commercial_ = [package isCommercial];
5109
5110 if ([package_ mode] != nil)
5111 [buttons_ addObject:UCLocalize("CLEAR")];
5112 if ([package_ source] == nil);
5113 else if ([package_ upgradableAndEssential:NO])
5114 [buttons_ addObject:UCLocalize("UPGRADE")];
5115 else if ([package_ uninstalled])
5116 [buttons_ addObject:UCLocalize("INSTALL")];
5117 else
5118 [buttons_ addObject:UCLocalize("REINSTALL")];
5119 if (![package_ uninstalled])
5120 [buttons_ addObject:UCLocalize("REMOVE")];
5121
5122 if (special_ != NULL) {
5123 CGRect frame([webview_ frame]);
5124 frame.size.width = 320;
5125 frame.size.height = 0;
5126 [webview_ setFrame:frame];
5127
5128 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5129
5130 WebThreadLock();
5131 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5132
5133 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5134
5135 [self setFinishHook:nil];
5136 [self setPopupHook:nil];
5137 WebThreadUnlock();
5138
5139 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5140 [super callFunction:special_];
5141 }
5142 }
5143
5144 [self reloadButtons];
5145 }
5146
5147 - (bool) isLoading {
5148 return commercial_ ? [super isLoading] : false;
5149 }
5150
5151 - (void) reloadData {
5152 [self setPackage:[database_ packageWithName:name_]];
5153 }
5154
5155 @end
5156 /* }}} */
5157 /* Package Table {{{ */
5158 @interface PackageTable : RVPage {
5159 _transient Database *database_;
5160 NSString *title_;
5161 NSMutableArray *packages_;
5162 NSMutableArray *sections_;
5163 UITableView *list_;
5164 NSMutableArray *index_;
5165 NSMutableDictionary *indices_;
5166 }
5167
5168 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5169
5170 - (void) setDelegate:(id)delegate;
5171
5172 - (void) reloadData;
5173 - (void) resetCursor;
5174
5175 - (UITableView *) list;
5176
5177 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5178
5179 @end
5180
5181 @implementation PackageTable
5182
5183 - (void) dealloc {
5184 [list_ setDataSource:nil];
5185
5186 [title_ release];
5187 [packages_ release];
5188 [sections_ release];
5189 [list_ release];
5190 [index_ release];
5191 [indices_ release];
5192 [super dealloc];
5193 }
5194
5195 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5196 NSInteger count([sections_ count]);
5197 return count == 0 ? 1 : count;
5198 }
5199
5200 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5201 if ([sections_ count] == 0)
5202 return nil;
5203 return [[sections_ objectAtIndex:section] name];
5204 }
5205
5206 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5207 if ([sections_ count] == 0)
5208 return 0;
5209 return [[sections_ objectAtIndex:section] count];
5210 }
5211
5212 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5213 Section *section([sections_ objectAtIndex:[path section]]);
5214 NSInteger row([path row]);
5215 Package *package([packages_ objectAtIndex:([section row] + row)]);
5216 return package;
5217 }
5218
5219 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5220 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5221 if (cell == nil)
5222 cell = [[[PackageCell alloc] init] autorelease];
5223 [cell setPackage:[self packageAtIndexPath:path]];
5224 return cell;
5225 }
5226
5227 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5228 return 73;
5229 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5230 }
5231
5232 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5233 Package *package([self packageAtIndexPath:path]);
5234 package = [database_ packageWithName:[package id]];
5235 PackageView *view([delegate_ packageView]);
5236 [view setPackage:package];
5237 [view setDelegate:delegate_];
5238 [book_ pushPage:view];
5239 return path;
5240 }
5241
5242 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5243 return [packages_ count] > 20 ? index_ : nil;
5244 }
5245
5246 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5247 return index;
5248 }
5249
5250 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5251 if ((self = [super initWithBook:book]) != nil) {
5252 database_ = database;
5253 title_ = [title retain];
5254
5255 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5256 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5257
5258 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5259 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5260
5261 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5262 [list_ setDataSource:self];
5263 [list_ setDelegate:self];
5264
5265 [self addSubview:list_];
5266
5267 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5268 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5269 } return self;
5270 }
5271
5272 - (void) setDelegate:(id)delegate {
5273 delegate_ = delegate;
5274 }
5275
5276 - (bool) hasPackage:(Package *)package {
5277 return true;
5278 }
5279
5280 - (void) reloadData {
5281 NSArray *packages = [database_ packages];
5282
5283 [packages_ removeAllObjects];
5284 [sections_ removeAllObjects];
5285
5286 _profile(PackageTable$reloadData$Filter)
5287 for (Package *package in packages)
5288 if ([self hasPackage:package])
5289 [packages_ addObject:package];
5290 _end
5291
5292 [index_ removeAllObjects];
5293 [indices_ removeAllObjects];
5294
5295 Section *section = nil;
5296
5297 _profile(PackageTable$reloadData$Section)
5298 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5299 Package *package;
5300 unichar index;
5301
5302 _profile(PackageTable$reloadData$Section$Package)
5303 package = [packages_ objectAtIndex:offset];
5304 index = [package index];
5305 _end
5306
5307 if (section == nil || [section index] != index) {
5308 _profile(PackageTable$reloadData$Section$Allocate)
5309 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5310 _end
5311
5312 [index_ addObject:[section name]];
5313 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5314
5315 _profile(PackageTable$reloadData$Section$Add)
5316 [sections_ addObject:section];
5317 _end
5318 }
5319
5320 [section addToCount];
5321 }
5322 _end
5323
5324 _profile(PackageTable$reloadData$List)
5325 [list_ reloadData];
5326 _end
5327 }
5328
5329 - (NSString *) title {
5330 return title_;
5331 }
5332
5333 - (void) resetViewAnimated:(BOOL)animated {
5334 [list_ resetViewAnimated:animated];
5335 }
5336
5337 - (void) resetCursor {
5338 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5339 }
5340
5341 - (UITableView *) list {
5342 return list_;
5343 }
5344
5345 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5346 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5347 }
5348
5349 @end
5350 /* }}} */
5351 /* Filtered Package Table {{{ */
5352 @interface FilteredPackageTable : PackageTable {
5353 SEL filter_;
5354 IMP imp_;
5355 id object_;
5356 }
5357
5358 - (void) setObject:(id)object;
5359
5360 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5361
5362 @end
5363
5364 @implementation FilteredPackageTable
5365
5366 - (void) dealloc {
5367 if (object_ != nil)
5368 [object_ release];
5369 [super dealloc];
5370 }
5371
5372 - (void) setObject:(id)object {
5373 if (object_ != nil)
5374 [object_ release];
5375 if (object == nil)
5376 object_ = nil;
5377 else
5378 object_ = [object retain];
5379 }
5380
5381 - (bool) hasPackage:(Package *)package {
5382 _profile(FilteredPackageTable$hasPackage)
5383 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5384 _end
5385 }
5386
5387 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5388 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5389 filter_ = filter;
5390 object_ = object == nil ? nil : [object retain];
5391
5392 /* XXX: this is an unsafe optimization of doomy hell */
5393 Method method = class_getInstanceMethod([Package class], filter);
5394 _assert(method != NULL);
5395 imp_ = method_getImplementation(method);
5396 _assert(imp_ != NULL);
5397
5398 [self reloadData];
5399 } return self;
5400 }
5401
5402 @end
5403 /* }}} */
5404
5405 /* Add Source View {{{ */
5406 @interface AddSourceView : RVPage {
5407 _transient Database *database_;
5408 }
5409
5410 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5411
5412 @end
5413
5414 @implementation AddSourceView
5415
5416 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5417 if ((self = [super initWithBook:book]) != nil) {
5418 database_ = database;
5419 } return self;
5420 }
5421
5422 @end
5423 /* }}} */
5424 /* Source Cell {{{ */
5425 @interface SourceCell : UITableCell {
5426 UIImage *icon_;
5427 NSString *origin_;
5428 NSString *description_;
5429 NSString *label_;
5430 }
5431
5432 - (void) dealloc;
5433
5434 - (SourceCell *) initWithSource:(Source *)source;
5435
5436 @end
5437
5438 @implementation SourceCell
5439
5440 - (void) dealloc {
5441 [icon_ release];
5442 [origin_ release];
5443 [description_ release];
5444 [label_ release];
5445 [super dealloc];
5446 }
5447
5448 - (SourceCell *) initWithSource:(Source *)source {
5449 if ((self = [super init]) != nil) {
5450 if (icon_ == nil)
5451 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5452 if (icon_ == nil)
5453 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5454 icon_ = [icon_ retain];
5455
5456 origin_ = [[source name] retain];
5457 label_ = [[source uri] retain];
5458 description_ = [[source description] retain];
5459 } return self;
5460 }
5461
5462 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5463 if (icon_ != nil)
5464 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5465
5466 if (selected)
5467 UISetColor(White_);
5468
5469 if (!selected)
5470 UISetColor(Black_);
5471 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5472
5473 if (!selected)
5474 UISetColor(Blue_);
5475 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5476
5477 if (!selected)
5478 UISetColor(Gray_);
5479 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5480
5481 [super drawContentInRect:rect selected:selected];
5482 }
5483
5484 @end
5485 /* }}} */
5486 /* Source Table {{{ */
5487 @interface SourceTable : RVPage {
5488 _transient Database *database_;
5489 UISectionList *list_;
5490 NSMutableArray *sources_;
5491 UIActionSheet *alert_;
5492 int offset_;
5493
5494 NSString *href_;
5495 UIProgressHUD *hud_;
5496 NSError *error_;
5497
5498 //NSURLConnection *installer_;
5499 NSURLConnection *trivial_bz2_;
5500 NSURLConnection *trivial_gz_;
5501 //NSURLConnection *automatic_;
5502
5503 BOOL trivial_;
5504 }
5505
5506 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5507
5508 @end
5509
5510 @implementation SourceTable
5511
5512 - (void) _deallocConnection:(NSURLConnection *)connection {
5513 if (connection != nil) {
5514 [connection cancel];
5515 //[connection setDelegate:nil];
5516 [connection release];
5517 }
5518 }
5519
5520 - (void) dealloc {
5521 [[list_ table] setDelegate:nil];
5522 [list_ setDataSource:nil];
5523
5524 if (href_ != nil)
5525 [href_ release];
5526 if (hud_ != nil)
5527 [hud_ release];
5528 if (error_ != nil)
5529 [error_ release];
5530
5531 //[self _deallocConnection:installer_];
5532 [self _deallocConnection:trivial_gz_];
5533 [self _deallocConnection:trivial_bz2_];
5534 //[self _deallocConnection:automatic_];
5535
5536 [sources_ release];
5537 [list_ release];
5538 [super dealloc];
5539 }
5540
5541 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5542 return offset_ == 0 ? 1 : 2;
5543 }
5544
5545 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5546 switch (section + (offset_ == 0 ? 1 : 0)) {
5547 case 0: return UCLocalize("ENTERED_BY_USER");
5548 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5549
5550 default:
5551 _assert(false);
5552 return nil;
5553 }
5554 }
5555
5556 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5557 switch (section + (offset_ == 0 ? 1 : 0)) {
5558 case 0: return 0;
5559 case 1: return offset_;
5560
5561 default:
5562 _assert(false);
5563 return -1;
5564 }
5565 }
5566
5567 - (int) numberOfRowsInTable:(UITable *)table {
5568 return [sources_ count];
5569 }
5570
5571 - (float) table:(UITable *)table heightForRow:(int)row {
5572 Source *source = [sources_ objectAtIndex:row];
5573 return [source description] == nil ? 56 : 73;
5574 }
5575
5576 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5577 Source *source = [sources_ objectAtIndex:row];
5578 // XXX: weird warning, stupid selectors ;P
5579 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5580 }
5581
5582 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5583 return YES;
5584 }
5585
5586 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5587 return YES;
5588 }
5589
5590 - (void) tableRowSelected:(NSNotification*)notification {
5591 UITable *table([list_ table]);
5592 int row([table selectedRow]);
5593 if (row == INT_MAX)
5594 return;
5595
5596 Source *source = [sources_ objectAtIndex:row];
5597
5598 PackageTable *packages = [[[FilteredPackageTable alloc]
5599 initWithBook:book_
5600 database:database_
5601 title:[source label]
5602 filter:@selector(isVisibleInSource:)
5603 with:source
5604 ] autorelease];
5605
5606 [packages setDelegate:delegate_];
5607
5608 [book_ pushPage:packages];
5609 }
5610
5611 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5612 Source *source = [sources_ objectAtIndex:row];
5613 return [source record] != nil;
5614 }
5615
5616 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5617 [[list_ table] setDeleteConfirmationRow:row];
5618 }
5619
5620 - (void) table:(UITable *)table deleteRow:(int)row {
5621 Source *source = [sources_ objectAtIndex:row];
5622 [Sources_ removeObjectForKey:[source key]];
5623 [delegate_ syncData];
5624 }
5625
5626 - (void) complete {
5627 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5628 @"deb", @"Type",
5629 href_, @"URI",
5630 @"./", @"Distribution",
5631 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5632
5633 [delegate_ syncData];
5634 }
5635
5636 - (NSString *) getWarning {
5637 NSString *href(href_);
5638 NSRange colon([href rangeOfString:@"://"]);
5639 if (colon.location != NSNotFound)
5640 href = [href substringFromIndex:(colon.location + 3)];
5641 href = [href stringByAddingPercentEscapes];
5642 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5643 href = [href stringByCachingURLWithCurrentCDN];
5644
5645 NSURL *url([NSURL URLWithString:href]);
5646
5647 NSStringEncoding encoding;
5648 NSError *error(nil);
5649
5650 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5651 return [warning length] == 0 ? nil : warning;
5652 return nil;
5653 }
5654
5655 - (void) _endConnection:(NSURLConnection *)connection {
5656 NSURLConnection **field = NULL;
5657 if (connection == trivial_bz2_)
5658 field = &trivial_bz2_;
5659 else if (connection == trivial_gz_)
5660 field = &trivial_gz_;
5661 _assert(field != NULL);
5662 [connection release];
5663 *field = nil;
5664
5665 if (
5666 trivial_bz2_ == nil &&
5667 trivial_gz_ == nil
5668 ) {
5669 bool defer(false);
5670
5671 if (trivial_) {
5672 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5673 defer = true;
5674
5675 UIActionSheet *sheet = [[[UIActionSheet alloc]
5676 initWithTitle:UCLocalize("SOURCE_WARNING")
5677 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5678 defaultButtonIndex:0
5679 delegate:self
5680 context:@"warning"
5681 ] autorelease];
5682
5683 [sheet setNumberOfRows:1];
5684
5685 [sheet setBodyText:warning];
5686 [sheet popupAlertAnimated:YES];
5687 } else
5688 [self complete];
5689 } else if (error_ != nil) {
5690 UIActionSheet *sheet = [[[UIActionSheet alloc]
5691 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5692 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5693 defaultButtonIndex:0
5694 delegate:self
5695 context:@"urlerror"
5696 ] autorelease];
5697
5698 [sheet setBodyText:[error_ localizedDescription]];
5699 [sheet popupAlertAnimated:YES];
5700 } else {
5701 UIActionSheet *sheet = [[[UIActionSheet alloc]
5702 initWithTitle:UCLocalize("NOT_REPOSITORY")
5703 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5704 defaultButtonIndex:0
5705 delegate:self
5706 context:@"trivial"
5707 ] autorelease];
5708
5709 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5710 [sheet popupAlertAnimated:YES];
5711 }
5712
5713 [delegate_ setStatusBarShowsProgress:NO];
5714 [delegate_ removeProgressHUD:hud_];
5715
5716 [hud_ autorelease];
5717 hud_ = nil;
5718
5719 if (!defer) {
5720 [href_ release];
5721 href_ = nil;
5722 }
5723
5724 if (error_ != nil) {
5725 [error_ release];
5726 error_ = nil;
5727 }
5728 }
5729 }
5730
5731 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5732 switch ([response statusCode]) {
5733 case 200:
5734 trivial_ = YES;
5735 }
5736 }
5737
5738 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5739 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5740 if (error_ != nil)
5741 error_ = [error retain];
5742 [self _endConnection:connection];
5743 }
5744
5745 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5746 [self _endConnection:connection];
5747 }
5748
5749 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5750 NSMutableURLRequest *request = [NSMutableURLRequest
5751 requestWithURL:[NSURL URLWithString:href]
5752 cachePolicy:NSURLRequestUseProtocolCachePolicy
5753 timeoutInterval:20.0
5754 ];
5755
5756 [request setHTTPMethod:method];
5757
5758 if (Machine_ != NULL)
5759 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5760 if (UniqueID_ != nil)
5761 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5762
5763 if (Role_ != nil)
5764 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5765
5766 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5767 }
5768
5769 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5770 NSString *context([sheet context]);
5771
5772 if ([context isEqualToString:@"source"]) {
5773 switch (button) {
5774 case 1: {
5775 NSString *href = [[sheet textField] text];
5776
5777 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5778
5779 if (![href hasSuffix:@"/"])
5780 href_ = [href stringByAppendingString:@"/"];
5781 else
5782 href_ = href;
5783 href_ = [href_ retain];
5784
5785 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5786 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5787 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5788 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5789
5790 trivial_ = false;
5791
5792 hud_ = [[delegate_ addProgressHUD] retain];
5793 [hud_ setText:UCLocalize("VERIFYING_URL")];
5794 } break;
5795
5796 case 2:
5797 break;
5798
5799 default:
5800 _assert(false);
5801 }
5802
5803 [sheet dismiss];
5804 } else if ([context isEqualToString:@"trivial"])
5805 [sheet dismiss];
5806 else if ([context isEqualToString:@"urlerror"])
5807 [sheet dismiss];
5808 else if ([context isEqualToString:@"warning"]) {
5809 switch (button) {
5810 case 1:
5811 [self complete];
5812 break;
5813
5814 case 2:
5815 break;
5816
5817 default:
5818 _assert(false);
5819 }
5820
5821 [href_ release];
5822 href_ = nil;
5823
5824 [sheet dismiss];
5825 }
5826 }
5827
5828 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5829 if ((self = [super initWithBook:book]) != nil) {
5830 database_ = database;
5831 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5832
5833 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5834 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5835 [list_ setShouldHideHeaderInShortLists:NO];
5836
5837 [self addSubview:list_];
5838 [list_ setDataSource:self];
5839
5840 UITableColumn *column = [[UITableColumn alloc]
5841 initWithTitle:UCLocalize("NAME")
5842 identifier:@"name"
5843 width:[self frame].size.width
5844 ];
5845
5846 UITable *table = [list_ table];
5847 [table setSeparatorStyle:1];
5848 [table addTableColumn:column];
5849 [table setDelegate:self];
5850
5851 [self reloadData];
5852
5853 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5854 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5855 } return self;
5856 }
5857
5858 - (void) reloadData {
5859 pkgSourceList list;
5860 _assert(list.ReadMainList());
5861
5862 [sources_ removeAllObjects];
5863 [sources_ addObjectsFromArray:[database_ sources]];
5864 _trace();
5865 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5866 _trace();
5867
5868 int count = [sources_ count];
5869 for (offset_ = 0; offset_ != count; ++offset_) {
5870 Source *source = [sources_ objectAtIndex:offset_];
5871 if ([source record] == nil)
5872 break;
5873 }
5874
5875 [list_ reloadData];
5876 }
5877
5878 - (void) resetViewAnimated:(BOOL)animated {
5879 [list_ resetViewAnimated:animated];
5880 }
5881
5882 - (void) _leftButtonClicked {
5883 /*[book_ pushPage:[[[AddSourceView alloc]
5884 initWithBook:book_
5885 database:database_
5886 ] autorelease]];*/
5887
5888 UIActionSheet *sheet = [[[UIActionSheet alloc]
5889 initWithTitle:UCLocalize("ENTER_APT_URL")
5890 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
5891 defaultButtonIndex:0
5892 delegate:self
5893 context:@"source"
5894 ] autorelease];
5895
5896 [sheet setNumberOfRows:1];
5897
5898 [sheet addTextFieldWithValue:@"http://" label:@""];
5899
5900 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5901 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5902 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5903 [traits setKeyboardType:UIKeyboardTypeURL];
5904 // XXX: UIReturnKeyDone
5905 [traits setReturnKeyType:UIReturnKeyNext];
5906
5907 [sheet popupAlertAnimated:YES];
5908 }
5909
5910 - (void) _rightButtonClicked {
5911 UITable *table = [list_ table];
5912 BOOL editing = [table isRowDeletionEnabled];
5913 [table enableRowDeletion:!editing animated:YES];
5914 [book_ reloadButtonsForPage:self];
5915 }
5916
5917 - (NSString *) title {
5918 return UCLocalize("SOURCES");
5919 }
5920
5921 - (NSString *) leftButtonTitle {
5922 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
5923 }
5924
5925 - (id) rightButtonTitle {
5926 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
5927 }
5928
5929 - (UINavigationButtonStyle) rightButtonStyle {
5930 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5931 }
5932
5933 @end
5934 /* }}} */
5935
5936 /* Installed View {{{ */
5937 @interface InstalledView : RVPage {
5938 _transient Database *database_;
5939 FilteredPackageTable *packages_;
5940 BOOL expert_;
5941 }
5942
5943 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5944
5945 @end
5946
5947 @implementation InstalledView
5948
5949 - (void) dealloc {
5950 [packages_ release];
5951 [super dealloc];
5952 }
5953
5954 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5955 if ((self = [super initWithBook:book]) != nil) {
5956 database_ = database;
5957
5958 packages_ = [[FilteredPackageTable alloc]
5959 initWithBook:book
5960 database:database
5961 title:nil
5962 filter:@selector(isInstalledAndVisible:)
5963 with:[NSNumber numberWithBool:YES]
5964 ];
5965
5966 [self addSubview:packages_];
5967
5968 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5969 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5970 } return self;
5971 }
5972
5973 - (void) resetViewAnimated:(BOOL)animated {
5974 [packages_ resetViewAnimated:animated];
5975 }
5976
5977 - (void) reloadData {
5978 [packages_ reloadData];
5979 }
5980
5981 - (void) _rightButtonClicked {
5982 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5983 [packages_ reloadData];
5984 expert_ = !expert_;
5985 [book_ reloadButtonsForPage:self];
5986 }
5987
5988 - (NSString *) title {
5989 return UCLocalize("INSTALLED");
5990 }
5991
5992 - (NSString *) backButtonTitle {
5993 return UCLocalize("PACKAGES");
5994 }
5995
5996 - (id) rightButtonTitle {
5997 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
5998 }
5999
6000 - (UINavigationButtonStyle) rightButtonStyle {
6001 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6002 }
6003
6004 - (void) setDelegate:(id)delegate {
6005 [super setDelegate:delegate];
6006 [packages_ setDelegate:delegate];
6007 }
6008
6009 @end
6010 /* }}} */
6011
6012 /* Home View {{{ */
6013 @interface HomeView : CydiaBrowserView {
6014 }
6015
6016 @end
6017
6018 @implementation HomeView
6019
6020 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6021 NSString *context([sheet context]);
6022
6023 if ([context isEqualToString:@"about"])
6024 [sheet dismiss];
6025 else
6026 [super alertSheet:sheet buttonClicked:button];
6027 }
6028
6029 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6030 [super _setMoreHeaders:request];
6031 if (ChipID_ != nil)
6032 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6033 }
6034
6035 - (void) _leftButtonClicked {
6036 UIActionSheet *sheet = [[[UIActionSheet alloc]
6037 initWithTitle:UCLocalize("ABOUT_CYDIA")
6038 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6039 defaultButtonIndex:0
6040 delegate:self
6041 context:@"about"
6042 ] autorelease];
6043
6044 [sheet setBodyText:
6045 @"Copyright (C) 2008-2009\n"
6046 "Jay Freeman (saurik)\n"
6047 "saurik@saurik.com\n"
6048 "http://www.saurik.com/\n"
6049 "\n"
6050 "The Okori Group\n"
6051 "http://www.theokorigroup.com/\n"
6052 "\n"
6053 "College of Creative Studies,\n"
6054 "University of California,\n"
6055 "Santa Barbara\n"
6056 "http://www.ccs.ucsb.edu/"
6057 ];
6058
6059 [sheet popupAlertAnimated:YES];
6060 }
6061
6062 - (NSString *) leftButtonTitle {
6063 return UCLocalize("ABOUT");
6064 }
6065
6066 @end
6067 /* }}} */
6068 /* Manage View {{{ */
6069 @interface ManageView : CydiaBrowserView {
6070 }
6071
6072 @end
6073
6074 @implementation ManageView
6075
6076 - (NSString *) title {
6077 return UCLocalize("MANAGE");
6078 }
6079
6080 - (void) _leftButtonClicked {
6081 [delegate_ askForSettings];
6082 }
6083
6084 - (NSString *) leftButtonTitle {
6085 return UCLocalize("SETTINGS");
6086 }
6087
6088 #if !AlwaysReload
6089 - (id) _rightButtonTitle {
6090 return Queuing_ ? UCLocalize("QUEUE") : nil;
6091 }
6092
6093 - (UINavigationButtonStyle) rightButtonStyle {
6094 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6095 }
6096
6097 - (void) _rightButtonClicked {
6098 [delegate_ queue];
6099 }
6100 #endif
6101
6102 - (bool) isLoading {
6103 return false;
6104 }
6105
6106 @end
6107 /* }}} */
6108
6109 /* Cydia Book {{{ */
6110 @interface CYBook : RVBook <
6111 ProgressDelegate
6112 > {
6113 _transient Database *database_;
6114 UINavigationBar *overlay_;
6115 UINavigationBar *underlay_;
6116 UIProgressIndicator *indicator_;
6117 UITextLabel *prompt_;
6118 UIProgressBar *progress_;
6119 UINavigationButton *cancel_;
6120 bool updating_;
6121 }
6122
6123 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6124 - (void) update;
6125 - (BOOL) updating;
6126
6127 @end
6128
6129 @implementation CYBook
6130
6131 - (void) dealloc {
6132 [overlay_ release];
6133 [indicator_ release];
6134 [prompt_ release];
6135 [progress_ release];
6136 [cancel_ release];
6137 [super dealloc];
6138 }
6139
6140 - (NSString *) getTitleForPage:(RVPage *)page {
6141 return [super getTitleForPage:page];
6142 }
6143
6144 - (BOOL) updating {
6145 return updating_;
6146 }
6147
6148 - (void) update {
6149 [UIView beginAnimations:nil context:NULL];
6150
6151 CGRect ovrframe = [overlay_ frame];
6152 ovrframe.origin.y = 0;
6153 [overlay_ setFrame:ovrframe];
6154
6155 CGRect barframe = [navbar_ frame];
6156 barframe.origin.y += ovrframe.size.height;
6157 [navbar_ setFrame:barframe];
6158
6159 CGRect trnframe = [transition_ frame];
6160 trnframe.origin.y += ovrframe.size.height;
6161 trnframe.size.height -= ovrframe.size.height;
6162 [transition_ setFrame:trnframe];
6163
6164 [UIView endAnimations];
6165
6166 [indicator_ startAnimation];
6167 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6168 [progress_ setProgress:0];
6169
6170 updating_ = true;
6171 [overlay_ addSubview:cancel_];
6172
6173 [NSThread
6174 detachNewThreadSelector:@selector(_update)
6175 toTarget:self
6176 withObject:nil
6177 ];
6178 }
6179
6180 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6181 NSString *context([sheet context]);
6182
6183 if ([context isEqualToString:@"refresh"])
6184 [sheet dismiss];
6185 }
6186
6187 - (void) _update_:(NSString *)error {
6188 updating_ = false;
6189
6190 [indicator_ stopAnimation];
6191
6192 [UIView beginAnimations:nil context:NULL];
6193
6194 CGRect ovrframe = [overlay_ frame];
6195 ovrframe.origin.y = -ovrframe.size.height;
6196 [overlay_ setFrame:ovrframe];
6197
6198 CGRect barframe = [navbar_ frame];
6199 barframe.origin.y -= ovrframe.size.height;
6200 [navbar_ setFrame:barframe];
6201
6202 CGRect trnframe = [transition_ frame];
6203 trnframe.origin.y -= ovrframe.size.height;
6204 trnframe.size.height += ovrframe.size.height;
6205 [transition_ setFrame:trnframe];
6206
6207 [UIView commitAnimations];
6208
6209 if (error == nil)
6210 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6211 else {
6212 UIActionSheet *sheet = [[[UIActionSheet alloc]
6213 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6214 buttons:[NSArray arrayWithObjects:
6215 UCLocalize("OK"),
6216 nil]
6217 defaultButtonIndex:0
6218 delegate:self
6219 context:@"refresh"
6220 ] autorelease];
6221
6222 [sheet setBodyText:error];
6223 [sheet popupAlertAnimated:YES];
6224
6225 [self reloadButtons];
6226 }
6227 }
6228
6229 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6230 if ((self = [super initWithFrame:frame]) != nil) {
6231 database_ = database;
6232
6233 CGRect ovrrect = [navbar_ bounds];
6234 ovrrect.size.height = [UINavigationBar defaultSize].height;
6235 ovrrect.origin.y = -ovrrect.size.height;
6236
6237 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6238 [self addSubview:overlay_];
6239
6240 ovrrect.origin.y = frame.size.height;
6241 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6242 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6243 [self addSubview:underlay_];
6244
6245 [overlay_ setBarStyle:1];
6246 [underlay_ setBarStyle:1];
6247
6248 int barstyle = [overlay_ _barStyle:NO];
6249 bool ugly = barstyle == 0;
6250
6251 UIProgressIndicatorStyle style = ugly ?
6252 UIProgressIndicatorStyleMediumBrown :
6253 UIProgressIndicatorStyleMediumWhite;
6254
6255 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
6256 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6257 CGRect indrect = {{indoffset, indoffset}, indsize};
6258
6259 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6260 [indicator_ setStyle:style];
6261 [overlay_ addSubview:indicator_];
6262
6263 CGSize prmsize = {215, indsize.height + 4};
6264
6265 CGRect prmrect = {{
6266 indoffset * 2 + indsize.width,
6267 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6268 }, prmsize};
6269
6270 UIFont *font = [UIFont systemFontOfSize:15];
6271
6272 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6273
6274 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6275 [prompt_ setBackgroundColor:[UIColor clearColor]];
6276 [prompt_ setFont:font];
6277
6278 [overlay_ addSubview:prompt_];
6279
6280 CGSize prgsize = {75, 100};
6281
6282 CGRect prgrect = {{
6283 ovrrect.size.width - prgsize.width - 10,
6284 (ovrrect.size.height - prgsize.height) / 2
6285 } , prgsize};
6286
6287 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6288 [progress_ setStyle:0];
6289 [overlay_ addSubview:progress_];
6290
6291 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6292 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6293
6294 CGRect frame = [cancel_ frame];
6295 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6296 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6297 [cancel_ setFrame:frame];
6298
6299 [cancel_ setBarStyle:barstyle];
6300 } return self;
6301 }
6302
6303 - (void) _onCancel {
6304 updating_ = false;
6305 [cancel_ removeFromSuperview];
6306 }
6307
6308 - (void) _update { _pooled
6309 Status status;
6310 status.setDelegate(self);
6311
6312 NSString *error([database_ updateWithStatus:status]);
6313
6314 [self
6315 performSelectorOnMainThread:@selector(_update_:)
6316 withObject:error
6317 waitUntilDone:NO
6318 ];
6319 }
6320
6321 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6322 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6323 }
6324
6325 - (void) setProgressTitle:(NSString *)title {
6326 [self
6327 performSelectorOnMainThread:@selector(_setProgressTitle:)
6328 withObject:title
6329 waitUntilDone:YES
6330 ];
6331 }
6332
6333 - (void) setProgressPercent:(float)percent {
6334 [self
6335 performSelectorOnMainThread:@selector(_setProgressPercent:)
6336 withObject:[NSNumber numberWithFloat:percent]
6337 waitUntilDone:YES
6338 ];
6339 }
6340
6341 - (void) startProgress {
6342 }
6343
6344 - (void) addProgressOutput:(NSString *)output {
6345 [self
6346 performSelectorOnMainThread:@selector(_addProgressOutput:)
6347 withObject:output
6348 waitUntilDone:YES
6349 ];
6350 }
6351
6352 - (bool) isCancelling:(size_t)received {
6353 return !updating_;
6354 }
6355
6356 - (void) _setProgressTitle:(NSString *)title {
6357 [prompt_ setText:title];
6358 }
6359
6360 - (void) _setProgressPercent:(NSNumber *)percent {
6361 [progress_ setProgress:[percent floatValue]];
6362 }
6363
6364 - (void) _addProgressOutput:(NSString *)output {
6365 }
6366
6367 @end
6368 /* }}} */
6369 /* Cydia:// Protocol {{{ */
6370 @interface CydiaURLProtocol : NSURLProtocol {
6371 }
6372
6373 @end
6374
6375 @implementation CydiaURLProtocol
6376
6377 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6378 NSURL *url([request URL]);
6379 if (url == nil)
6380 return NO;
6381 NSString *scheme([[url scheme] lowercaseString]);
6382 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6383 return NO;
6384 return YES;
6385 }
6386
6387 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6388 return request;
6389 }
6390
6391 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6392 id<NSURLProtocolClient> client([self client]);
6393 if (icon == nil)
6394 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6395 else {
6396 NSData *data(UIImagePNGRepresentation(icon));
6397
6398 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6399 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6400 [client URLProtocol:self didLoadData:data];
6401 [client URLProtocolDidFinishLoading:self];
6402 }
6403 }
6404
6405 - (void) startLoading {
6406 id<NSURLProtocolClient> client([self client]);
6407 NSURLRequest *request([self request]);
6408
6409 NSURL *url([request URL]);
6410 NSString *href([url absoluteString]);
6411
6412 NSString *path([href substringFromIndex:8]);
6413 NSRange slash([path rangeOfString:@"/"]);
6414
6415 NSString *command;
6416 if (slash.location == NSNotFound) {
6417 command = path;
6418 path = nil;
6419 } else {
6420 command = [path substringToIndex:slash.location];
6421 path = [path substringFromIndex:(slash.location + 1)];
6422 }
6423
6424 Database *database([Database sharedInstance]);
6425
6426 if ([command isEqualToString:@"package-icon"]) {
6427 if (path == nil)
6428 goto fail;
6429 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6430 Package *package([database packageWithName:path]);
6431 if (package == nil)
6432 goto fail;
6433 UIImage *icon([package icon]);
6434 [self _returnPNGWithImage:icon forRequest:request];
6435 } else if ([command isEqualToString:@"source-icon"]) {
6436 if (path == nil)
6437 goto fail;
6438 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6439 NSString *source(Simplify(path));
6440 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6441 if (icon == nil)
6442 icon = [UIImage applicationImageNamed:@"unknown.png"];
6443 [self _returnPNGWithImage:icon forRequest:request];
6444 } else if ([command isEqualToString:@"uikit-image"]) {
6445 if (path == nil)
6446 goto fail;
6447 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6448 UIImage *icon(_UIImageWithName(path));
6449 [self _returnPNGWithImage:icon forRequest:request];
6450 } else if ([command isEqualToString:@"section-icon"]) {
6451 if (path == nil)
6452 goto fail;
6453 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6454 NSString *section(Simplify(path));
6455 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6456 if (icon == nil)
6457 icon = [UIImage applicationImageNamed:@"unknown.png"];
6458 [self _returnPNGWithImage:icon forRequest:request];
6459 } else fail: {
6460 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6461 }
6462 }
6463
6464 - (void) stopLoading {
6465 }
6466
6467 @end
6468 /* }}} */
6469
6470 /* Sections View {{{ */
6471 @interface SectionsView : RVPage {
6472 _transient Database *database_;
6473 NSMutableArray *sections_;
6474 NSMutableArray *filtered_;
6475 UITransitionView *transition_;
6476 UITable *list_;
6477 UIView *accessory_;
6478 BOOL editing_;
6479 }
6480
6481 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6482 - (void) reloadData;
6483 - (void) resetView;
6484
6485 @end
6486
6487 @implementation SectionsView
6488
6489 - (void) dealloc {
6490 [list_ setDataSource:nil];
6491 [list_ setDelegate:nil];
6492
6493 [sections_ release];
6494 [filtered_ release];
6495 [transition_ release];
6496 [list_ release];
6497 [accessory_ release];
6498 [super dealloc];
6499 }
6500
6501 - (int) numberOfRowsInTable:(UITable *)table {
6502 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6503 }
6504
6505 - (float) table:(UITable *)table heightForRow:(int)row {
6506 return 45;
6507 }
6508
6509 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6510 if (reusing == nil)
6511 reusing = [[[SectionCell alloc] init] autorelease];
6512 [(SectionCell *)reusing setSection:(editing_ ?
6513 [sections_ objectAtIndex:row] :
6514 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6515 ) editing:editing_];
6516 return reusing;
6517 }
6518
6519 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6520 return !editing_;
6521 }
6522
6523 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6524 return !editing_;
6525 }
6526
6527 - (void) tableRowSelected:(NSNotification *)notification {
6528 int row = [[notification object] selectedRow];
6529 if (row == INT_MAX)
6530 return;
6531
6532 Section *section;
6533 NSString *name;
6534 NSString *title;
6535
6536 if (row == 0) {
6537 section = nil;
6538 name = nil;
6539 title = UCLocalize("ALL_PACKAGES");
6540 } else {
6541 section = [filtered_ objectAtIndex:(row - 1)];
6542 name = [section name];
6543
6544 if (name != nil) {
6545 name = [NSString stringWithString:name];
6546 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6547 } else {
6548 name = @"";
6549 title = UCLocalize("NO_SECTION");
6550 }
6551 }
6552
6553 PackageTable *table = [[[FilteredPackageTable alloc]
6554 initWithBook:book_
6555 database:database_
6556 title:title
6557 filter:@selector(isVisiblyUninstalledInSection:)
6558 with:name
6559 ] autorelease];
6560
6561 [table setDelegate:delegate_];
6562
6563 [book_ pushPage:table];
6564 }
6565
6566 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6567 if ((self = [super initWithBook:book]) != nil) {
6568 database_ = database;
6569
6570 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6571 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6572
6573 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6574 [self addSubview:transition_];
6575
6576 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6577 [transition_ transition:0 toView:list_];
6578
6579 UITableColumn *column = [[[UITableColumn alloc]
6580 initWithTitle:UCLocalize("NAME")
6581 identifier:@"name"
6582 width:[self frame].size.width
6583 ] autorelease];
6584
6585 [list_ setDataSource:self];
6586 [list_ setSeparatorStyle:1];
6587 [list_ addTableColumn:column];
6588 [list_ setDelegate:self];
6589 [list_ setReusesTableCells:YES];
6590
6591 [self reloadData];
6592
6593 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6594 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6595 } return self;
6596 }
6597
6598 - (void) reloadData {
6599 NSArray *packages = [database_ packages];
6600
6601 [sections_ removeAllObjects];
6602 [filtered_ removeAllObjects];
6603
6604 #if 0
6605 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6606 SectionMap sections;
6607 sections.resize(64);
6608 #else
6609 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6610 #endif
6611
6612 _trace();
6613 for (Package *package in packages) {
6614 NSString *name([package section]);
6615 NSString *key(name == nil ? @"" : name);
6616
6617 #if 0
6618 Section **section;
6619
6620 _profile(SectionsView$reloadData$Section)
6621 section = &sections[key];
6622 if (*section == nil) {
6623 _profile(SectionsView$reloadData$Section$Allocate)
6624 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6625 _end
6626 }
6627 _end
6628
6629 [*section addToCount];
6630
6631 _profile(SectionsView$reloadData$Filter)
6632 if (![package valid] || ![package uninstalled] || ![package visible])
6633 continue;
6634 _end
6635
6636 [*section addToRow];
6637 #else
6638 Section *section;
6639
6640 _profile(SectionsView$reloadData$Section)
6641 section = [sections objectForKey:key];
6642 if (section == nil) {
6643 _profile(SectionsView$reloadData$Section$Allocate)
6644 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6645 [sections setObject:section forKey:key];
6646 _end
6647 }
6648 _end
6649
6650 [section addToCount];
6651
6652 _profile(SectionsView$reloadData$Filter)
6653 if (![package valid] || ![package uninstalled] || ![package visible])
6654 continue;
6655 _end
6656
6657 [section addToRow];
6658 #endif
6659 }
6660 _trace();
6661
6662 #if 0
6663 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6664 [sections_ addObject:i->second];
6665 #else
6666 [sections_ addObjectsFromArray:[sections allValues]];
6667 #endif
6668
6669 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6670
6671 for (Section *section in sections_) {
6672 size_t count([section row]);
6673 if (count == 0)
6674 continue;
6675
6676 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6677 [section setCount:count];
6678 [filtered_ addObject:section];
6679 }
6680
6681 [list_ reloadData];
6682 _trace();
6683 }
6684
6685 - (void) resetView {
6686 if (editing_)
6687 [self _rightButtonClicked];
6688 }
6689
6690 - (void) resetViewAnimated:(BOOL)animated {
6691 [list_ resetViewAnimated:animated];
6692 }
6693
6694 - (void) _rightButtonClicked {
6695 if ((editing_ = !editing_))
6696 [list_ reloadData];
6697 else
6698 [delegate_ updateData];
6699 [book_ reloadTitleForPage:self];
6700 [book_ reloadButtonsForPage:self];
6701 }
6702
6703 - (NSString *) title {
6704 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("INSTALL_BY_SECTION");
6705 }
6706
6707 - (NSString *) backButtonTitle {
6708 return UCLocalize("SECTIONS");
6709 }
6710
6711 - (id) rightButtonTitle {
6712 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6713 }
6714
6715 - (UINavigationButtonStyle) rightButtonStyle {
6716 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6717 }
6718
6719 - (UIView *) accessoryView {
6720 return accessory_;
6721 }
6722
6723 @end
6724 /* }}} */
6725 /* Changes View {{{ */
6726 @interface ChangesView : RVPage {
6727 _transient Database *database_;
6728 NSMutableArray *packages_;
6729 NSMutableArray *sections_;
6730 UITableView *list_;
6731 unsigned upgrades_;
6732 }
6733
6734 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6735 - (void) reloadData;
6736
6737 @end
6738
6739 @implementation ChangesView
6740
6741 - (void) dealloc {
6742 [list_ setDelegate:nil];
6743 [list_ setDataSource:nil];
6744
6745 [packages_ release];
6746 [sections_ release];
6747 [list_ release];
6748 [super dealloc];
6749 }
6750
6751 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6752 NSInteger count([sections_ count]);
6753 return count == 0 ? 1 : count;
6754 }
6755
6756 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6757 if ([sections_ count] == 0)
6758 return nil;
6759 return [[sections_ objectAtIndex:section] name];
6760 }
6761
6762 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6763 if ([sections_ count] == 0)
6764 return 0;
6765 return [[sections_ objectAtIndex:section] count];
6766 }
6767
6768 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6769 Section *section([sections_ objectAtIndex:[path section]]);
6770 NSInteger row([path row]);
6771 return [packages_ objectAtIndex:([section row] + row)];
6772 }
6773
6774 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6775 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6776 if (cell == nil)
6777 cell = [[[PackageCell alloc] init] autorelease];
6778 [cell setPackage:[self packageAtIndexPath:path]];
6779 return cell;
6780 }
6781
6782 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6783 return 73;
6784 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6785 }
6786
6787 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6788 Package *package([self packageAtIndexPath:path]);
6789 PackageView *view([delegate_ packageView]);
6790 [view setDelegate:delegate_];
6791 [view setPackage:package];
6792 [book_ pushPage:view];
6793 return path;
6794 }
6795
6796 - (void) _leftButtonClicked {
6797 [(CYBook *)book_ update];
6798 [self reloadButtons];
6799 }
6800
6801 - (void) _rightButtonClicked {
6802 [delegate_ distUpgrade];
6803 }
6804
6805 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6806 if ((self = [super initWithBook:book]) != nil) {
6807 database_ = database;
6808
6809 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6810 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6811
6812 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6813 [self addSubview:list_];
6814
6815 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6816 [list_ setDataSource:self];
6817 [list_ setDelegate:self];
6818 //[list_ setSectionListStyle:1];
6819
6820 [self reloadData];
6821
6822 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6823 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6824 } return self;
6825 }
6826
6827 - (void) reloadData {
6828 NSArray *packages = [database_ packages];
6829
6830 [packages_ removeAllObjects];
6831 [sections_ removeAllObjects];
6832
6833 _trace();
6834 for (Package *package in packages)
6835 if (
6836 [package uninstalled] && [package valid] && [package visible] ||
6837 [package upgradableAndEssential:YES]
6838 )
6839 [packages_ addObject:package];
6840
6841 _trace();
6842 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6843 _trace();
6844
6845 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6846 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6847 Section *section = nil;
6848 NSDate *last = nil;
6849
6850 upgrades_ = 0;
6851 bool unseens = false;
6852
6853 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6854
6855 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6856 Package *package = [packages_ objectAtIndex:offset];
6857
6858 BOOL uae = [package upgradableAndEssential:YES];
6859
6860 if (!uae) {
6861 unseens = true;
6862 NSDate *seen;
6863
6864 _profile(ChangesView$reloadData$Remember)
6865 seen = [package seen];
6866 _end
6867
6868 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6869 last = seen;
6870
6871 NSString *name;
6872 if (seen == nil)
6873 name = UCLocalize("UNKNOWN");
6874 else {
6875 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6876 [name autorelease];
6877 }
6878
6879 _profile(ChangesView$reloadData$Allocate)
6880 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6881 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6882 [sections_ addObject:section];
6883 _end
6884 }
6885
6886 [section addToCount];
6887 } else if ([package ignored])
6888 [ignored addToCount];
6889 else {
6890 ++upgrades_;
6891 [upgradable addToCount];
6892 }
6893 }
6894 _trace();
6895
6896 CFRelease(formatter);
6897
6898 if (unseens) {
6899 Section *last = [sections_ lastObject];
6900 size_t count = [last count];
6901 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6902 [sections_ removeLastObject];
6903 }
6904
6905 if ([ignored count] != 0)
6906 [sections_ insertObject:ignored atIndex:0];
6907 if (upgrades_ != 0)
6908 [sections_ insertObject:upgradable atIndex:0];
6909
6910 [list_ reloadData];
6911 [self reloadButtons];
6912 }
6913
6914 - (void) resetViewAnimated:(BOOL)animated {
6915 [list_ resetViewAnimated:animated];
6916 }
6917
6918 - (NSString *) leftButtonTitle {
6919 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
6920 }
6921
6922 - (id) rightButtonTitle {
6923 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6924 }
6925
6926 - (NSString *) title {
6927 return UCLocalize("CHANGES");
6928 }
6929
6930 @end
6931 /* }}} */
6932 /* Search View {{{ */
6933 @protocol SearchViewDelegate
6934 - (void) showKeyboard:(BOOL)show;
6935 @end
6936
6937 @interface SearchView : RVPage {
6938 UIView *accessory_;
6939 UISearchField *field_;
6940 FilteredPackageTable *table_;
6941 UIView *dimmed_;
6942 bool reload_;
6943 }
6944
6945 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6946 - (void) reloadData;
6947
6948 @end
6949
6950 @implementation SearchView
6951
6952 - (void) dealloc {
6953 [field_ setDelegate:nil];
6954
6955 [accessory_ release];
6956 [field_ release];
6957 [table_ release];
6958 [dimmed_ release];
6959 [super dealloc];
6960 }
6961
6962 - (void) _showKeyboard:(BOOL)show {
6963 CGSize keysize = [UIKeyboard defaultSize];
6964 CGRect keydown = [book_ pageBounds];
6965 CGRect keyup = keydown;
6966 keyup.size.height -= keysize.height - ButtonBarHeight_;
6967
6968 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6969
6970 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6971 [animation setSignificantRectFields:8];
6972
6973 if (show) {
6974 [animation setStartFrame:keydown];
6975 [animation setEndFrame:keyup];
6976 } else {
6977 [animation setStartFrame:keyup];
6978 [animation setEndFrame:keydown];
6979 }
6980
6981 UIAnimator *animator = [UIAnimator sharedAnimator];
6982
6983 [animator
6984 addAnimations:[NSArray arrayWithObjects:animation, nil]
6985 withDuration:(KeyboardTime_ - delay)
6986 start:!show
6987 ];
6988
6989 if (show)
6990 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6991
6992 [delegate_ showKeyboard:show];
6993 }
6994
6995 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6996 [self _showKeyboard:YES];
6997 }
6998
6999 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7000 [self _showKeyboard:NO];
7001 }
7002
7003 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7004 if (reload_) {
7005 NSString *text([field_ text]);
7006 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7007 [self reloadData];
7008 reload_ = false;
7009 }
7010 }
7011
7012 - (void) textFieldClearButtonPressed:(UITextField *)field {
7013 reload_ = true;
7014 }
7015
7016 - (void) keyboardInputShouldDelete:(id)input {
7017 reload_ = true;
7018 }
7019
7020 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7021 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7022 reload_ = true;
7023 return YES;
7024 } else {
7025 [field_ resignFirstResponder];
7026 return NO;
7027 }
7028 }
7029
7030 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7031 if ((self = [super initWithBook:book]) != nil) {
7032 CGRect pageBounds = [book_ pageBounds];
7033
7034 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7035 CGColor dimmed(space_, 0, 0, 0, 0.5);
7036 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7037
7038 table_ = [[FilteredPackageTable alloc]
7039 initWithBook:book
7040 database:database
7041 title:nil
7042 filter:@selector(isUnfilteredAndSearchedForBy:)
7043 with:nil
7044 ];
7045
7046 [table_ setShouldHideHeaderInShortLists:NO];
7047 [self addSubview:table_];
7048
7049 CGRect cnfrect = {{7, 38}, {17, 18}};
7050
7051 CGRect area;
7052
7053 area.origin.x = 10;
7054 area.origin.y = 1;
7055
7056 area.size.width = [self bounds].size.width - area.origin.x * 2;
7057 area.size.height = [UISearchField defaultHeight];
7058
7059 field_ = [[UISearchField alloc] initWithFrame:area];
7060
7061 UIFont *font = [UIFont systemFontOfSize:16];
7062 [field_ setFont:font];
7063
7064 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7065 [field_ setDelegate:self];
7066
7067 [field_ setPaddingTop:5];
7068
7069 UITextInputTraits *traits([field_ textInputTraits]);
7070 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7071 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7072 [traits setReturnKeyType:UIReturnKeySearch];
7073
7074 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7075
7076 accessory_ = [[UIView alloc] initWithFrame:accrect];
7077 [accessory_ addSubview:field_];
7078
7079 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7080 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7081 } return self;
7082 }
7083
7084 - (void) resetViewAnimated:(BOOL)animated {
7085 [table_ resetViewAnimated:animated];
7086 }
7087
7088 - (void) _reloadData {
7089 }
7090
7091 - (void) reloadData {
7092 [table_ setObject:[field_ text]];
7093 _profile(SearchView$reloadData)
7094 [table_ reloadData];
7095 _end
7096 PrintTimes();
7097 [table_ resetCursor];
7098 }
7099
7100 - (UIView *) accessoryView {
7101 return accessory_;
7102 }
7103
7104 - (NSString *) title {
7105 return nil;
7106 }
7107
7108 - (NSString *) backButtonTitle {
7109 return UCLocalize("SEARCH");
7110 }
7111
7112 - (void) setDelegate:(id)delegate {
7113 [table_ setDelegate:delegate];
7114 [super setDelegate:delegate];
7115 }
7116
7117 @end
7118 /* }}} */
7119 /* Settings View {{{ */
7120 @interface SettingsView : RVPage {
7121 _transient Database *database_;
7122 NSString *name_;
7123 Package *package_;
7124 UIPreferencesTable *table_;
7125 _UISwitchSlider *subscribedSwitch_;
7126 _UISwitchSlider *ignoredSwitch_;
7127 UIPreferencesControlTableCell *subscribedCell_;
7128 UIPreferencesControlTableCell *ignoredCell_;
7129 }
7130
7131 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7132
7133 @end
7134
7135 @implementation SettingsView
7136
7137 - (void) dealloc {
7138 [table_ setDataSource:nil];
7139
7140 [name_ release];
7141 if (package_ != nil)
7142 [package_ release];
7143 [table_ release];
7144 [subscribedSwitch_ release];
7145 [ignoredSwitch_ release];
7146 [subscribedCell_ release];
7147 [ignoredCell_ release];
7148 [super dealloc];
7149 }
7150
7151 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7152 if (package_ == nil)
7153 return 0;
7154
7155 return 2;
7156 }
7157
7158 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7159 if (package_ == nil)
7160 return nil;
7161
7162 switch (group) {
7163 case 0: return nil;
7164 case 1: return nil;
7165
7166 default: _assert(false);
7167 }
7168
7169 return nil;
7170 }
7171
7172 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7173 if (package_ == nil)
7174 return NO;
7175
7176 switch (group) {
7177 case 0: return NO;
7178 case 1: return YES;
7179
7180 default: _assert(false);
7181 }
7182
7183 return NO;
7184 }
7185
7186 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7187 if (package_ == nil)
7188 return 0;
7189
7190 switch (group) {
7191 case 0: return 1;
7192 case 1: return 1;
7193
7194 default: _assert(false);
7195 }
7196
7197 return 0;
7198 }
7199
7200 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7201 if (package_ == nil)
7202 return;
7203
7204 _UISwitchSlider *slider([cell control]);
7205 BOOL value([slider value] != 0);
7206 NSMutableDictionary *metadata([package_ metadata]);
7207
7208 BOOL before;
7209 if (NSNumber *number = [metadata objectForKey:key])
7210 before = [number boolValue];
7211 else
7212 before = NO;
7213
7214 if (value != before) {
7215 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7216 Changed_ = true;
7217 [delegate_ updateData];
7218 }
7219 }
7220
7221 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7222 [self onSomething:cell withKey:@"IsSubscribed"];
7223 }
7224
7225 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7226 [self onSomething:cell withKey:@"IsIgnored"];
7227 }
7228
7229 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7230 if (package_ == nil)
7231 return nil;
7232
7233 switch (group) {
7234 case 0: switch (row) {
7235 case 0:
7236 return subscribedCell_;
7237 case 1:
7238 return ignoredCell_;
7239 default: _assert(false);
7240 } break;
7241
7242 case 1: switch (row) {
7243 case 0: {
7244 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7245 [cell setShowSelection:NO];
7246 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7247 return cell;
7248 }
7249
7250 default: _assert(false);
7251 } break;
7252
7253 default: _assert(false);
7254 }
7255
7256 return nil;
7257 }
7258
7259 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7260 if ((self = [super initWithBook:book])) {
7261 database_ = database;
7262 name_ = [package retain];
7263
7264 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7265 [self addSubview:table_];
7266
7267 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7268 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7269
7270 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7271 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7272
7273 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7274 [subscribedCell_ setShowSelection:NO];
7275 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7276 [subscribedCell_ setControl:subscribedSwitch_];
7277
7278 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7279 [ignoredCell_ setShowSelection:NO];
7280 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7281 [ignoredCell_ setControl:ignoredSwitch_];
7282
7283 [table_ setDataSource:self];
7284 [self reloadData];
7285 } return self;
7286 }
7287
7288 - (void) resetViewAnimated:(BOOL)animated {
7289 [table_ resetViewAnimated:animated];
7290 }
7291
7292 - (void) reloadData {
7293 if (package_ != nil)
7294 [package_ autorelease];
7295 package_ = [database_ packageWithName:name_];
7296 if (package_ != nil) {
7297 [package_ retain];
7298 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7299 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7300 }
7301
7302 [table_ reloadData];
7303 }
7304
7305 - (NSString *) title {
7306 return UCLocalize("SETTINGS");
7307 }
7308
7309 @end
7310 /* }}} */
7311
7312 /* Signature View {{{ */
7313 @interface SignatureView : CydiaBrowserView {
7314 _transient Database *database_;
7315 NSString *package_;
7316 }
7317
7318 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7319
7320 @end
7321
7322 @implementation SignatureView
7323
7324 - (void) dealloc {
7325 [package_ release];
7326 [super dealloc];
7327 }
7328
7329 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7330 // XXX: dude!
7331 [super webView:sender didClearWindowObject:window forFrame:frame];
7332 }
7333
7334 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7335 if ((self = [super initWithBook:book]) != nil) {
7336 database_ = database;
7337 package_ = [package retain];
7338 [self reloadData];
7339 } return self;
7340 }
7341
7342 - (void) resetViewAnimated:(BOOL)animated {
7343 }
7344
7345 - (void) reloadData {
7346 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7347 }
7348
7349 @end
7350 /* }}} */
7351
7352 @interface Cydia : UIApplication <
7353 ConfirmationViewDelegate,
7354 ProgressViewDelegate,
7355 SearchViewDelegate,
7356 CydiaDelegate
7357 > {
7358 UIWindow *window_;
7359
7360 UIView *underlay_;
7361 UIView *overlay_;
7362 CYBook *book_;
7363 UIToolbar *toolbar_;
7364
7365 RVBook *confirm_;
7366
7367 NSMutableArray *essential_;
7368 NSMutableArray *broken_;
7369
7370 Database *database_;
7371 ProgressView *progress_;
7372
7373 unsigned tag_;
7374
7375 UIKeyboard *keyboard_;
7376 UIProgressHUD *hud_;
7377
7378 SectionsView *sections_;
7379 ChangesView *changes_;
7380 ManageView *manage_;
7381 SearchView *search_;
7382
7383 #if RecyclePackageViews
7384 NSMutableArray *details_;
7385 #endif
7386 }
7387
7388 @end
7389
7390 @implementation Cydia
7391
7392 - (void) _loaded {
7393 if ([broken_ count] != 0) {
7394 int count = [broken_ count];
7395
7396 UIActionSheet *sheet = [[[UIActionSheet alloc]
7397 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7398 buttons:[NSArray arrayWithObjects:
7399 UCLocalize("FORCIBLY_CLEAR"),
7400 UCLocalize("TEMPORARY_IGNORE"),
7401 nil]
7402 defaultButtonIndex:0
7403 delegate:self
7404 context:@"fixhalf"
7405 ] autorelease];
7406
7407 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7408 [sheet popupAlertAnimated:YES];
7409 } else if (!Ignored_ && [essential_ count] != 0) {
7410 int count = [essential_ count];
7411
7412 UIActionSheet *sheet = [[[UIActionSheet alloc]
7413 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7414 buttons:[NSArray arrayWithObjects:
7415 UCLocalize("UPGRADE_ESSENTIAL"),
7416 UCLocalize("COMPLETE_UPGRADE"),
7417 UCLocalize("TEMPORARY_IGNORE"),
7418 nil]
7419 defaultButtonIndex:0
7420 delegate:self
7421 context:@"upgrade"
7422 ] autorelease];
7423
7424 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7425 [sheet popupAlertAnimated:YES];
7426 }
7427 }
7428
7429 - (void) _saveConfig {
7430 if (Changed_) {
7431 _trace();
7432 NSString *error(nil);
7433 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7434 _trace();
7435 NSError *error(nil);
7436 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7437 NSLog(@"failure to save metadata data: %@", error);
7438 _trace();
7439 } else {
7440 NSLog(@"failure to serialize metadata: %@", error);
7441 return;
7442 }
7443
7444 Changed_ = false;
7445 }
7446 }
7447
7448 - (void) _updateData {
7449 [self _saveConfig];
7450
7451 /* XXX: this is just stupid */
7452 if (tag_ != 2 && sections_ != nil)
7453 [sections_ reloadData];
7454 if (tag_ != 3 && changes_ != nil)
7455 [changes_ reloadData];
7456 if (tag_ != 5 && search_ != nil)
7457 [search_ reloadData];
7458
7459 [book_ reloadData];
7460 }
7461
7462 - (void) _reloadData {
7463 UIView *block();
7464
7465 static bool loaded(false);
7466 UIProgressHUD *hud([self addProgressHUD]);
7467 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7468 loaded = true;
7469
7470 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7471 _trace();
7472
7473 [self removeProgressHUD:hud];
7474
7475 size_t changes(0);
7476
7477 [essential_ removeAllObjects];
7478 [broken_ removeAllObjects];
7479
7480 NSArray *packages = [database_ packages];
7481 for (Package *package in packages) {
7482 if ([package half])
7483 [broken_ addObject:package];
7484 if ([package upgradableAndEssential:NO]) {
7485 if ([package essential])
7486 [essential_ addObject:package];
7487 ++changes;
7488 }
7489 }
7490
7491 if (changes != 0) {
7492 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7493 [toolbar_ setBadgeValue:badge forButton:3];
7494 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7495 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7496 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7497 [self setApplicationBadge:badge];
7498 else
7499 [self setApplicationBadgeString:badge];
7500 } else {
7501 [toolbar_ setBadgeValue:nil forButton:3];
7502 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7503 [toolbar_ setBadgeAnimated:NO forButton:3];
7504 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7505 [self removeApplicationBadge];
7506 else // XXX: maybe use setApplicationBadgeString also?
7507 [self setApplicationIconBadgeNumber:0];
7508 }
7509
7510 Queuing_ = false;
7511 [toolbar_ setBadgeValue:nil forButton:4];
7512
7513 [self _updateData];
7514
7515 // XXX: what is this line of code for?
7516 if ([packages count] == 0);
7517 else if (Loaded_ || ManualRefresh) loaded:
7518 [self _loaded];
7519 else {
7520 Loaded_ = YES;
7521
7522 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7523 NSTimeInterval interval([update timeIntervalSinceNow]);
7524 if (interval <= 0 && interval > -600)
7525 goto loaded;
7526 }
7527
7528 [book_ update];
7529 }
7530 }
7531
7532 - (void) updateData {
7533 [database_ setVisible];
7534 [self _updateData];
7535 }
7536
7537 - (void) update_ {
7538 [database_ update];
7539 }
7540
7541 - (void) syncData {
7542 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7543 _assert(file != NULL);
7544
7545 NSArray *keys = [Sources_ allKeys];
7546
7547 for (NSString *key in keys) {
7548 NSDictionary *source = [Sources_ objectForKey:key];
7549
7550 fprintf(file, "%s %s %s\n",
7551 [[source objectForKey:@"Type"] UTF8String],
7552 [[source objectForKey:@"URI"] UTF8String],
7553 [[source objectForKey:@"Distribution"] UTF8String]
7554 );
7555 }
7556
7557 fclose(file);
7558
7559 [self _saveConfig];
7560
7561 [progress_
7562 detachNewThreadSelector:@selector(update_)
7563 toTarget:self
7564 withObject:nil
7565 title:UCLocalize("UPDATING_SOURCES")
7566 ];
7567 }
7568
7569 - (void) reloadData {
7570 @synchronized (self) {
7571 if (confirm_ == nil)
7572 [self _reloadData];
7573 }
7574 }
7575
7576 - (void) resolve {
7577 pkgProblemResolver *resolver = [database_ resolver];
7578
7579 resolver->InstallProtect();
7580 if (!resolver->Resolve(true))
7581 _error->Discard();
7582 }
7583
7584 - (void) popUpBook:(RVBook *)book {
7585 [underlay_ popSubview:book];
7586 }
7587
7588 - (CGRect) popUpBounds {
7589 return [underlay_ bounds];
7590 }
7591
7592 - (void) perform {
7593 [database_ prepare];
7594
7595 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7596 [confirm_ setDelegate:self];
7597
7598 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7599 [page setDelegate:self];
7600
7601 [confirm_ setPage:page];
7602 [self popUpBook:confirm_];
7603 }
7604
7605 - (void) queue {
7606 @synchronized (self) {
7607 [self perform];
7608 }
7609 }
7610
7611 - (void) clearPackage:(Package *)package {
7612 @synchronized (self) {
7613 [package clear];
7614 [self resolve];
7615 [self perform];
7616 }
7617 }
7618
7619 - (void) installPackage:(Package *)package {
7620 @synchronized (self) {
7621 [package install];
7622 [self resolve];
7623 [self perform];
7624 }
7625 }
7626
7627 - (void) removePackage:(Package *)package {
7628 @synchronized (self) {
7629 [package remove];
7630 [self resolve];
7631 [self perform];
7632 }
7633 }
7634
7635 - (void) distUpgrade {
7636 @synchronized (self) {
7637 [database_ upgrade];
7638 [self perform];
7639 }
7640 }
7641
7642 - (void) cancel {
7643 [self slideUp:[[[UIActionSheet alloc]
7644 initWithTitle:nil
7645 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7646 defaultButtonIndex:1
7647 delegate:self
7648 context:@"cancel"
7649 ] autorelease]];
7650 }
7651
7652 - (void) complete {
7653 @synchronized (self) {
7654 [self _reloadData];
7655
7656 if (confirm_ != nil) {
7657 [confirm_ release];
7658 confirm_ = nil;
7659 }
7660 }
7661 }
7662
7663 - (void) confirm {
7664 [overlay_ removeFromSuperview];
7665 reload_ = true;
7666
7667 [progress_
7668 detachNewThreadSelector:@selector(perform)
7669 toTarget:database_
7670 withObject:nil
7671 title:UCLocalize("RUNNING")
7672 ];
7673 }
7674
7675 - (void) progressViewIsComplete:(ProgressView *)progress {
7676 if (confirm_ != nil) {
7677 [underlay_ addSubview:overlay_];
7678 [confirm_ popFromSuperviewAnimated:NO];
7679 }
7680
7681 [self complete];
7682 }
7683
7684 - (void) setPage:(RVPage *)page {
7685 [page resetViewAnimated:NO];
7686 [page setDelegate:self];
7687 [book_ setPage:page];
7688 }
7689
7690 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7691 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7692 [browser loadURL:url];
7693 return browser;
7694 }
7695
7696 - (void) _setHomePage {
7697 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7698 }
7699
7700 - (SectionsView *) sectionsView {
7701 if (sections_ == nil)
7702 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7703 return sections_;
7704 }
7705
7706 - (void) buttonBarItemTapped:(id)sender {
7707 unsigned tag = [sender tag];
7708 if (tag == tag_) {
7709 [book_ resetViewAnimated:YES];
7710 return;
7711 } else if (tag_ == 2 && tag != 2)
7712 [[self sectionsView] resetView];
7713
7714 switch (tag) {
7715 case 1: [self _setHomePage]; break;
7716
7717 case 2: [self setPage:[self sectionsView]]; break;
7718 case 3: [self setPage:changes_]; break;
7719 case 4: [self setPage:manage_]; break;
7720 case 5: [self setPage:search_]; break;
7721
7722 default: _assert(false);
7723 }
7724
7725 tag_ = tag;
7726 }
7727
7728 - (void) applicationWillSuspend {
7729 [database_ clean];
7730 [super applicationWillSuspend];
7731 }
7732
7733 - (void) askForSettings {
7734 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7735
7736 UIActionSheet *role = [[[UIActionSheet alloc]
7737 initWithTitle:UCLocalize("WHO_ARE_YOU")
7738 buttons:[NSArray arrayWithObjects:
7739 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7740 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7741 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7742 nil]
7743 defaultButtonIndex:-1
7744 delegate:self
7745 context:@"role"
7746 ] autorelease];
7747
7748 [role setBodyText:UCLocalize("ROLE_EX")];
7749 [role popupAlertAnimated:YES];
7750 }
7751
7752 - (void) setPackageView:(PackageView *)view {
7753 WebThreadLock();
7754 [view setPackage:nil];
7755 #if RecyclePackageViews
7756 if ([details_ count] < 3)
7757 [details_ addObject:view];
7758 #endif
7759 WebThreadUnlock();
7760 }
7761
7762 - (PackageView *) _packageView {
7763 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7764 }
7765
7766 - (PackageView *) packageView {
7767 #if RecyclePackageViews
7768 PackageView *view;
7769 size_t count([details_ count]);
7770
7771 if (count == 0) {
7772 view = [self _packageView];
7773 renew:
7774 [details_ addObject:[self _packageView]];
7775 } else {
7776 view = [[[details_ lastObject] retain] autorelease];
7777 [details_ removeLastObject];
7778 if (count == 1)
7779 goto renew;
7780 }
7781
7782 return view;
7783 #else
7784 return [self _packageView];
7785 #endif
7786 }
7787
7788 - (void) finish {
7789 if (hud_ != nil) {
7790 [self setStatusBarShowsProgress:NO];
7791 [self removeProgressHUD:hud_];
7792
7793 [hud_ autorelease];
7794 hud_ = nil;
7795
7796 pid_t pid = ExecFork();
7797 if (pid == 0) {
7798 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7799 perror("launchctl stop");
7800 }
7801
7802 return;
7803 }
7804
7805 if (Role_ == nil) {
7806 [self askForSettings];
7807 return;
7808 }
7809
7810 _trace();
7811 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7812
7813 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7814 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7815 0, 0, screenrect.size.width, screenrect.size.height - 48
7816 ) database:database_];
7817
7818 [book_ setDelegate:self];
7819
7820 [overlay_ addSubview:book_];
7821
7822 NSArray *buttonitems = [NSArray arrayWithObjects:
7823 [NSDictionary dictionaryWithObjectsAndKeys:
7824 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7825 @"home-up.png", kUIButtonBarButtonInfo,
7826 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7827 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7828 self, kUIButtonBarButtonTarget,
7829 @"Cydia", kUIButtonBarButtonTitle,
7830 @"0", kUIButtonBarButtonType,
7831 nil],
7832
7833 [NSDictionary dictionaryWithObjectsAndKeys:
7834 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7835 @"install-up.png", kUIButtonBarButtonInfo,
7836 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7837 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7838 self, kUIButtonBarButtonTarget,
7839 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7840 @"0", kUIButtonBarButtonType,
7841 nil],
7842
7843 [NSDictionary dictionaryWithObjectsAndKeys:
7844 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7845 @"changes-up.png", kUIButtonBarButtonInfo,
7846 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7847 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7848 self, kUIButtonBarButtonTarget,
7849 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
7850 @"0", kUIButtonBarButtonType,
7851 nil],
7852
7853 [NSDictionary dictionaryWithObjectsAndKeys:
7854 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7855 @"manage-up.png", kUIButtonBarButtonInfo,
7856 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7857 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7858 self, kUIButtonBarButtonTarget,
7859 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
7860 @"0", kUIButtonBarButtonType,
7861 nil],
7862
7863 [NSDictionary dictionaryWithObjectsAndKeys:
7864 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7865 @"search-up.png", kUIButtonBarButtonInfo,
7866 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7867 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7868 self, kUIButtonBarButtonTarget,
7869 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
7870 @"0", kUIButtonBarButtonType,
7871 nil],
7872 nil];
7873
7874 toolbar_ = [[UIToolbar alloc]
7875 initInView:overlay_
7876 withFrame:CGRectMake(
7877 0, screenrect.size.height - ButtonBarHeight_,
7878 screenrect.size.width, ButtonBarHeight_
7879 )
7880 withItemList:buttonitems
7881 ];
7882
7883 [toolbar_ setDelegate:self];
7884 [toolbar_ setBarStyle:1];
7885 [toolbar_ setButtonBarTrackingMode:2];
7886
7887 int buttons[5] = {1, 2, 3, 4, 5};
7888 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7889 [toolbar_ showButtonGroup:0 withDuration:0];
7890
7891 for (int i = 0; i != 5; ++i)
7892 [[toolbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7893 i * 64 + 2, 1, 60, ButtonBarHeight_
7894 )];
7895
7896 [toolbar_ showSelectionForButton:1];
7897 [overlay_ addSubview:toolbar_];
7898
7899 [UIKeyboard initImplementationNow];
7900 CGSize keysize = [UIKeyboard defaultSize];
7901 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7902 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7903 [overlay_ addSubview:keyboard_];
7904
7905 [underlay_ addSubview:overlay_];
7906
7907 [self reloadData];
7908
7909 [self sectionsView];
7910 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7911 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7912
7913 manage_ = (ManageView *) [[self
7914 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7915 withClass:[ManageView class]
7916 ] retain];
7917
7918 #if RecyclePackageViews
7919 details_ = [[NSMutableArray alloc] initWithCapacity:4];
7920 [details_ addObject:[self _packageView]];
7921 [details_ addObject:[self _packageView]];
7922 #endif
7923
7924 PrintTimes();
7925
7926 [self _setHomePage];
7927 }
7928
7929 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7930 NSString *context([sheet context]);
7931
7932 if ([context isEqualToString:@"missing"])
7933 [sheet dismiss];
7934 else if ([context isEqualToString:@"cancel"]) {
7935 bool clear;
7936
7937 switch (button) {
7938 case 1:
7939 clear = false;
7940 break;
7941
7942 case 2:
7943 clear = true;
7944 break;
7945
7946 default:
7947 _assert(false);
7948 }
7949
7950 [sheet dismiss];
7951
7952 @synchronized (self) {
7953 if (clear)
7954 [self _reloadData];
7955 else {
7956 Queuing_ = true;
7957 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
7958 [book_ reloadData];
7959 }
7960
7961 if (confirm_ != nil) {
7962 [confirm_ release];
7963 confirm_ = nil;
7964 }
7965 }
7966 } else if ([context isEqualToString:@"fixhalf"]) {
7967 switch (button) {
7968 case 1:
7969 @synchronized (self) {
7970 for (Package *broken in broken_) {
7971 [broken remove];
7972
7973 NSString *id = [broken id];
7974 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7975 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7976 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7977 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7978 }
7979
7980 [self resolve];
7981 [self perform];
7982 }
7983 break;
7984
7985 case 2:
7986 [broken_ removeAllObjects];
7987 [self _loaded];
7988 break;
7989
7990 default:
7991 _assert(false);
7992 }
7993
7994 [sheet dismiss];
7995 } else if ([context isEqualToString:@"role"]) {
7996 switch (button) {
7997 case 1: Role_ = @"User"; break;
7998 case 2: Role_ = @"Hacker"; break;
7999 case 3: Role_ = @"Developer"; break;
8000
8001 default:
8002 Role_ = nil;
8003 _assert(false);
8004 }
8005
8006 bool reset = Settings_ != nil;
8007
8008 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8009 Role_, @"Role",
8010 nil];
8011
8012 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8013
8014 Changed_ = true;
8015
8016 [sheet dismiss];
8017
8018 if (reset)
8019 [self updateData];
8020 else
8021 [self finish];
8022 } else if ([context isEqualToString:@"upgrade"]) {
8023 switch (button) {
8024 case 1:
8025 @synchronized (self) {
8026 for (Package *essential in essential_)
8027 [essential install];
8028
8029 [self resolve];
8030 [self perform];
8031 }
8032 break;
8033
8034 case 2:
8035 [self distUpgrade];
8036 break;
8037
8038 case 3:
8039 Ignored_ = YES;
8040 break;
8041
8042 default:
8043 _assert(false);
8044 }
8045
8046 [sheet dismiss];
8047 }
8048 }
8049
8050 - (void) reorganize { _pooled
8051 system("/usr/libexec/cydia/free.sh");
8052 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
8053 }
8054
8055 - (void) applicationSuspend:(__GSEvent *)event {
8056 if (hud_ == nil && ![progress_ isRunning])
8057 [super applicationSuspend:event];
8058 }
8059
8060 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8061 if (hud_ == nil)
8062 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8063 }
8064
8065 - (void) _setSuspended:(BOOL)value {
8066 if (hud_ == nil)
8067 [super _setSuspended:value];
8068 }
8069
8070 - (UIProgressHUD *) addProgressHUD {
8071 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8072 [window_ setUserInteractionEnabled:NO];
8073 [hud show:YES];
8074 [progress_ addSubview:hud];
8075 return hud;
8076 }
8077
8078 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8079 [hud show:NO];
8080 [hud removeFromSuperview];
8081 [window_ setUserInteractionEnabled:YES];
8082 }
8083
8084 - (RVPage *) pageForPackage:(NSString *)name {
8085 if (Package *package = [database_ packageWithName:name]) {
8086 PackageView *view([self packageView]);
8087 [view setPackage:package];
8088 return view;
8089 } else {
8090 UIActionSheet *sheet = [[[UIActionSheet alloc]
8091 initWithTitle:UCLocalize("CANNOT_LOCATE_PACKAGE")
8092 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
8093 defaultButtonIndex:0
8094 delegate:self
8095 context:@"missing"
8096 ] autorelease];
8097
8098 [sheet setBodyText:[NSString stringWithFormat:UCLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
8099
8100 [sheet popupAlertAnimated:YES];
8101 return nil;
8102 }
8103 }
8104
8105 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8106 if (tag != NULL)
8107 tag = 0;
8108
8109 NSString *href([url absoluteString]);
8110 if ([href hasPrefix:@"apptapp://package/"])
8111 return [self pageForPackage:[href substringFromIndex:18]];
8112
8113 NSString *scheme([[url scheme] lowercaseString]);
8114 if (![scheme isEqualToString:@"cydia"])
8115 return nil;
8116 NSString *path([url absoluteString]);
8117 if ([path length] < 8)
8118 return nil;
8119 path = [path substringFromIndex:8];
8120 if (![path hasPrefix:@"/"])
8121 path = [@"/" stringByAppendingString:path];
8122
8123 if ([path isEqualToString:@"/add-source"])
8124 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8125 else if ([path isEqualToString:@"/storage"])
8126 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8127 else if ([path isEqualToString:@"/sources"])
8128 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8129 else if ([path isEqualToString:@"/packages"])
8130 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8131 else if ([path hasPrefix:@"/url/"])
8132 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8133 else if ([path hasPrefix:@"/launch/"])
8134 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8135 else if ([path hasPrefix:@"/package-settings/"])
8136 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8137 else if ([path hasPrefix:@"/package-signature/"])
8138 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8139 else if ([path hasPrefix:@"/package/"])
8140 return [self pageForPackage:[path substringFromIndex:9]];
8141 else if ([path hasPrefix:@"/files/"]) {
8142 NSString *name = [path substringFromIndex:7];
8143
8144 if (Package *package = [database_ packageWithName:name]) {
8145 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8146 [files setPackage:package];
8147 return files;
8148 }
8149 }
8150
8151 return nil;
8152 }
8153
8154 - (void) applicationOpenURL:(NSURL *)url {
8155 [super applicationOpenURL:url];
8156 int tag;
8157 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8158 [self setPage:page];
8159 [toolbar_ showSelectionForButton:tag];
8160 tag_ = tag;
8161 }
8162 }
8163
8164 - (void) applicationDidFinishLaunching:(id)unused {
8165 [BrowserView _initialize];
8166
8167 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8168
8169 Font12_ = [[UIFont systemFontOfSize:12] retain];
8170 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8171 Font14_ = [[UIFont systemFontOfSize:14] retain];
8172 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8173 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8174
8175 tag_ = 1;
8176
8177 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8178 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8179
8180 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8181 [window_ orderFront:self];
8182 [window_ makeKey:self];
8183 [window_ setHidden:NO];
8184
8185 database_ = [Database sharedInstance];
8186
8187 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8188 [database_ setDelegate:progress_];
8189 [window_ setContentView:progress_];
8190
8191 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8192 [progress_ setContentView:underlay_];
8193
8194 [progress_ resetView];
8195
8196 if (
8197 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8198 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8199 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8200 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8201 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8202 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8203 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8204 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8205 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8206 false
8207 ) {
8208 [self setIdleTimerDisabled:YES];
8209
8210 hud_ = [[self addProgressHUD] retain];
8211 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8212
8213 [self setStatusBarShowsProgress:YES];
8214
8215 [NSThread
8216 detachNewThreadSelector:@selector(reorganize)
8217 toTarget:self
8218 withObject:nil
8219 ];
8220 } else
8221 [self finish];
8222 }
8223
8224 - (void) showKeyboard:(BOOL)show {
8225 CGSize keysize([UIKeyboard defaultSize]);
8226 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8227 CGRect keyup(keydown);
8228 keyup.origin.y -= keysize.height;
8229
8230 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8231 [animation setSignificantRectFields:2];
8232
8233 if (show) {
8234 [animation setStartFrame:keydown];
8235 [animation setEndFrame:keyup];
8236 [keyboard_ activate];
8237 } else {
8238 [animation setStartFrame:keyup];
8239 [animation setEndFrame:keydown];
8240 [keyboard_ deactivate];
8241 }
8242
8243 [[UIAnimator sharedAnimator]
8244 addAnimations:[NSArray arrayWithObjects:animation, nil]
8245 withDuration:KeyboardTime_
8246 start:YES
8247 ];
8248 }
8249
8250 - (void) slideUp:(UIActionSheet *)alert {
8251 [alert presentSheetInView:overlay_];
8252 }
8253
8254 @end
8255
8256 /*IMP alloc_;
8257 id Alloc_(id self, SEL selector) {
8258 id object = alloc_(self, selector);
8259 lprintf("[%s]A-%p\n", self->isa->name, object);
8260 return object;
8261 }*/
8262
8263 /*IMP dealloc_;
8264 id Dealloc_(id self, SEL selector) {
8265 id object = dealloc_(self, selector);
8266 lprintf("[%s]D-%p\n", self->isa->name, object);
8267 return object;
8268 }*/
8269
8270 Class $WebDefaultUIKitDelegate;
8271
8272 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8273 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8274 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8275 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8276 }
8277
8278 int main(int argc, char *argv[]) { _pooled
8279 _trace();
8280
8281 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8282
8283 /* Library Hacks {{{ */
8284 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8285
8286 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8287 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8288 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8289 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8290 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8291 }
8292 /* }}} */
8293 /* Set Locale {{{ */
8294 Locale_ = CFLocaleCopyCurrent();
8295 Languages_ = [NSLocale preferredLanguages];
8296 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8297 //NSLog(@"%@", [Languages_ description]);
8298 const char *lang;
8299 if (Languages_ == nil || [Languages_ count] == 0)
8300 lang = NULL;
8301 else
8302 lang = [[Languages_ objectAtIndex:0] UTF8String];
8303 setenv("LANG", lang, true);
8304 //std::setlocale(LC_ALL, lang);
8305 NSLog(@"Setting Language: %s", lang);
8306 /* }}} */
8307
8308 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8309
8310 /* Parse Arguments {{{ */
8311 bool substrate(false);
8312
8313 if (argc != 0) {
8314 char **args(argv);
8315 int arge(1);
8316
8317 for (int argi(1); argi != argc; ++argi)
8318 if (strcmp(argv[argi], "--") == 0) {
8319 arge = argi;
8320 argv[argi] = argv[0];
8321 argv += argi;
8322 argc -= argi;
8323 break;
8324 }
8325
8326 for (int argi(1); argi != arge; ++argi)
8327 if (strcmp(args[argi], "--substrate") == 0)
8328 substrate = true;
8329 else
8330 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8331 }
8332 /* }}} */
8333
8334 App_ = [[NSBundle mainBundle] bundlePath];
8335 Home_ = NSHomeDirectory();
8336 Advanced_ = YES;
8337
8338 setuid(0);
8339 setgid(0);
8340
8341 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8342 alloc_ = alloc->method_imp;
8343 alloc->method_imp = (IMP) &Alloc_;*/
8344
8345 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8346 dealloc_ = dealloc->method_imp;
8347 dealloc->method_imp = (IMP) &Dealloc_;*/
8348
8349 /* System Information {{{ */
8350 size_t size;
8351
8352 int maxproc;
8353 size = sizeof(maxproc);
8354 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8355 perror("sysctlbyname(\"kern.maxproc\", ?)");
8356 else if (maxproc < 64) {
8357 maxproc = 64;
8358 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8359 perror("sysctlbyname(\"kern.maxproc\", #)");
8360 }
8361
8362 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8363 char *osversion = new char[size];
8364 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8365 perror("sysctlbyname(\"kern.osversion\", ?)");
8366 else
8367 System_ = [NSString stringWithUTF8String:osversion];
8368
8369 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8370 char *machine = new char[size];
8371 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8372 perror("sysctlbyname(\"hw.machine\", ?)");
8373 else
8374 Machine_ = machine;
8375
8376 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8377 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8378 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8379 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8380 CFRelease(serial);
8381 }
8382
8383 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8384 NSData *data((NSData *) ecid);
8385 size_t length([data length]);
8386 uint8_t bytes[length];
8387 [data getBytes:bytes];
8388 char string[length * 2 + 1];
8389 for (size_t i(0); i != length; ++i)
8390 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8391 ChipID_ = [NSString stringWithUTF8String:string];
8392 CFRelease(ecid);
8393 }
8394
8395 IOObjectRelease(service);
8396 }
8397 }
8398
8399 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8400
8401 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8402 Build_ = [system objectForKey:@"ProductBuildVersion"];
8403 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8404 Product_ = [info objectForKey:@"SafariProductVersion"];
8405 Safari_ = [info objectForKey:@"CFBundleVersion"];
8406 }
8407 /* }}} */
8408 /* Load Database {{{ */
8409 _trace();
8410 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8411 _trace();
8412 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8413 _trace();
8414
8415 if (Metadata_ == NULL)
8416 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8417 else {
8418 Settings_ = [Metadata_ objectForKey:@"Settings"];
8419
8420 Packages_ = [Metadata_ objectForKey:@"Packages"];
8421 Sections_ = [Metadata_ objectForKey:@"Sections"];
8422 Sources_ = [Metadata_ objectForKey:@"Sources"];
8423 }
8424
8425 if (Settings_ != nil)
8426 Role_ = [Settings_ objectForKey:@"Role"];
8427
8428 if (Packages_ == nil) {
8429 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8430 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8431 }
8432
8433 if (Sections_ == nil) {
8434 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8435 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8436 }
8437
8438 if (Sources_ == nil) {
8439 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8440 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8441 }
8442 /* }}} */
8443
8444 #if RecycleWebViews
8445 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8446 #endif
8447
8448 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8449
8450 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8451 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8452 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8453 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8454
8455 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8456 unlink("/tmp/.cydia.fw");
8457 goto firmware;
8458 } else if (access("/User", F_OK) != 0) {
8459 firmware:
8460 _trace();
8461 system("/usr/libexec/cydia/firmware.sh");
8462 _trace();
8463 }
8464
8465 _assert([[NSFileManager defaultManager]
8466 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8467 withIntermediateDirectories:YES
8468 attributes:nil
8469 error:NULL
8470 ]);
8471
8472 if (access("/tmp/cydia.chk", F_OK) == 0) {
8473 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8474 _assert(errno == ENOENT);
8475 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8476 _assert(errno == ENOENT);
8477 }
8478
8479 /* APT Initialization {{{ */
8480 _assert(pkgInitConfig(*_config));
8481 _assert(pkgInitSystem(*_config, _system));
8482
8483 if (lang != NULL)
8484 _config->Set("APT::Acquire::Translation", lang);
8485 _config->Set("Acquire::http::Timeout", 15);
8486 _config->Set("Acquire::http::MaxParallel", 3);
8487 /* }}} */
8488 /* Color Choices {{{ */
8489 space_ = CGColorSpaceCreateDeviceRGB();
8490
8491 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8492 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8493 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8494 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8495 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8496 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8497 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8498 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8499 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8500
8501 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8502 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8503 /* }}}*/
8504 /* UIKit Configuration {{{ */
8505 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8506 if ($GSFontSetUseLegacyFontMetrics != NULL)
8507 $GSFontSetUseLegacyFontMetrics(YES);
8508
8509 UIKeyboardDisableAutomaticAppearance();
8510 /* }}} */
8511
8512 _trace();
8513 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8514
8515 CGColorSpaceRelease(space_);
8516 CFRelease(Locale_);
8517
8518 return value;
8519 }