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