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