]> git.saurik.com Git - cydia.git/blob - Cydia.mm
Fix the ZodTTD/MacCiti Mac OS Roman Name: bug.
[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 if (lhn == NULL)
1936 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1937 else if (rhn == NULL)
1938 return NSOrderedDescending;
1939
1940 _profile(PackageNameCompare$NumbersLast)
1941 if (!lhi.empty() && !rhi.empty()) {
1942 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1943 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1944 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1945 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1946 return lha ? NSOrderedAscending : NSOrderedDescending;
1947 }
1948 _end
1949
1950 CFIndex length = CFStringGetLength(lhn);
1951
1952 _profile(PackageNameCompare$Compare)
1953 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1954 _end
1955 _end
1956 }
1957
1958 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1959 return PackageNameCompare(*lhs, *rhs, context);
1960 }
1961
1962 struct PackageNameOrdering :
1963 std::binary_function<Package *, Package *, bool>
1964 {
1965 _finline bool operator ()(Package *lhs, Package *rhs) const {
1966 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1967 }
1968 };
1969
1970 @implementation Package
1971
1972 - (NSString *) description {
1973 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1974 }
1975
1976 - (void) dealloc {
1977 if (source_ != nil)
1978 [source_ release];
1979 if (section$_ != nil)
1980 [section$_ release];
1981
1982 if (latest_ != nil)
1983 [latest_ release];
1984
1985 if (sponsor$_ != nil)
1986 [sponsor$_ release];
1987 if (author$_ != nil)
1988 [author$_ release];
1989 if (tags_ != nil)
1990 [tags_ release];
1991 if (role_ != nil)
1992 [role_ release];
1993
1994 if (relationships_ != nil)
1995 [relationships_ release];
1996 if (metadata_ != nil)
1997 [metadata_ release];
1998
1999 [super dealloc];
2000 }
2001
2002 + (NSString *) webScriptNameForSelector:(SEL)selector {
2003 if (selector == @selector(hasTag:))
2004 return @"hasTag";
2005 else
2006 return nil;
2007 }
2008
2009 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2010 return [self webScriptNameForSelector:selector] == nil;
2011 }
2012
2013 + (NSArray *) _attributeKeys {
2014 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];
2015 }
2016
2017 - (NSArray *) attributeKeys {
2018 return [[self class] _attributeKeys];
2019 }
2020
2021 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2022 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2023 }
2024
2025 - (void) parse {
2026 if (parsed_)
2027 return;
2028 parsed_ = true;
2029 if (file_.end())
2030 return;
2031
2032 _profile(Package$parse)
2033 pkgRecords::Parser *parser;
2034
2035 _profile(Package$parse$Lookup)
2036 parser = &[database_ records]->Lookup(file_);
2037 _end
2038
2039 CYString website;
2040
2041 _profile(Package$parse$Find)
2042 struct {
2043 const char *name_;
2044 CYString *value_;
2045 } names[] = {
2046 {"icon", &icon_},
2047 {"depiction", &depiction_},
2048 {"homepage", &homepage_},
2049 {"website", &website},
2050 {"bugs", &bugs_},
2051 {"support", &support_},
2052 {"sponsor", &sponsor_},
2053 {"author", &author_},
2054 };
2055
2056 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2057 const char *start, *end;
2058
2059 if (parser->Find(names[i].name_, start, end)) {
2060 CYString &value(*names[i].value_);
2061 _profile(Package$parse$Value)
2062 value.set(pool_, start, end - start);
2063 _end
2064 }
2065 }
2066 _end
2067
2068 _profile(Package$parse$Tagline)
2069 const char *start, *end;
2070 if (parser->ShortDesc(start, end)) {
2071 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2072 if (stop == NULL)
2073 stop = end;
2074 while (stop != start && stop[-1] == '\r')
2075 --stop;
2076 tagline_.set(pool_, start, stop - start);
2077 }
2078 _end
2079
2080 _profile(Package$parse$Retain)
2081 if (homepage_.empty())
2082 homepage_ = website;
2083 if (homepage_ == depiction_)
2084 homepage_.clear();
2085 _end
2086 _end
2087 }
2088
2089 - (void) setVisible {
2090 visible_ = required_ && [self hasSupportingRole] && [self unfiltered];
2091 }
2092
2093 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2094 if ((self = [super init]) != nil) {
2095 _profile(Package$initWithVersion)
2096 @synchronized (database) {
2097 era_ = [database era];
2098 pool_ = pool;
2099
2100 version_ = version;
2101 iterator_ = version.ParentPkg();
2102 database_ = database;
2103
2104 _profile(Package$initWithVersion$Latest)
2105 latest_ = (NSString *) StripVersion(version_.VerStr());
2106 _end
2107
2108 pkgCache::VerIterator current;
2109 _profile(Package$initWithVersion$Versions)
2110 current = iterator_.CurrentVer();
2111 if (!current.end())
2112 installed_.set(pool_, StripVersion_(current.VerStr()));
2113
2114 if (!version_.end())
2115 file_ = version_.FileList();
2116 else {
2117 pkgCache &cache([database_ cache]);
2118 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2119 }
2120 _end
2121
2122 _profile(Package$initWithVersion$Name)
2123 id_.set(pool_, iterator_.Name());
2124 name_.set(pool, iterator_.Display());
2125 _end
2126
2127 if (!file_.end()) {
2128 _profile(Package$initWithVersion$Source)
2129 source_ = [database_ getSource:file_.File()];
2130 if (source_ != nil)
2131 [source_ retain];
2132 cached_ = true;
2133 _end
2134 }
2135
2136 required_ = true;
2137
2138 _profile(Package$initWithVersion$Tags)
2139 pkgCache::TagIterator tag(iterator_.TagList());
2140 if (!tag.end()) {
2141 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2142 do {
2143 const char *name(tag.Name());
2144 [tags_ addObject:(NSString *)CFCString(name)];
2145 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2146 role_ = (NSString *) CFCString(name + 6);
2147 if (required_ && strncmp(name, "require::", 9) == 0 && (
2148 true
2149 ))
2150 required_ = false;
2151 ++tag;
2152 } while (!tag.end());
2153 }
2154 _end
2155
2156 bool changed(false);
2157 NSString *key([id_ lowercaseString]);
2158
2159 _profile(Package$initWithVersion$Metadata)
2160 metadata_ = [Packages_ objectForKey:key];
2161
2162 if (metadata_ == nil) {
2163 firstSeen_ = now_;
2164
2165 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2166 firstSeen_, @"FirstSeen",
2167 latest_, @"LastVersion",
2168 nil] mutableCopy];
2169
2170 changed = true;
2171 } else {
2172 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2173 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2174
2175 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2176 subscribed_ = [subscribed boolValue];
2177
2178 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2179
2180 if (firstSeen_ == nil) {
2181 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2182 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2183 changed = true;
2184 }
2185
2186 if (version == nil) {
2187 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2188 changed = true;
2189 } else {
2190 if (![version isEqualToString:latest_]) {
2191 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2192 lastSeen_ = now_;
2193 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2194 changed = true;
2195 } }
2196 }
2197
2198 metadata_ = [metadata_ retain];
2199
2200 if (changed) {
2201 [Packages_ setObject:metadata_ forKey:key];
2202 Changed_ = true;
2203 }
2204 _end
2205
2206 _profile(Package$initWithVersion$Section)
2207 section_.set(pool_, iterator_.Section());
2208 _end
2209
2210 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2211 [self setVisible];
2212 } _end } return self;
2213 }
2214
2215 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2216 @synchronized ([Database class]) {
2217 pkgCache::VerIterator version;
2218
2219 _profile(Package$packageWithIterator$GetCandidateVer)
2220 version = [database policy]->GetCandidateVer(iterator);
2221 _end
2222
2223 if (version.end())
2224 return nil;
2225
2226 return [[[Package alloc]
2227 initWithVersion:version
2228 withZone:zone
2229 inPool:pool
2230 database:database
2231 ] autorelease];
2232 } }
2233
2234 - (pkgCache::PkgIterator) iterator {
2235 return iterator_;
2236 }
2237
2238 - (NSString *) section {
2239 if (section$_ == nil) {
2240 if (section_.empty())
2241 return nil;
2242
2243 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2244 NSString *name(section_);
2245
2246 lookup:
2247 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2248 if (NSString *rename = [value objectForKey:@"Rename"]) {
2249 name = rename;
2250 goto lookup;
2251 }
2252
2253 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2254 } return section$_;
2255 }
2256
2257 - (NSString *) simpleSection {
2258 if (NSString *section = [self section])
2259 return Simplify(section);
2260 else
2261 return nil;
2262 }
2263
2264 - (NSString *) longSection {
2265 return LocalizeSection([self section]);
2266 }
2267
2268 - (NSString *) shortSection {
2269 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2270 }
2271
2272 - (NSString *) uri {
2273 return nil;
2274 #if 0
2275 pkgIndexFile *index;
2276 pkgCache::PkgFileIterator file(file_.File());
2277 if (![database_ list].FindIndex(file, index))
2278 return nil;
2279 return [NSString stringWithUTF8String:iterator_->Path];
2280 //return [NSString stringWithUTF8String:file.Site()];
2281 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2282 #endif
2283 }
2284
2285 - (Address *) maintainer {
2286 if (file_.end())
2287 return nil;
2288 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2289 const std::string &maintainer(parser->Maintainer());
2290 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2291 }
2292
2293 - (size_t) size {
2294 return version_.end() ? 0 : version_->InstalledSize;
2295 }
2296
2297 - (NSString *) longDescription {
2298 if (file_.end())
2299 return nil;
2300 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2301 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2302
2303 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2304 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2305 if ([lines count] < 2)
2306 return nil;
2307
2308 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2309 for (size_t i(1), e([lines count]); i != e; ++i) {
2310 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2311 [trimmed addObject:trim];
2312 }
2313
2314 return [trimmed componentsJoinedByString:@"\n"];
2315 }
2316
2317 - (NSString *) shortDescription {
2318 return tagline_;
2319 }
2320
2321 - (unichar) index {
2322 _profile(Package$index)
2323 CFStringRef name((CFStringRef) [self name]);
2324 if (CFStringGetLength(name) == 0)
2325 return '#';
2326 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2327 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2328 return '#';
2329 return toupper(character);
2330 _end
2331 }
2332
2333 - (NSMutableDictionary *) metadata {
2334 return metadata_;
2335 }
2336
2337 - (NSDate *) seen {
2338 if (subscribed_ && lastSeen_ != nil)
2339 return lastSeen_;
2340 return firstSeen_;
2341 }
2342
2343 - (BOOL) subscribed {
2344 return subscribed_;
2345 }
2346
2347 - (BOOL) ignored {
2348 NSDictionary *metadata([self metadata]);
2349 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2350 return [ignored boolValue];
2351 else
2352 return false;
2353 }
2354
2355 - (NSString *) latest {
2356 return latest_;
2357 }
2358
2359 - (NSString *) installed {
2360 return installed_;
2361 }
2362
2363 - (BOOL) uninstalled {
2364 return installed_.empty();
2365 }
2366
2367 - (BOOL) valid {
2368 return !version_.end();
2369 }
2370
2371 - (BOOL) upgradableAndEssential:(BOOL)essential {
2372 _profile(Package$upgradableAndEssential)
2373 pkgCache::VerIterator current(iterator_.CurrentVer());
2374 if (current.end())
2375 return essential && essential_ && visible_;
2376 else
2377 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2378 _end
2379 }
2380
2381 - (BOOL) essential {
2382 return essential_;
2383 }
2384
2385 - (BOOL) broken {
2386 return [database_ cache][iterator_].InstBroken();
2387 }
2388
2389 - (BOOL) unfiltered {
2390 NSString *section([self section]);
2391 return section == nil || isSectionVisible(section);
2392 }
2393
2394 - (BOOL) visible {
2395 return visible_;
2396 }
2397
2398 - (BOOL) half {
2399 unsigned char current(iterator_->CurrentState);
2400 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2401 }
2402
2403 - (BOOL) halfConfigured {
2404 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2405 }
2406
2407 - (BOOL) halfInstalled {
2408 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2409 }
2410
2411 - (BOOL) hasMode {
2412 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2413 return state.Mode != pkgDepCache::ModeKeep;
2414 }
2415
2416 - (NSString *) mode {
2417 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2418
2419 switch (state.Mode) {
2420 case pkgDepCache::ModeDelete:
2421 if ((state.iFlags & pkgDepCache::Purge) != 0)
2422 return @"PURGE";
2423 else
2424 return @"REMOVE";
2425 case pkgDepCache::ModeKeep:
2426 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2427 return @"REINSTALL";
2428 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2429 return nil;*/
2430 else
2431 return nil;
2432 case pkgDepCache::ModeInstall:
2433 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2434 return @"REINSTALL";
2435 else*/ switch (state.Status) {
2436 case -1:
2437 return @"DOWNGRADE";
2438 case 0:
2439 return @"INSTALL";
2440 case 1:
2441 return @"UPGRADE";
2442 case 2:
2443 return @"NEW_INSTALL";
2444 _nodefault
2445 }
2446 _nodefault
2447 }
2448 }
2449
2450 - (NSString *) id {
2451 return id_;
2452 }
2453
2454 - (NSString *) name {
2455 return name_.empty() ? id_ : name_;
2456 }
2457
2458 - (UIImage *) icon {
2459 NSString *section = [self simpleSection];
2460
2461 UIImage *icon(nil);
2462 if (!icon_.empty())
2463 if ([icon_ hasPrefix:@"file:///"])
2464 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2465 if (icon == nil) if (section != nil)
2466 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2467 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2468 if ([dicon hasPrefix:@"file:///"])
2469 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2470 if (icon == nil)
2471 icon = [UIImage applicationImageNamed:@"unknown.png"];
2472 return icon;
2473 }
2474
2475 - (NSString *) homepage {
2476 return homepage_;
2477 }
2478
2479 - (NSString *) depiction {
2480 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2481 }
2482
2483 - (Address *) sponsor {
2484 if (sponsor$_ == nil) {
2485 if (sponsor_.empty())
2486 return nil;
2487 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2488 } return sponsor$_;
2489 }
2490
2491 - (Address *) author {
2492 if (author$_ == nil) {
2493 if (author_.empty())
2494 return nil;
2495 author$_ = [[Address addressWithString:author_] retain];
2496 } return author$_;
2497 }
2498
2499 - (NSString *) support {
2500 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2501 }
2502
2503 - (NSArray *) files {
2504 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2505 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2506
2507 std::ifstream fin;
2508 fin.open([path UTF8String]);
2509 if (!fin.is_open())
2510 return nil;
2511
2512 std::string line;
2513 while (std::getline(fin, line))
2514 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2515
2516 return files;
2517 }
2518
2519 - (NSArray *) relationships {
2520 return relationships_;
2521 }
2522
2523 - (NSArray *) warnings {
2524 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2525 const char *name(iterator_.Name());
2526
2527 size_t length(strlen(name));
2528 if (length < 2) invalid:
2529 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2530 else for (size_t i(0); i != length; ++i)
2531 if (
2532 /* XXX: technically this is not allowed */
2533 (name[i] < 'A' || name[i] > 'Z') &&
2534 (name[i] < 'a' || name[i] > 'z') &&
2535 (name[i] < '0' || name[i] > '9') &&
2536 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2537 ) goto invalid;
2538
2539 if (strcmp(name, "cydia") != 0) {
2540 bool cydia = false;
2541 bool user = false;
2542 bool _private = false;
2543 bool stash = false;
2544
2545 bool repository = [[self section] isEqualToString:@"Repositories"];
2546
2547 if (NSArray *files = [self files])
2548 for (NSString *file in files)
2549 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2550 cydia = true;
2551 else if (!user && [file isEqualToString:@"/User"])
2552 user = true;
2553 else if (!_private && [file isEqualToString:@"/private"])
2554 _private = true;
2555 else if (!stash && [file isEqualToString:@"/var/stash"])
2556 stash = true;
2557
2558 /* XXX: this is not sensitive enough. only some folders are valid. */
2559 if (cydia && !repository)
2560 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2561 if (user)
2562 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2563 if (_private)
2564 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2565 if (stash)
2566 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2567 }
2568
2569 return [warnings count] == 0 ? nil : warnings;
2570 }
2571
2572 - (NSArray *) applications {
2573 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2574
2575 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2576
2577 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2578 if (NSArray *files = [self files])
2579 for (NSString *file in files)
2580 if (application_r(file)) {
2581 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2582 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2583 if ([id isEqualToString:me])
2584 continue;
2585
2586 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2587 if (display == nil)
2588 display = application_r[1];
2589
2590 NSString *bundle([file stringByDeletingLastPathComponent]);
2591 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2592 if (icon == nil || [icon length] == 0)
2593 icon = @"icon.png";
2594 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2595
2596 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2597 [applications addObject:application];
2598
2599 [application addObject:id];
2600 [application addObject:display];
2601 [application addObject:url];
2602 }
2603
2604 return [applications count] == 0 ? nil : applications;
2605 }
2606
2607 - (Source *) source {
2608 if (!cached_) {
2609 @synchronized (database_) {
2610 if ([database_ era] != era_ || file_.end())
2611 source_ = nil;
2612 else {
2613 source_ = [database_ getSource:file_.File()];
2614 if (source_ != nil)
2615 [source_ retain];
2616 }
2617
2618 cached_ = true;
2619 }
2620 }
2621
2622 return source_;
2623 }
2624
2625 - (NSString *) role {
2626 return role_;
2627 }
2628
2629 - (BOOL) matches:(NSString *)text {
2630 if (text == nil)
2631 return NO;
2632
2633 NSRange range;
2634
2635 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2636 if (range.location != NSNotFound)
2637 return YES;
2638
2639 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2640 if (range.location != NSNotFound)
2641 return YES;
2642
2643 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2644 if (range.location != NSNotFound)
2645 return YES;
2646
2647 return NO;
2648 }
2649
2650 - (bool) hasSupportingRole {
2651 if (role_ == nil)
2652 return true;
2653 if ([role_ isEqualToString:@"enduser"])
2654 return true;
2655 if ([Role_ isEqualToString:@"User"])
2656 return false;
2657 if ([role_ isEqualToString:@"hacker"])
2658 return true;
2659 if ([Role_ isEqualToString:@"Hacker"])
2660 return false;
2661 if ([role_ isEqualToString:@"developer"])
2662 return true;
2663 if ([Role_ isEqualToString:@"Developer"])
2664 return false;
2665 _assert(false);
2666 }
2667
2668 - (BOOL) hasTag:(NSString *)tag {
2669 return tags_ == nil ? NO : [tags_ containsObject:tag];
2670 }
2671
2672 - (NSString *) primaryPurpose {
2673 for (NSString *tag in tags_)
2674 if ([tag hasPrefix:@"purpose::"])
2675 return [tag substringFromIndex:9];
2676 return nil;
2677 }
2678
2679 - (NSArray *) purposes {
2680 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2681 for (NSString *tag in tags_)
2682 if ([tag hasPrefix:@"purpose::"])
2683 [purposes addObject:[tag substringFromIndex:9]];
2684 return [purposes count] == 0 ? nil : purposes;
2685 }
2686
2687 - (bool) isCommercial {
2688 return [self hasTag:@"cydia::commercial"];
2689 }
2690
2691 - (CYString &) cyname {
2692 return name_.empty() ? id_ : name_;
2693 }
2694
2695 - (uint32_t) compareBySection:(NSArray *)sections {
2696 NSString *section([self section]);
2697 for (size_t i(0), e([sections count]); i != e; ++i) {
2698 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2699 return i;
2700 }
2701
2702 return _not(uint32_t);
2703 }
2704
2705 - (uint32_t) compareForChanges {
2706 union {
2707 uint32_t key;
2708
2709 struct {
2710 uint32_t timestamp : 30;
2711 uint32_t ignored : 1;
2712 uint32_t upgradable : 1;
2713 } bits;
2714 } value;
2715
2716 bool upgradable([self upgradableAndEssential:YES]);
2717 value.bits.upgradable = upgradable ? 1 : 0;
2718
2719 if (upgradable) {
2720 value.bits.timestamp = 0;
2721 value.bits.ignored = [self ignored] ? 0 : 1;
2722 value.bits.upgradable = 1;
2723 } else {
2724 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2725 value.bits.ignored = 0;
2726 value.bits.upgradable = 0;
2727 }
2728
2729 return _not(uint32_t) - value.key;
2730 }
2731
2732 - (void) clear {
2733 pkgProblemResolver *resolver = [database_ resolver];
2734 resolver->Clear(iterator_);
2735 resolver->Protect(iterator_);
2736 }
2737
2738 - (void) install {
2739 pkgProblemResolver *resolver = [database_ resolver];
2740 resolver->Clear(iterator_);
2741 resolver->Protect(iterator_);
2742 pkgCacheFile &cache([database_ cache]);
2743 cache->MarkInstall(iterator_, false);
2744 pkgDepCache::StateCache &state((*cache)[iterator_]);
2745 if (!state.Install())
2746 cache->SetReInstall(iterator_, true);
2747 }
2748
2749 - (void) remove {
2750 pkgProblemResolver *resolver = [database_ resolver];
2751 resolver->Clear(iterator_);
2752 resolver->Protect(iterator_);
2753 resolver->Remove(iterator_);
2754 [database_ cache]->MarkDelete(iterator_, true);
2755 }
2756
2757 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2758 _profile(Package$isUnfilteredAndSearchedForBy)
2759 bool value(true);
2760
2761 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2762 value &= [self unfiltered];
2763 _end
2764
2765 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2766 value &= [self matches:search];
2767 _end
2768
2769 return value;
2770 _end
2771 }
2772
2773 - (bool) isInstalledAndVisible:(NSNumber *)number {
2774 return (![number boolValue] || [self visible]) && ![self uninstalled];
2775 }
2776
2777 - (bool) isVisibleInSection:(NSString *)name {
2778 NSString *section = [self section];
2779
2780 return
2781 [self visible] && (
2782 name == nil ||
2783 section == nil && [name length] == 0 ||
2784 [name isEqualToString:section]
2785 );
2786 }
2787
2788 - (bool) isVisibleInSource:(Source *)source {
2789 return [self source] == source && [self visible];
2790 }
2791
2792 @end
2793 /* }}} */
2794 /* Section Class {{{ */
2795 @interface Section : NSObject {
2796 NSString *name_;
2797 unichar index_;
2798 size_t row_;
2799 size_t count_;
2800 NSString *localized_;
2801 }
2802
2803 - (NSComparisonResult) compareByLocalized:(Section *)section;
2804 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2805 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2806 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2807 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2808 - (NSString *) name;
2809 - (unichar) index;
2810
2811 - (size_t) row;
2812 - (size_t) count;
2813
2814 - (void) addToRow;
2815 - (void) addToCount;
2816
2817 - (void) setCount:(size_t)count;
2818 - (NSString *) localized;
2819
2820 @end
2821
2822 @implementation Section
2823
2824 - (void) dealloc {
2825 [name_ release];
2826 if (localized_ != nil)
2827 [localized_ release];
2828 [super dealloc];
2829 }
2830
2831 - (NSComparisonResult) compareByLocalized:(Section *)section {
2832 NSString *lhs(localized_);
2833 NSString *rhs([section localized]);
2834
2835 /*if ([lhs length] != 0 && [rhs length] != 0) {
2836 unichar lhc = [lhs characterAtIndex:0];
2837 unichar rhc = [rhs characterAtIndex:0];
2838
2839 if (isalpha(lhc) && !isalpha(rhc))
2840 return NSOrderedAscending;
2841 else if (!isalpha(lhc) && isalpha(rhc))
2842 return NSOrderedDescending;
2843 }*/
2844
2845 return [lhs compare:rhs options:LaxCompareOptions_];
2846 }
2847
2848 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2849 if ((self = [self initWithName:name localize:NO]) != nil) {
2850 if (localized != nil)
2851 localized_ = [localized retain];
2852 } return self;
2853 }
2854
2855 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2856 return [self initWithName:name row:0 localize:localize];
2857 }
2858
2859 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2860 if ((self = [super init]) != nil) {
2861 name_ = [name retain];
2862 index_ = '\0';
2863 row_ = row;
2864 if (localize)
2865 localized_ = [LocalizeSection(name_) retain];
2866 } return self;
2867 }
2868
2869 /* XXX: localize the index thingees */
2870 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2871 if ((self = [super init]) != nil) {
2872 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2873 index_ = index;
2874 row_ = row;
2875 } return self;
2876 }
2877
2878 - (NSString *) name {
2879 return name_;
2880 }
2881
2882 - (unichar) index {
2883 return index_;
2884 }
2885
2886 - (size_t) row {
2887 return row_;
2888 }
2889
2890 - (size_t) count {
2891 return count_;
2892 }
2893
2894 - (void) addToRow {
2895 ++row_;
2896 }
2897
2898 - (void) addToCount {
2899 ++count_;
2900 }
2901
2902 - (void) setCount:(size_t)count {
2903 count_ = count;
2904 }
2905
2906 - (NSString *) localized {
2907 return localized_;
2908 }
2909
2910 @end
2911 /* }}} */
2912
2913 static NSString *Colon_;
2914 static NSString *Error_;
2915 static NSString *Warning_;
2916
2917 /* Database Implementation {{{ */
2918 @implementation Database
2919
2920 + (Database *) sharedInstance {
2921 static Database *instance;
2922 if (instance == nil)
2923 instance = [[Database alloc] init];
2924 return instance;
2925 }
2926
2927 - (unsigned) era {
2928 return era_;
2929 }
2930
2931 - (void) dealloc {
2932 _assert(false);
2933 NSRecycleZone(zone_);
2934 // XXX: malloc_destroy_zone(zone_);
2935 apr_pool_destroy(pool_);
2936 [super dealloc];
2937 }
2938
2939 - (void) _readCydia:(NSNumber *)fd { _pooled
2940 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2941 std::istream is(&ib);
2942 std::string line;
2943
2944 static Pcre finish_r("^finish:([^:]*)$");
2945
2946 while (std::getline(is, line)) {
2947 const char *data(line.c_str());
2948 size_t size = line.size();
2949 lprintf("C:%s\n", data);
2950
2951 if (finish_r(data, size)) {
2952 NSString *finish = finish_r[1];
2953 int index = [Finishes_ indexOfObject:finish];
2954 if (index != INT_MAX && index > Finish_)
2955 Finish_ = index;
2956 }
2957 }
2958
2959 _assume(false);
2960 }
2961
2962 - (void) _readStatus:(NSNumber *)fd { _pooled
2963 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2964 std::istream is(&ib);
2965 std::string line;
2966
2967 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2968 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2969
2970 while (std::getline(is, line)) {
2971 const char *data(line.c_str());
2972 size_t size(line.size());
2973 lprintf("S:%s\n", data);
2974
2975 if (conffile_r(data, size)) {
2976 [delegate_ setConfigurationData:conffile_r[1]];
2977 } else if (strncmp(data, "status: ", 8) == 0) {
2978 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2979 [delegate_ setProgressTitle:string];
2980 } else if (pmstatus_r(data, size)) {
2981 std::string type([pmstatus_r[1] UTF8String]);
2982 NSString *id = pmstatus_r[2];
2983
2984 float percent([pmstatus_r[3] floatValue]);
2985 [delegate_ setProgressPercent:(percent / 100)];
2986
2987 NSString *string = pmstatus_r[4];
2988
2989 if (type == "pmerror")
2990 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
2991 withObject:[NSArray arrayWithObjects:string, id, nil]
2992 waitUntilDone:YES
2993 ];
2994 else if (type == "pmstatus") {
2995 [delegate_ setProgressTitle:string];
2996 } else if (type == "pmconffile")
2997 [delegate_ setConfigurationData:string];
2998 else
2999 lprintf("E:unknown pmstatus\n");
3000 } else
3001 lprintf("E:unknown status\n");
3002 }
3003
3004 _assume(false);
3005 }
3006
3007 - (void) _readOutput:(NSNumber *)fd { _pooled
3008 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3009 std::istream is(&ib);
3010 std::string line;
3011
3012 while (std::getline(is, line)) {
3013 lprintf("O:%s\n", line.c_str());
3014 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3015 }
3016
3017 _assume(false);
3018 }
3019
3020 - (FILE *) input {
3021 return input_;
3022 }
3023
3024 - (Package *) packageWithName:(NSString *)name {
3025 @synchronized ([Database class]) {
3026 if (static_cast<pkgDepCache *>(cache_) == NULL)
3027 return nil;
3028 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3029 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3030 } }
3031
3032 - (Database *) init {
3033 if ((self = [super init]) != nil) {
3034 policy_ = NULL;
3035 records_ = NULL;
3036 resolver_ = NULL;
3037 fetcher_ = NULL;
3038 lock_ = NULL;
3039
3040 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3041 apr_pool_create(&pool_, NULL);
3042
3043 packages_ = [[NSMutableArray alloc] init];
3044
3045 int fds[2];
3046
3047 _assert(pipe(fds) != -1);
3048 cydiafd_ = fds[1];
3049
3050 _config->Set("APT::Keep-Fds::", cydiafd_);
3051 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3052
3053 [NSThread
3054 detachNewThreadSelector:@selector(_readCydia:)
3055 toTarget:self
3056 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3057 ];
3058
3059 _assert(pipe(fds) != -1);
3060 statusfd_ = fds[1];
3061
3062 [NSThread
3063 detachNewThreadSelector:@selector(_readStatus:)
3064 toTarget:self
3065 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3066 ];
3067
3068 _assert(pipe(fds) != -1);
3069 _assert(dup2(fds[0], 0) != -1);
3070 _assert(close(fds[0]) != -1);
3071
3072 input_ = fdopen(fds[1], "a");
3073
3074 _assert(pipe(fds) != -1);
3075 _assert(dup2(fds[1], 1) != -1);
3076 _assert(close(fds[1]) != -1);
3077
3078 [NSThread
3079 detachNewThreadSelector:@selector(_readOutput:)
3080 toTarget:self
3081 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3082 ];
3083 } return self;
3084 }
3085
3086 - (pkgCacheFile &) cache {
3087 return cache_;
3088 }
3089
3090 - (pkgDepCache::Policy *) policy {
3091 return policy_;
3092 }
3093
3094 - (pkgRecords *) records {
3095 return records_;
3096 }
3097
3098 - (pkgProblemResolver *) resolver {
3099 return resolver_;
3100 }
3101
3102 - (pkgAcquire &) fetcher {
3103 return *fetcher_;
3104 }
3105
3106 - (pkgSourceList &) list {
3107 return *list_;
3108 }
3109
3110 - (NSArray *) packages {
3111 return packages_;
3112 }
3113
3114 - (NSArray *) sources {
3115 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3116 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3117 [sources addObject:i->second];
3118 return sources;
3119 }
3120
3121 - (NSArray *) issues {
3122 if (cache_->BrokenCount() == 0)
3123 return nil;
3124
3125 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3126
3127 for (Package *package in packages_) {
3128 if (![package broken])
3129 continue;
3130 pkgCache::PkgIterator pkg([package iterator]);
3131
3132 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3133 [entry addObject:[package name]];
3134 [issues addObject:entry];
3135
3136 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3137 if (ver.end())
3138 continue;
3139
3140 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3141 pkgCache::DepIterator start;
3142 pkgCache::DepIterator end;
3143 dep.GlobOr(start, end); // ++dep
3144
3145 if (!cache_->IsImportantDep(end))
3146 continue;
3147 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3148 continue;
3149
3150 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3151 [entry addObject:failure];
3152 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3153
3154 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3155 if (Package *package = [self packageWithName:name])
3156 name = [package name];
3157 [failure addObject:name];
3158
3159 pkgCache::PkgIterator target(start.TargetPkg());
3160 if (target->ProvidesList != 0)
3161 [failure addObject:@"?"];
3162 else {
3163 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3164 if (!ver.end())
3165 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3166 else if (!cache_[target].CandidateVerIter(cache_).end())
3167 [failure addObject:@"-"];
3168 else if (target->ProvidesList == 0)
3169 [failure addObject:@"!"];
3170 else
3171 [failure addObject:@"%"];
3172 }
3173
3174 _forever {
3175 if (start.TargetVer() != 0)
3176 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3177 if (start == end)
3178 break;
3179 ++start;
3180 }
3181 }
3182 }
3183
3184 return issues;
3185 }
3186
3187 - (bool) popErrorWithTitle:(NSString *)title {
3188 bool fatal(false);
3189 std::string message;
3190
3191 while (!_error->empty()) {
3192 std::string error;
3193 bool warning(!_error->PopMessage(error));
3194 if (!warning)
3195 fatal = true;
3196 for (;;) {
3197 size_t size(error.size());
3198 if (size == 0 || error[size - 1] != '\n')
3199 break;
3200 error.resize(size - 1);
3201 }
3202 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3203
3204 if (!message.empty())
3205 message += "\n\n";
3206 message += error;
3207 }
3208
3209 if (fatal && !message.empty())
3210 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3211
3212 return fatal;
3213 }
3214
3215 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3216 return [self popErrorWithTitle:title] || !success;
3217 }
3218
3219 - (void) reloadData { _pooled
3220 @synchronized ([Database class]) {
3221 @synchronized (self) {
3222 ++era_;
3223 }
3224
3225 [packages_ removeAllObjects];
3226 sources_.clear();
3227
3228 _error->Discard();
3229
3230 delete list_;
3231 list_ = NULL;
3232 manager_ = NULL;
3233 delete lock_;
3234 lock_ = NULL;
3235 delete fetcher_;
3236 fetcher_ = NULL;
3237 delete resolver_;
3238 resolver_ = NULL;
3239 delete records_;
3240 records_ = NULL;
3241 delete policy_;
3242 policy_ = NULL;
3243
3244 if (now_ != nil) {
3245 [now_ release];
3246 now_ = nil;
3247 }
3248
3249 cache_.Close();
3250
3251 apr_pool_clear(pool_);
3252 NSRecycleZone(zone_);
3253
3254 int chk(creat("/tmp/cydia.chk", 0644));
3255 if (chk != -1)
3256 close(chk);
3257
3258 NSString *title(UCLocalize("DATABASE"));
3259
3260 _trace();
3261 if (!cache_.Open(progress_, true)) { pop:
3262 std::string error;
3263 bool warning(!_error->PopMessage(error));
3264 lprintf("cache_.Open():[%s]\n", error.c_str());
3265
3266 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3267 [delegate_ repairWithSelector:@selector(configure)];
3268 else if (error == "The package lists or status file could not be parsed or opened.")
3269 [delegate_ repairWithSelector:@selector(update)];
3270 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3271 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3272 // else if (error == "The list of sources could not be read.")
3273 else
3274 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3275
3276 if (warning)
3277 goto pop;
3278 _error->Discard();
3279 return;
3280 }
3281 _trace();
3282
3283 unlink("/tmp/cydia.chk");
3284
3285 now_ = [[NSDate date] retain];
3286
3287 policy_ = new pkgDepCache::Policy();
3288 records_ = new pkgRecords(cache_);
3289 resolver_ = new pkgProblemResolver(cache_);
3290 fetcher_ = new pkgAcquire(&status_);
3291 lock_ = NULL;
3292
3293 list_ = new pkgSourceList();
3294 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3295 return;
3296
3297 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3298 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3299 return;
3300 }
3301
3302 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3303 return;
3304
3305 if (cache_->BrokenCount() != 0) {
3306 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3307 return;
3308
3309 if (cache_->BrokenCount() != 0) {
3310 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3311 return;
3312 }
3313
3314 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3315 return;
3316 }
3317
3318 _trace();
3319
3320 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3321 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3322 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3323 // XXX: this could be more intelligent
3324 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3325 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3326 if (!cached.end())
3327 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3328 }
3329 }
3330
3331 _trace();
3332
3333 {
3334 /*std::vector<Package *> packages;
3335 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3336 [packages_ release];
3337 packages_ = nil;*/
3338
3339 _trace();
3340
3341 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3342 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3343 //packages.push_back(package);
3344 [packages_ addObject:package];
3345
3346 _trace();
3347
3348 /*if (packages.empty())
3349 packages_ = [[NSArray alloc] init];
3350 else
3351 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3352 _trace();*/
3353
3354 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3355 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3356 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3357
3358 /*_trace();
3359 PrintTimes();
3360 _trace();*/
3361
3362 _trace();
3363
3364 /*if (!packages.empty())
3365 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3366 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3367
3368 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3369
3370 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3371
3372 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3373
3374 _trace();
3375 }
3376 } }
3377
3378 - (void) configure {
3379 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3380 system([dpkg UTF8String]);
3381 }
3382
3383 - (bool) clean {
3384 // XXX: I don't remember this condition
3385 if (lock_ != NULL)
3386 return false;
3387
3388 FileFd Lock;
3389 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3390
3391 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3392
3393 if ([self popErrorWithTitle:title])
3394 return false;
3395
3396 pkgAcquire fetcher;
3397 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3398
3399 class LogCleaner :
3400 public pkgArchiveCleaner
3401 {
3402 protected:
3403 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3404 unlink(File);
3405 }
3406 } cleaner;
3407
3408 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3409 return false;
3410
3411 return true;
3412 }
3413
3414 - (bool) prepare {
3415 fetcher_->Shutdown();
3416
3417 pkgRecords records(cache_);
3418
3419 lock_ = new FileFd();
3420 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3421
3422 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3423
3424 if ([self popErrorWithTitle:title])
3425 return false;
3426
3427 pkgSourceList list;
3428 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3429 return false;
3430
3431 manager_ = (_system->CreatePM(cache_));
3432 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3433 return false;
3434
3435 return true;
3436 }
3437
3438 - (void) perform {
3439 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3440
3441 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3442 pkgSourceList list;
3443 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3444 return;
3445 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3446 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3447 }
3448
3449 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3450 _trace();
3451 return;
3452 }
3453
3454 bool failed = false;
3455 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3456 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3457 continue;
3458 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3459 continue;
3460
3461 std::string uri = (*item)->DescURI();
3462 std::string error = (*item)->ErrorText;
3463
3464 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3465 failed = true;
3466
3467 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3468 withObject:[NSArray arrayWithObjects:
3469 [NSString stringWithUTF8String:error.c_str()],
3470 nil]
3471 waitUntilDone:YES
3472 ];
3473 }
3474
3475 if (failed) {
3476 _trace();
3477 return;
3478 }
3479
3480 _system->UnLock();
3481 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3482
3483 if (_error->PendingError()) {
3484 _trace();
3485 return;
3486 }
3487
3488 if (result == pkgPackageManager::Failed) {
3489 _trace();
3490 return;
3491 }
3492
3493 if (result != pkgPackageManager::Completed) {
3494 _trace();
3495 return;
3496 }
3497
3498 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3499 pkgSourceList list;
3500 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3501 return;
3502 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3503 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3504 }
3505
3506 if (![before isEqualToArray:after])
3507 [self update];
3508 }
3509
3510 - (bool) upgrade {
3511 NSString *title(UCLocalize("UPGRADE"));
3512 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3513 return false;
3514 return true;
3515 }
3516
3517 - (void) update {
3518 [self updateWithStatus:status_];
3519 }
3520
3521 - (void) setVisible {
3522 for (Package *package in packages_)
3523 [package setVisible];
3524 }
3525
3526 - (void) updateWithStatus:(Status &)status {
3527 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3528 NSString *title(UCLocalize("REFRESHING_DATA"));
3529
3530 pkgSourceList list;
3531 if (!list.ReadMainList())
3532 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3533
3534 FileFd lock;
3535 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3536 if ([self popErrorWithTitle:title])
3537 return;
3538
3539 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3540 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3541
3542 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3543 Changed_ = true;
3544 }
3545
3546 - (void) setDelegate:(id)delegate {
3547 delegate_ = delegate;
3548 status_.setDelegate(delegate);
3549 progress_.setDelegate(delegate);
3550 }
3551
3552 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3553 SourceMap::const_iterator i(sources_.find(file->ID));
3554 return i == sources_.end() ? nil : i->second;
3555 }
3556
3557 @end
3558 /* }}} */
3559
3560 /* Confirmation View {{{ */
3561 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3562 if (!iterator.end())
3563 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3564 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3565 continue;
3566 pkgCache::PkgIterator package(dep.TargetPkg());
3567 if (package.end())
3568 continue;
3569 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3570 return true;
3571 }
3572
3573 return false;
3574 }
3575
3576 /* Web Scripting {{{ */
3577 @interface CydiaObject : NSObject {
3578 id indirect_;
3579 }
3580
3581 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3582 @end
3583
3584 @implementation CydiaObject
3585
3586 - (void) dealloc {
3587 [indirect_ release];
3588 [super dealloc];
3589 }
3590
3591 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3592 if ((self = [super init]) != nil) {
3593 indirect_ = [indirect retain];
3594 } return self;
3595 }
3596
3597 + (NSArray *) _attributeKeys {
3598 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3599 }
3600
3601 - (NSArray *) attributeKeys {
3602 return [[self class] _attributeKeys];
3603 }
3604
3605 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3606 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3607 }
3608
3609 - (NSString *) device {
3610 return [[UIDevice currentDevice] uniqueIdentifier];
3611 }
3612
3613 #if 0 // XXX: implement!
3614 - (NSString *) mac {
3615 if (![indirect_ promptForSensitive:@"Mac Address"])
3616 return nil;
3617 }
3618
3619 - (NSString *) serial {
3620 if (![indirect_ promptForSensitive:@"Serial #"])
3621 return nil;
3622 }
3623
3624 - (NSString *) firewire {
3625 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3626 return nil;
3627 }
3628
3629 - (NSString *) imei {
3630 if (![indirect_ promptForSensitive:@"IMEI"])
3631 return nil;
3632 }
3633 #endif
3634
3635 + (NSString *) webScriptNameForSelector:(SEL)selector {
3636 if (selector == @selector(close))
3637 return @"close";
3638 else if (selector == @selector(getInstalledPackages))
3639 return @"getInstalledPackages";
3640 else if (selector == @selector(getPackageById:))
3641 return @"getPackageById";
3642 else if (selector == @selector(setAutoPopup:))
3643 return @"setAutoPopup";
3644 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3645 return @"setButtonImage";
3646 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3647 return @"setButtonTitle";
3648 else if (selector == @selector(setFinishHook:))
3649 return @"setFinishHook";
3650 else if (selector == @selector(setPopupHook:))
3651 return @"setPopupHook";
3652 else if (selector == @selector(setSpecial:))
3653 return @"setSpecial";
3654 else if (selector == @selector(setViewportWidth:))
3655 return @"setViewportWidth";
3656 else if (selector == @selector(supports:))
3657 return @"supports";
3658 else if (selector == @selector(stringWithFormat:arguments:))
3659 return @"format";
3660 else if (selector == @selector(localizedStringForKey:value:table:))
3661 return @"localize";
3662 else if (selector == @selector(du:))
3663 return @"du";
3664 else if (selector == @selector(statfs:))
3665 return @"statfs";
3666 else
3667 return nil;
3668 }
3669
3670 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3671 return [self webScriptNameForSelector:selector] == nil;
3672 }
3673
3674 - (BOOL) supports:(NSString *)feature {
3675 return [feature isEqualToString:@"window.open"];
3676 }
3677
3678 - (NSArray *) getInstalledPackages {
3679 NSArray *packages([[Database sharedInstance] packages]);
3680 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3681 for (Package *package in installed)
3682 if ([package installed] != nil)
3683 [installed addObject:package];
3684 return installed;
3685 }
3686
3687 - (Package *) getPackageById:(NSString *)id {
3688 Package *package([[Database sharedInstance] packageWithName:id]);
3689 [package parse];
3690 return package;
3691 }
3692
3693 - (NSArray *) statfs:(NSString *)path {
3694 struct statfs stat;
3695
3696 if (path == nil || statfs([path UTF8String], &stat) == -1)
3697 return nil;
3698
3699 return [NSArray arrayWithObjects:
3700 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3701 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3702 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3703 nil];
3704 }
3705
3706 - (NSNumber *) du:(NSString *)path {
3707 NSNumber *value(nil);
3708
3709 int fds[2];
3710 _assert(pipe(fds) != -1);
3711
3712 pid_t pid(ExecFork());
3713 if (pid == 0) {
3714 _assert(dup2(fds[1], 1) != -1);
3715 _assert(close(fds[0]) != -1);
3716 _assert(close(fds[1]) != -1);
3717 /* XXX: this should probably not use du */
3718 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3719 exit(1);
3720 _assert(false);
3721 }
3722
3723 _assert(close(fds[1]) != -1);
3724
3725 if (FILE *du = fdopen(fds[0], "r")) {
3726 char line[1024];
3727 while (fgets(line, sizeof(line), du) != NULL) {
3728 size_t length(strlen(line));
3729 while (length != 0 && line[length - 1] == '\n')
3730 line[--length] = '\0';
3731 if (char *tab = strchr(line, '\t')) {
3732 *tab = '\0';
3733 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3734 }
3735 }
3736
3737 fclose(du);
3738 } else _assert(close(fds[0]));
3739
3740 int status;
3741 wait:
3742 if (waitpid(pid, &status, 0) == -1)
3743 if (errno == EINTR)
3744 goto wait;
3745 else _assert(false);
3746
3747 return value;
3748 }
3749
3750 - (void) close {
3751 [indirect_ close];
3752 }
3753
3754 - (void) setAutoPopup:(BOOL)popup {
3755 [indirect_ setAutoPopup:popup];
3756 }
3757
3758 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3759 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3760 }
3761
3762 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3763 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3764 }
3765
3766 - (void) setSpecial:(id)function {
3767 [indirect_ setSpecial:function];
3768 }
3769
3770 - (void) setFinishHook:(id)function {
3771 [indirect_ setFinishHook:function];
3772 }
3773
3774 - (void) setPopupHook:(id)function {
3775 [indirect_ setPopupHook:function];
3776 }
3777
3778 - (void) setViewportWidth:(float)width {
3779 [indirect_ setViewportWidth:width];
3780 }
3781
3782 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3783 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3784 unsigned count([arguments count]);
3785 id values[count];
3786 for (unsigned i(0); i != count; ++i)
3787 values[i] = [arguments objectAtIndex:i];
3788 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3789 }
3790
3791 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3792 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3793 value = nil;
3794 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3795 table = nil;
3796 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3797 }
3798
3799 @end
3800 /* }}} */
3801
3802 @interface CydiaBrowserView : BrowserView {
3803 CydiaObject *cydia_;
3804 }
3805
3806 @end
3807
3808 @implementation CydiaBrowserView
3809
3810 - (void) dealloc {
3811 [cydia_ release];
3812 [super dealloc];
3813 }
3814
3815 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3816 [super webView:sender didClearWindowObject:window forFrame:frame];
3817 [window setValue:cydia_ forKey:@"cydia"];
3818 }
3819
3820 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3821 if (System_ != NULL)
3822 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3823 if (Machine_ != NULL)
3824 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3825 if (UniqueID_ != nil)
3826 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
3827 if (Role_ != nil)
3828 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3829 }
3830
3831 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3832 NSMutableURLRequest *copy = [request mutableCopy];
3833 [self _setMoreHeaders:copy];
3834 return copy;
3835 }
3836
3837 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3838 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3839 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3840
3841 WebView *webview([webview_ webView]);
3842
3843 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3844
3845 NSString *application = package == nil ? @"Cydia" : [NSString
3846 stringWithFormat:@"Cydia/%@",
3847 [package installed]
3848 ];
3849
3850 if (Safari_ != nil)
3851 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3852 if (Build_ != nil)
3853 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3854 if (Product_ != nil)
3855 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3856
3857 [webview setApplicationNameForUserAgent:application];
3858 } return self;
3859 }
3860
3861 @end
3862
3863 @protocol ConfirmationViewDelegate
3864 - (void) cancel;
3865 - (void) confirm;
3866 - (void) queue;
3867 @end
3868
3869 @interface ConfirmationView : CydiaBrowserView {
3870 _transient Database *database_;
3871 UIActionSheet *essential_;
3872 NSArray *changes_;
3873 NSArray *issues_;
3874 NSArray *sizes_;
3875 BOOL substrate_;
3876 }
3877
3878 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3879
3880 @end
3881
3882 @implementation ConfirmationView
3883
3884 - (void) dealloc {
3885 [changes_ release];
3886 if (issues_ != nil)
3887 [issues_ release];
3888 [sizes_ release];
3889 if (essential_ != nil)
3890 [essential_ release];
3891 [super dealloc];
3892 }
3893
3894 - (void) cancel {
3895 [delegate_ cancel];
3896 [book_ popFromSuperviewAnimated:YES];
3897 }
3898
3899 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3900 NSString *context([sheet context]);
3901
3902 if ([context isEqualToString:@"remove"]) {
3903 switch (button) {
3904 case 1:
3905 [self cancel];
3906 break;
3907 case 2:
3908 if (substrate_)
3909 Finish_ = 2;
3910 [delegate_ confirm];
3911 break;
3912 _nodefault
3913 }
3914
3915 [sheet dismiss];
3916 } else if ([context isEqualToString:@"unable"]) {
3917 [self cancel];
3918 [sheet dismiss];
3919 } else
3920 [super alertSheet:sheet buttonClicked:button];
3921 }
3922
3923 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3924 [super webView:sender didClearWindowObject:window forFrame:frame];
3925 [window setValue:changes_ forKey:@"changes"];
3926 [window setValue:issues_ forKey:@"issues"];
3927 [window setValue:sizes_ forKey:@"sizes"];
3928 }
3929
3930 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3931 if ((self = [super initWithBook:book]) != nil) {
3932 database_ = database;
3933
3934 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3935 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3936 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3937 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3938 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3939
3940 bool remove(false);
3941
3942 pkgDepCache::Policy *policy([database_ policy]);
3943
3944 pkgCacheFile &cache([database_ cache]);
3945 NSArray *packages = [database_ packages];
3946 for (Package *package in packages) {
3947 pkgCache::PkgIterator iterator = [package iterator];
3948 pkgDepCache::StateCache &state(cache[iterator]);
3949
3950 NSString *name([package name]);
3951
3952 if (state.NewInstall())
3953 [installing addObject:name];
3954 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3955 [reinstalling addObject:name];
3956 else if (state.Upgrade())
3957 [upgrading addObject:name];
3958 else if (state.Downgrade())
3959 [downgrading addObject:name];
3960 else if (state.Delete()) {
3961 if ([package essential])
3962 remove = true;
3963 [removing addObject:name];
3964 } else continue;
3965
3966 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3967 substrate_ |= DepSubstrate(iterator.CurrentVer());
3968 }
3969
3970 if (!remove)
3971 essential_ = nil;
3972 else if (Advanced_) {
3973 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
3974
3975 essential_ = [[UIActionSheet alloc]
3976 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
3977 buttons:[NSArray arrayWithObjects:
3978 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
3979 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
3980 nil]
3981 defaultButtonIndex:0
3982 delegate:self
3983 context:@"remove"
3984 ];
3985
3986 [essential_ setDestructiveButtonIndex:1];
3987 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
3988 } else {
3989 essential_ = [[UIActionSheet alloc]
3990 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
3991 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
3992 defaultButtonIndex:0
3993 delegate:self
3994 context:@"unable"
3995 ];
3996
3997 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
3998 }
3999
4000 changes_ = [[NSArray alloc] initWithObjects:
4001 installing,
4002 reinstalling,
4003 upgrading,
4004 downgrading,
4005 removing,
4006 nil];
4007
4008 issues_ = [database_ issues];
4009 if (issues_ != nil)
4010 issues_ = [issues_ retain];
4011
4012 sizes_ = [[NSArray alloc] initWithObjects:
4013 SizeString([database_ fetcher].FetchNeeded()),
4014 SizeString([database_ fetcher].PartialPresent()),
4015 SizeString([database_ cache]->UsrSize()),
4016 nil];
4017
4018 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4019 } return self;
4020 }
4021
4022 - (NSString *) backButtonTitle {
4023 return UCLocalize("CONFIRM");
4024 }
4025
4026 - (NSString *) leftButtonTitle {
4027 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4028 }
4029
4030 - (id) rightButtonTitle {
4031 return issues_ != nil ? nil : [super rightButtonTitle];
4032 }
4033
4034 - (id) _rightButtonTitle {
4035 #if AlwaysReload || IgnoreInstall
4036 return [super _rightButtonTitle];
4037 #else
4038 return UCLocalize("CONFIRM");
4039 #endif
4040 }
4041
4042 - (void) _leftButtonClicked {
4043 [self cancel];
4044 }
4045
4046 #if !AlwaysReload
4047 - (void) _rightButtonClicked {
4048 #if IgnoreInstall
4049 return [super _rightButtonClicked];
4050 #endif
4051 if (essential_ != nil)
4052 [essential_ popupAlertAnimated:YES];
4053 else {
4054 if (substrate_)
4055 Finish_ = 2;
4056 [delegate_ confirm];
4057 }
4058 }
4059 #endif
4060
4061 @end
4062 /* }}} */
4063
4064 /* Progress Data {{{ */
4065 @interface ProgressData : NSObject {
4066 SEL selector_;
4067 id target_;
4068 id object_;
4069 }
4070
4071 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4072
4073 - (SEL) selector;
4074 - (id) target;
4075 - (id) object;
4076 @end
4077
4078 @implementation ProgressData
4079
4080 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4081 if ((self = [super init]) != nil) {
4082 selector_ = selector;
4083 target_ = target;
4084 object_ = object;
4085 } return self;
4086 }
4087
4088 - (SEL) selector {
4089 return selector_;
4090 }
4091
4092 - (id) target {
4093 return target_;
4094 }
4095
4096 - (id) object {
4097 return object_;
4098 }
4099
4100 @end
4101 /* }}} */
4102 /* Progress View {{{ */
4103 @interface ProgressView : UIView <
4104 ConfigurationDelegate,
4105 ProgressDelegate
4106 > {
4107 _transient Database *database_;
4108 UIView *view_;
4109 UIView *background_;
4110 UITransitionView *transition_;
4111 UIView *overlay_;
4112 UINavigationBar *navbar_;
4113 UIProgressBar *progress_;
4114 UITextView *output_;
4115 UITextLabel *status_;
4116 UIPushButton *close_;
4117 id delegate_;
4118 BOOL running_;
4119 SHA1SumValue springlist_;
4120 SHA1SumValue notifyconf_;
4121 NSString *title_;
4122 }
4123
4124 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4125 - (void) setContentView:(UIView *)view;
4126 - (void) resetView;
4127
4128 - (void) _retachThread;
4129 - (void) _detachNewThreadData:(ProgressData *)data;
4130 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4131
4132 - (BOOL) isRunning;
4133
4134 @end
4135
4136 @protocol ProgressViewDelegate
4137 - (void) progressViewIsComplete:(ProgressView *)sender;
4138 @end
4139
4140 @implementation ProgressView
4141
4142 - (void) dealloc {
4143 [transition_ setDelegate:nil];
4144 [navbar_ setDelegate:nil];
4145
4146 [view_ release];
4147 if (background_ != nil)
4148 [background_ release];
4149 [transition_ release];
4150 [overlay_ release];
4151 [navbar_ release];
4152 [progress_ release];
4153 [output_ release];
4154 [status_ release];
4155 [close_ release];
4156 if (title_ != nil)
4157 [title_ release];
4158 [super dealloc];
4159 }
4160
4161 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4162 if ((self = [super initWithFrame:frame]) != nil) {
4163 database_ = database;
4164 delegate_ = delegate;
4165
4166 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4167 [transition_ setDelegate:self];
4168
4169 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4170
4171 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4172 [background_ setBackgroundColor:[UIColor blackColor]];
4173 [self addSubview:background_];
4174
4175 [self addSubview:transition_];
4176
4177 CGSize navsize = [UINavigationBar defaultSize];
4178 CGRect navrect = {{0, 0}, navsize};
4179
4180 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4181 [overlay_ addSubview:navbar_];
4182
4183 [navbar_ setBarStyle:1];
4184 [navbar_ setDelegate:self];
4185
4186 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4187 [navbar_ pushNavigationItem:navitem];
4188
4189 CGRect bounds = [overlay_ bounds];
4190 CGSize prgsize = [UIProgressBar defaultSize];
4191
4192 CGRect prgrect = {{
4193 (bounds.size.width - prgsize.width) / 2,
4194 bounds.size.height - prgsize.height - 20
4195 }, prgsize};
4196
4197 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4198 [progress_ setStyle:0];
4199
4200 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4201 10,
4202 bounds.size.height - prgsize.height - 50,
4203 bounds.size.width - 20,
4204 24
4205 )];
4206
4207 [status_ setColor:[UIColor whiteColor]];
4208 [status_ setBackgroundColor:[UIColor clearColor]];
4209
4210 [status_ setCentersHorizontally:YES];
4211 //[status_ setFont:font];
4212
4213 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4214 10,
4215 navrect.size.height + 20,
4216 bounds.size.width - 20,
4217 bounds.size.height - navsize.height - 62 - navrect.size.height
4218 )];
4219
4220 //[output_ setTextFont:@"Courier New"];
4221 [output_ setFont:[[output_ font] fontWithSize:12]];
4222
4223 [output_ setTextColor:[UIColor whiteColor]];
4224 [output_ setBackgroundColor:[UIColor clearColor]];
4225
4226 [output_ setMarginTop:0];
4227 [output_ setAllowsRubberBanding:YES];
4228 [output_ setEditable:NO];
4229
4230 [overlay_ addSubview:output_];
4231
4232 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4233 10,
4234 bounds.size.height - prgsize.height - 50,
4235 bounds.size.width - 20,
4236 32 + prgsize.height
4237 )];
4238
4239 [close_ setAutosizesToFit:NO];
4240 [close_ setDrawsShadow:YES];
4241 [close_ setStretchBackground:YES];
4242 [close_ setEnabled:YES];
4243
4244 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4245 [close_ setTitleFont:bold];
4246
4247 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4248 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4249 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4250 } return self;
4251 }
4252
4253 - (void) setContentView:(UIView *)view {
4254 view_ = [view retain];
4255 }
4256
4257 - (void) resetView {
4258 [transition_ transition:6 toView:view_];
4259 }
4260
4261 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4262 NSString *context([sheet context]);
4263
4264 if ([context isEqualToString:@"conffile"]) {
4265 FILE *input = [database_ input];
4266
4267 switch (button) {
4268 case 1:
4269 fprintf(input, "N\n");
4270 fflush(input);
4271 break;
4272 case 2:
4273 fprintf(input, "Y\n");
4274 fflush(input);
4275 break;
4276 _nodefault
4277 }
4278
4279 [sheet dismiss];
4280 }
4281 }
4282
4283 - (void) closeButtonPushed {
4284 running_ = NO;
4285
4286 switch (Finish_) {
4287 case 0:
4288 [self resetView];
4289 break;
4290
4291 case 1:
4292 [delegate_ terminateWithSuccess];
4293 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4294 [delegate_ suspendWithAnimation:YES];
4295 else
4296 [delegate_ suspend];*/
4297 break;
4298
4299 case 2:
4300 system("launchctl stop com.apple.SpringBoard");
4301 break;
4302
4303 case 3:
4304 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4305 break;
4306
4307 case 4:
4308 system("reboot");
4309 break;
4310 }
4311 }
4312
4313 - (void) _retachThread {
4314 UINavigationItem *item([navbar_ topItem]);
4315 [item setTitle:UCLocalize("COMPLETE")];
4316
4317 [overlay_ addSubview:close_];
4318 [progress_ removeFromSuperview];
4319 [status_ removeFromSuperview];
4320
4321 [database_ popErrorWithTitle:title_];
4322 [delegate_ progressViewIsComplete:self];
4323
4324 if (Finish_ < 4) {
4325 FileFd file;
4326 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4327 _error->Discard();
4328 else {
4329 MMap mmap(file, MMap::ReadOnly);
4330 SHA1Summation sha1;
4331 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4332 if (!(notifyconf_ == sha1.Result()))
4333 Finish_ = 4;
4334 }
4335 }
4336
4337 if (Finish_ < 3) {
4338 FileFd file;
4339 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4340 _error->Discard();
4341 else {
4342 MMap mmap(file, MMap::ReadOnly);
4343 SHA1Summation sha1;
4344 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4345 if (!(springlist_ == sha1.Result()))
4346 Finish_ = 3;
4347 }
4348 }
4349
4350 switch (Finish_) {
4351 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4352 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4353 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4354 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4355 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4356 }
4357
4358 #define ListCache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4359 #define IconCache_ "/User/Library/Caches/com.apple.springboard-imagecache-icons.plist"
4360
4361 unlink(IconCache_);
4362
4363 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ListCache_]) {
4364 [cache autorelease];
4365
4366 NSFileManager *manager([NSFileManager defaultManager]);
4367 NSError *error(nil);
4368
4369 id system([cache objectForKey:@"System"]);
4370 if (system == nil)
4371 goto error;
4372
4373 struct stat info;
4374 if (stat(ListCache_, &info) == -1)
4375 goto error;
4376
4377 [system removeAllObjects];
4378
4379 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4380 for (NSString *app in apps)
4381 if ([app hasSuffix:@".app"]) {
4382 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4383 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4384 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4385 [info autorelease];
4386 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4387 [info setObject:path forKey:@"Path"];
4388 [info setObject:@"System" forKey:@"ApplicationType"];
4389 [system addInfoDictionary:info];
4390 }
4391 }
4392 }
4393 } else goto error;
4394
4395 [cache writeToFile:@ListCache_ atomically:YES];
4396
4397 if (chown(ListCache_, info.st_uid, info.st_gid) == -1)
4398 goto error;
4399 if (chmod(ListCache_, info.st_mode) == -1)
4400 goto error;
4401
4402 if (false) error:
4403 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4404 }
4405
4406 notify_post("com.apple.mobile.application_installed");
4407
4408 [delegate_ setStatusBarShowsProgress:NO];
4409 }
4410
4411 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4412 [[data target] performSelector:[data selector] withObject:[data object]];
4413 [data release];
4414
4415 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4416 }
4417
4418 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4419 if (title_ != nil)
4420 [title_ release];
4421 if (title == nil)
4422 title_ = nil;
4423 else
4424 title_ = [title retain];
4425
4426 UINavigationItem *item([navbar_ topItem]);
4427 [item setTitle:title_];
4428
4429 [status_ setText:nil];
4430 [output_ setText:@""];
4431 [progress_ setProgress:0];
4432
4433 [close_ removeFromSuperview];
4434 [overlay_ addSubview:progress_];
4435 [overlay_ addSubview:status_];
4436
4437 [delegate_ setStatusBarShowsProgress:YES];
4438 running_ = YES;
4439
4440 {
4441 FileFd file;
4442 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4443 _error->Discard();
4444 else {
4445 MMap mmap(file, MMap::ReadOnly);
4446 SHA1Summation sha1;
4447 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4448 notifyconf_ = sha1.Result();
4449 }
4450 }
4451
4452 {
4453 FileFd file;
4454 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4455 _error->Discard();
4456 else {
4457 MMap mmap(file, MMap::ReadOnly);
4458 SHA1Summation sha1;
4459 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4460 springlist_ = sha1.Result();
4461 }
4462 }
4463
4464 [transition_ transition:6 toView:overlay_];
4465
4466 [NSThread
4467 detachNewThreadSelector:@selector(_detachNewThreadData:)
4468 toTarget:self
4469 withObject:[[ProgressData alloc]
4470 initWithSelector:selector
4471 target:target
4472 object:object
4473 ]
4474 ];
4475 }
4476
4477 - (void) repairWithSelector:(SEL)selector {
4478 [self
4479 detachNewThreadSelector:selector
4480 toTarget:database_
4481 withObject:nil
4482 title:UCLocalize("REPAIRING")
4483 ];
4484 }
4485
4486 - (void) setConfigurationData:(NSString *)data {
4487 [self
4488 performSelectorOnMainThread:@selector(_setConfigurationData:)
4489 withObject:data
4490 waitUntilDone:YES
4491 ];
4492 }
4493
4494 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4495 CYActionSheet *sheet([[[CYActionSheet alloc]
4496 initWithTitle:title
4497 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4498 defaultButtonIndex:0
4499 ] autorelease]);
4500
4501 [sheet setBodyText:error];
4502 [sheet yieldToPopupAlertAnimated:YES];
4503 [sheet dismiss];
4504 }
4505
4506 - (void) setProgressTitle:(NSString *)title {
4507 [self
4508 performSelectorOnMainThread:@selector(_setProgressTitle:)
4509 withObject:title
4510 waitUntilDone:YES
4511 ];
4512 }
4513
4514 - (void) setProgressPercent:(float)percent {
4515 [self
4516 performSelectorOnMainThread:@selector(_setProgressPercent:)
4517 withObject:[NSNumber numberWithFloat:percent]
4518 waitUntilDone:YES
4519 ];
4520 }
4521
4522 - (void) startProgress {
4523 }
4524
4525 - (void) addProgressOutput:(NSString *)output {
4526 [self
4527 performSelectorOnMainThread:@selector(_addProgressOutput:)
4528 withObject:output
4529 waitUntilDone:YES
4530 ];
4531 }
4532
4533 - (bool) isCancelling:(size_t)received {
4534 return false;
4535 }
4536
4537 - (void) _setConfigurationData:(NSString *)data {
4538 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4539
4540 if (!conffile_r(data)) {
4541 lprintf("E:invalid conffile\n");
4542 return;
4543 }
4544
4545 NSString *ofile = conffile_r[1];
4546 //NSString *nfile = conffile_r[2];
4547
4548 UIActionSheet *sheet = [[[UIActionSheet alloc]
4549 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4550 buttons:[NSArray arrayWithObjects:
4551 UCLocalize("KEEP_OLD_COPY"),
4552 UCLocalize("ACCEPT_NEW_COPY"),
4553 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4554 nil]
4555 defaultButtonIndex:0
4556 delegate:self
4557 context:@"conffile"
4558 ] autorelease];
4559
4560 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4561 [sheet popupAlertAnimated:YES];
4562 }
4563
4564 - (void) _setProgressTitle:(NSString *)title {
4565 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4566 for (size_t i(0), e([words count]); i != e; ++i) {
4567 NSString *word([words objectAtIndex:i]);
4568 if (Package *package = [database_ packageWithName:word])
4569 [words replaceObjectAtIndex:i withObject:[package name]];
4570 }
4571
4572 [status_ setText:[words componentsJoinedByString:@" "]];
4573 }
4574
4575 - (void) _setProgressPercent:(NSNumber *)percent {
4576 [progress_ setProgress:[percent floatValue]];
4577 }
4578
4579 - (void) _addProgressOutput:(NSString *)output {
4580 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4581 CGSize size = [output_ contentSize];
4582 CGRect rect = {{0, size.height}, {size.width, 0}};
4583 [output_ scrollRectToVisible:rect animated:YES];
4584 }
4585
4586 - (BOOL) isRunning {
4587 return running_;
4588 }
4589
4590 @end
4591 /* }}} */
4592
4593 /* Package Cell {{{ */
4594 @interface ContentView : UIView {
4595 _transient id delegate_;
4596 }
4597
4598 @end
4599
4600 @interface PackageCell : UITableViewCell {
4601 UIImage *icon_;
4602 NSString *name_;
4603 NSString *description_;
4604 bool commercial_;
4605 NSString *source_;
4606 UIImage *badge_;
4607 Package *package_;
4608 UIColor *color_;
4609 ContentView *content_;
4610 BOOL faded_;
4611 float fade_;
4612 UIImage *placard_;
4613 }
4614
4615 - (PackageCell *) init;
4616 - (void) setPackage:(Package *)package;
4617
4618 + (int) heightForPackage:(Package *)package;
4619 - (void) drawContentRect:(CGRect)rect;
4620
4621 @end
4622
4623 @implementation ContentView
4624
4625 - (id) initWithFrame:(CGRect)frame {
4626 if ((self = [super initWithFrame:frame]) != nil) {
4627 } return self;
4628 }
4629
4630 - (void) setDelegate:(id)delegate {
4631 delegate_ = delegate;
4632 }
4633
4634 - (void) drawRect:(CGRect)rect {
4635 [super drawRect:rect];
4636 [delegate_ drawContentRect:rect];
4637 }
4638
4639 @end
4640
4641 @implementation PackageCell
4642
4643 - (void) clearPackage {
4644 if (icon_ != nil) {
4645 [icon_ release];
4646 icon_ = nil;
4647 }
4648
4649 if (name_ != nil) {
4650 [name_ release];
4651 name_ = nil;
4652 }
4653
4654 if (description_ != nil) {
4655 [description_ release];
4656 description_ = nil;
4657 }
4658
4659 if (source_ != nil) {
4660 [source_ release];
4661 source_ = nil;
4662 }
4663
4664 if (badge_ != nil) {
4665 [badge_ release];
4666 badge_ = nil;
4667 }
4668
4669 if (placard_ != nil) {
4670 [placard_ release];
4671 placard_ = nil;
4672 }
4673
4674 [package_ release];
4675 package_ = nil;
4676 }
4677
4678 - (void) dealloc {
4679 [self clearPackage];
4680 [content_ release];
4681 [color_ release];
4682 [super dealloc];
4683 }
4684
4685 - (float) fade {
4686 return faded_ ? [self selectionPercent] : fade_;
4687 }
4688
4689 - (PackageCell *) init {
4690 CGRect frame(CGRectMake(0, 0, 320, 74));
4691 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4692 UIView *content([self contentView]);
4693 CGRect bounds([content bounds]);
4694 content_ = [[ContentView alloc] initWithFrame:bounds];
4695 [content_ setDelegate:self];
4696 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4697 [content_ setOpaque:YES];
4698 [content addSubview:content_];
4699 if ([self respondsToSelector:@selector(selectionPercent)])
4700 faded_ = YES;
4701 } return self;
4702 }
4703
4704 - (void) _setBackgroundColor {
4705 UIColor *color;
4706 if (NSString *mode = [package_ mode]) {
4707 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4708 color = remove ? RemovingColor_ : InstallingColor_;
4709 } else
4710 color = [UIColor whiteColor];
4711
4712 [content_ setBackgroundColor:color];
4713 [self setNeedsDisplay];
4714 }
4715
4716 - (void) setPackage:(Package *)package {
4717 [self clearPackage];
4718 [package parse];
4719
4720 Source *source = [package source];
4721
4722 icon_ = [[package icon] retain];
4723 name_ = [[package name] retain];
4724 description_ = [[package shortDescription] retain];
4725 commercial_ = [package isCommercial];
4726
4727 package_ = [package retain];
4728
4729 NSString *label = nil;
4730 bool trusted = false;
4731
4732 if (source != nil) {
4733 label = [source label];
4734 trusted = [source trusted];
4735 } else if ([[package id] isEqualToString:@"firmware"])
4736 label = UCLocalize("APPLE");
4737 else
4738 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4739
4740 NSString *from(label);
4741
4742 NSString *section = [package simpleSection];
4743 if (section != nil && ![section isEqualToString:label]) {
4744 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4745 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4746 }
4747
4748 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4749 source_ = [from retain];
4750
4751 if (NSString *purpose = [package primaryPurpose])
4752 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4753 badge_ = [badge_ retain];
4754
4755 if ([package installed] != nil)
4756 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4757 placard_ = [placard_ retain];
4758
4759 [self _setBackgroundColor];
4760 [content_ setNeedsDisplay];
4761 }
4762
4763 - (void) drawContentRect:(CGRect)rect {
4764 bool selected([self isSelected]);
4765
4766 #if 0
4767 CGContextRef context(UIGraphicsGetCurrentContext());
4768 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4769 CGContextFillRect(context, rect);
4770 #endif
4771
4772 if (icon_ != nil) {
4773 CGRect rect;
4774 rect.size = [icon_ size];
4775
4776 rect.size.width /= 2;
4777 rect.size.height /= 2;
4778
4779 rect.origin.x = 25 - rect.size.width / 2;
4780 rect.origin.y = 25 - rect.size.height / 2;
4781
4782 [icon_ drawInRect:rect];
4783 }
4784
4785 if (badge_ != nil) {
4786 CGSize size = [badge_ size];
4787
4788 [badge_ drawAtPoint:CGPointMake(
4789 36 - size.width / 2,
4790 36 - size.height / 2
4791 )];
4792 }
4793
4794 if (selected)
4795 UISetColor(White_);
4796
4797 if (!selected)
4798 UISetColor(commercial_ ? Purple_ : Black_);
4799 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(placard_ == nil ? 240 : 214) withFont:Font18Bold_ ellipsis:2];
4800 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4801
4802 if (!selected)
4803 UISetColor(commercial_ ? Purplish_ : Gray_);
4804 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:274 withFont:Font14_ ellipsis:2];
4805
4806 if (placard_ != nil)
4807 [placard_ drawAtPoint:CGPointMake(268, 9)];
4808 }
4809
4810 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4811 //[self _setBackgroundColor];
4812 [super setSelected:selected animated:fade];
4813 [content_ setNeedsDisplay];
4814 }
4815
4816 + (int) heightForPackage:(Package *)package {
4817 return 73;
4818 }
4819
4820 @end
4821 /* }}} */
4822 /* Section Cell {{{ */
4823 @interface SectionCell : UISimpleTableCell {
4824 NSString *section_;
4825 NSString *name_;
4826 NSString *count_;
4827 UIImage *icon_;
4828 _UISwitchSlider *switch_;
4829 BOOL editing_;
4830 }
4831
4832 - (id) init;
4833 - (void) setSection:(Section *)section editing:(BOOL)editing;
4834
4835 @end
4836
4837 @implementation SectionCell
4838
4839 - (void) clearSection {
4840 if (section_ != nil) {
4841 [section_ release];
4842 section_ = nil;
4843 }
4844
4845 if (name_ != nil) {
4846 [name_ release];
4847 name_ = nil;
4848 }
4849
4850 if (count_ != nil) {
4851 [count_ release];
4852 count_ = nil;
4853 }
4854 }
4855
4856 - (void) dealloc {
4857 [self clearSection];
4858 [icon_ release];
4859 [switch_ release];
4860 [super dealloc];
4861 }
4862
4863 - (id) init {
4864 if ((self = [super init]) != nil) {
4865 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4866
4867 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4868 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4869 } return self;
4870 }
4871
4872 - (void) onSwitch:(id)sender {
4873 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4874 if (metadata == nil) {
4875 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4876 [Sections_ setObject:metadata forKey:section_];
4877 }
4878
4879 Changed_ = true;
4880 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4881 }
4882
4883 - (void) setSection:(Section *)section editing:(BOOL)editing {
4884 if (editing != editing_) {
4885 if (editing_)
4886 [switch_ removeFromSuperview];
4887 else
4888 [self addSubview:switch_];
4889 editing_ = editing;
4890 }
4891
4892 [self clearSection];
4893
4894 if (section == nil) {
4895 name_ = [UCLocalize("ALL_PACKAGES") retain];
4896 count_ = nil;
4897 } else {
4898 section_ = [section localized];
4899 if (section_ != nil)
4900 section_ = [section_ retain];
4901 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4902 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4903
4904 if (editing_)
4905 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4906 }
4907 }
4908
4909 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4910 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4911
4912 if (selected)
4913 UISetColor(White_);
4914
4915 if (!selected)
4916 UISetColor(Black_);
4917 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4918
4919 CGSize size = [count_ sizeWithFont:Font14_];
4920
4921 UISetColor(White_);
4922 if (count_ != nil)
4923 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4924
4925 [super drawContentInRect:rect selected:selected];
4926 }
4927
4928 @end
4929 /* }}} */
4930
4931 /* File Table {{{ */
4932 @interface FileTable : RVPage {
4933 _transient Database *database_;
4934 Package *package_;
4935 NSString *name_;
4936 NSMutableArray *files_;
4937 UITable *list_;
4938 }
4939
4940 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4941 - (void) setPackage:(Package *)package;
4942
4943 @end
4944
4945 @implementation FileTable
4946
4947 - (void) dealloc {
4948 if (package_ != nil)
4949 [package_ release];
4950 if (name_ != nil)
4951 [name_ release];
4952 [files_ release];
4953 [list_ release];
4954 [super dealloc];
4955 }
4956
4957 - (int) numberOfRowsInTable:(UITable *)table {
4958 return files_ == nil ? 0 : [files_ count];
4959 }
4960
4961 - (float) table:(UITable *)table heightForRow:(int)row {
4962 return 24;
4963 }
4964
4965 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4966 if (reusing == nil) {
4967 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4968 UIFont *font = [UIFont systemFontOfSize:16];
4969 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4970 }
4971 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4972 return reusing;
4973 }
4974
4975 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4976 return NO;
4977 }
4978
4979 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4980 if ((self = [super initWithBook:book]) != nil) {
4981 database_ = database;
4982
4983 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4984
4985 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4986 [self addSubview:list_];
4987
4988 UITableColumn *column = [[[UITableColumn alloc]
4989 initWithTitle:UCLocalize("NAME")
4990 identifier:@"name"
4991 width:[self frame].size.width
4992 ] autorelease];
4993
4994 [list_ setDataSource:self];
4995 [list_ setSeparatorStyle:1];
4996 [list_ addTableColumn:column];
4997 [list_ setDelegate:self];
4998 [list_ setReusesTableCells:YES];
4999 } return self;
5000 }
5001
5002 - (void) setPackage:(Package *)package {
5003 if (package_ != nil) {
5004 [package_ autorelease];
5005 package_ = nil;
5006 }
5007
5008 if (name_ != nil) {
5009 [name_ release];
5010 name_ = nil;
5011 }
5012
5013 [files_ removeAllObjects];
5014
5015 if (package != nil) {
5016 package_ = [package retain];
5017 name_ = [[package id] retain];
5018
5019 if (NSArray *files = [package files])
5020 [files_ addObjectsFromArray:files];
5021
5022 if ([files_ count] != 0) {
5023 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5024 [files_ removeObjectAtIndex:0];
5025 [files_ sortUsingSelector:@selector(compareByPath:)];
5026
5027 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5028 [stack addObject:@"/"];
5029
5030 for (int i(0), e([files_ count]); i != e; ++i) {
5031 NSString *file = [files_ objectAtIndex:i];
5032 while (![file hasPrefix:[stack lastObject]])
5033 [stack removeLastObject];
5034 NSString *directory = [stack lastObject];
5035 [stack addObject:[file stringByAppendingString:@"/"]];
5036 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5037 ([stack count] - 2) * 3, "",
5038 [file substringFromIndex:[directory length]]
5039 ]];
5040 }
5041 }
5042 }
5043
5044 [list_ reloadData];
5045 }
5046
5047 - (void) resetViewAnimated:(BOOL)animated {
5048 [list_ resetViewAnimated:animated];
5049 }
5050
5051 - (void) reloadData {
5052 [self setPackage:[database_ packageWithName:name_]];
5053 [self reloadButtons];
5054 }
5055
5056 - (NSString *) title {
5057 return UCLocalize("INSTALLED_FILES");
5058 }
5059
5060 - (NSString *) backButtonTitle {
5061 return UCLocalize("FILES");
5062 }
5063
5064 @end
5065 /* }}} */
5066 /* Package View {{{ */
5067 @interface PackageView : CydiaBrowserView {
5068 _transient Database *database_;
5069 Package *package_;
5070 NSString *name_;
5071 bool commercial_;
5072 NSMutableArray *buttons_;
5073 }
5074
5075 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5076 - (void) setPackage:(Package *)package;
5077
5078 @end
5079
5080 @implementation PackageView
5081
5082 - (void) dealloc {
5083 if (package_ != nil)
5084 [package_ release];
5085 if (name_ != nil)
5086 [name_ release];
5087 [buttons_ release];
5088 [super dealloc];
5089 }
5090
5091 - (void) release {
5092 if ([self retainCount] == 1)
5093 [delegate_ setPackageView:self];
5094 [super release];
5095 }
5096
5097 /* XXX: this is not safe at all... localization of /fail/ */
5098 - (void) _clickButtonWithName:(NSString *)name {
5099 if ([name isEqualToString:UCLocalize("CLEAR")])
5100 [delegate_ clearPackage:package_];
5101 else if ([name isEqualToString:UCLocalize("INSTALL")])
5102 [delegate_ installPackage:package_];
5103 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5104 [delegate_ installPackage:package_];
5105 else if ([name isEqualToString:UCLocalize("REMOVE")])
5106 [delegate_ removePackage:package_];
5107 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5108 [delegate_ installPackage:package_];
5109 else _assert(false);
5110 }
5111
5112 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5113 NSString *context([sheet context]);
5114
5115 if ([context isEqualToString:@"modify"]) {
5116 int count = [buttons_ count];
5117 _assert(count != 0);
5118 _assert(button <= count + 1);
5119
5120 if (count != button - 1)
5121 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5122
5123 [sheet dismiss];
5124 } else
5125 [super alertSheet:sheet buttonClicked:button];
5126 }
5127
5128 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5129 return [super webView:sender didFinishLoadForFrame:frame];
5130 }
5131
5132 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5133 [super webView:sender didClearWindowObject:window forFrame:frame];
5134 [window setValue:package_ forKey:@"package"];
5135 }
5136
5137 - (bool) _allowJavaScriptPanel {
5138 return commercial_;
5139 }
5140
5141 #if !AlwaysReload
5142 - (void) __rightButtonClicked {
5143 int count([buttons_ count]);
5144 if (count == 0)
5145 return;
5146
5147 if (count == 1)
5148 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5149 else {
5150 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5151 [buttons addObjectsFromArray:buttons_];
5152 [buttons addObject:UCLocalize("CANCEL")];
5153
5154 [delegate_ slideUp:[[[UIActionSheet alloc]
5155 initWithTitle:nil
5156 buttons:buttons
5157 defaultButtonIndex:([buttons count] - 1)
5158 delegate:self
5159 context:@"modify"
5160 ] autorelease]];
5161 }
5162 }
5163
5164 - (void) _rightButtonClicked {
5165 if (commercial_)
5166 [super _rightButtonClicked];
5167 else
5168 [self __rightButtonClicked];
5169 }
5170 #endif
5171
5172 - (id) _rightButtonTitle {
5173 int count = [buttons_ count];
5174 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5175 }
5176
5177 - (NSString *) backButtonTitle {
5178 return @"Details";
5179 }
5180
5181 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5182 if ((self = [super initWithBook:book]) != nil) {
5183 database_ = database;
5184 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5185 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5186 } return self;
5187 }
5188
5189 - (void) setPackage:(Package *)package {
5190 if (package_ != nil) {
5191 [package_ autorelease];
5192 package_ = nil;
5193 }
5194
5195 if (name_ != nil) {
5196 [name_ release];
5197 name_ = nil;
5198 }
5199
5200 [buttons_ removeAllObjects];
5201
5202 if (package != nil) {
5203 [package parse];
5204
5205 package_ = [package retain];
5206 name_ = [[package id] retain];
5207 commercial_ = [package isCommercial];
5208
5209 if ([package_ mode] != nil)
5210 [buttons_ addObject:UCLocalize("CLEAR")];
5211 if ([package_ source] == nil);
5212 else if ([package_ upgradableAndEssential:NO])
5213 [buttons_ addObject:UCLocalize("UPGRADE")];
5214 else if ([package_ uninstalled])
5215 [buttons_ addObject:UCLocalize("INSTALL")];
5216 else
5217 [buttons_ addObject:UCLocalize("REINSTALL")];
5218 if (![package_ uninstalled])
5219 [buttons_ addObject:UCLocalize("REMOVE")];
5220
5221 if (special_ != NULL) {
5222 CGRect frame([webview_ frame]);
5223 frame.size.width = 320;
5224 frame.size.height = 0;
5225 [webview_ setFrame:frame];
5226
5227 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5228
5229 WebThreadLock();
5230 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5231
5232 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5233
5234 [self setFinishHook:nil];
5235 [self setPopupHook:nil];
5236 WebThreadUnlock();
5237
5238 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5239 [super callFunction:special_];
5240 }
5241 }
5242
5243 [self reloadButtons];
5244 }
5245
5246 - (bool) isLoading {
5247 return commercial_ ? [super isLoading] : false;
5248 }
5249
5250 - (void) reloadData {
5251 [self setPackage:[database_ packageWithName:name_]];
5252 }
5253
5254 @end
5255 /* }}} */
5256 /* Package Table {{{ */
5257 @interface PackageTable : RVPage {
5258 _transient Database *database_;
5259 NSString *title_;
5260 NSMutableArray *packages_;
5261 NSMutableArray *sections_;
5262 UITableView *list_;
5263 NSMutableArray *index_;
5264 NSMutableDictionary *indices_;
5265 }
5266
5267 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5268
5269 - (void) setDelegate:(id)delegate;
5270
5271 - (void) reloadData;
5272 - (void) resetCursor;
5273
5274 - (UITableView *) list;
5275
5276 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5277
5278 @end
5279
5280 @implementation PackageTable
5281
5282 - (void) dealloc {
5283 [list_ setDataSource:nil];
5284
5285 [title_ release];
5286 [packages_ release];
5287 [sections_ release];
5288 [list_ release];
5289 [index_ release];
5290 [indices_ release];
5291 [super dealloc];
5292 }
5293
5294 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5295 NSInteger count([sections_ count]);
5296 return count == 0 ? 1 : count;
5297 }
5298
5299 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5300 if ([sections_ count] == 0)
5301 return nil;
5302 return [[sections_ objectAtIndex:section] name];
5303 }
5304
5305 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5306 if ([sections_ count] == 0)
5307 return 0;
5308 return [[sections_ objectAtIndex:section] count];
5309 }
5310
5311 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5312 Section *section([sections_ objectAtIndex:[path section]]);
5313 NSInteger row([path row]);
5314 Package *package([packages_ objectAtIndex:([section row] + row)]);
5315 return package;
5316 }
5317
5318 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5319 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5320 if (cell == nil)
5321 cell = [[[PackageCell alloc] init] autorelease];
5322 [cell setPackage:[self packageAtIndexPath:path]];
5323 return cell;
5324 }
5325
5326 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5327 return 73;
5328 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5329 }
5330
5331 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5332 Package *package([self packageAtIndexPath:path]);
5333 package = [database_ packageWithName:[package id]];
5334 PackageView *view([delegate_ packageView]);
5335 [view setPackage:package];
5336 [view setDelegate:delegate_];
5337 [book_ pushPage:view];
5338 return path;
5339 }
5340
5341 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5342 return [packages_ count] > 20 ? index_ : nil;
5343 }
5344
5345 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5346 return index;
5347 }
5348
5349 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5350 if ((self = [super initWithBook:book]) != nil) {
5351 database_ = database;
5352 title_ = [title retain];
5353
5354 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5355 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5356
5357 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5358 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5359
5360 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5361 [list_ setDataSource:self];
5362 [list_ setDelegate:self];
5363
5364 [self addSubview:list_];
5365
5366 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5367 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5368 } return self;
5369 }
5370
5371 - (void) setDelegate:(id)delegate {
5372 delegate_ = delegate;
5373 }
5374
5375 - (bool) hasPackage:(Package *)package {
5376 return true;
5377 }
5378
5379 - (void) reloadData {
5380 NSArray *packages = [database_ packages];
5381
5382 [packages_ removeAllObjects];
5383 [sections_ removeAllObjects];
5384
5385 _profile(PackageTable$reloadData$Filter)
5386 for (Package *package in packages)
5387 if ([self hasPackage:package])
5388 [packages_ addObject:package];
5389 _end
5390
5391 [index_ removeAllObjects];
5392 [indices_ removeAllObjects];
5393
5394 Section *section = nil;
5395
5396 _profile(PackageTable$reloadData$Section)
5397 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5398 Package *package;
5399 unichar index;
5400
5401 _profile(PackageTable$reloadData$Section$Package)
5402 package = [packages_ objectAtIndex:offset];
5403 index = [package index];
5404 _end
5405
5406 if (section == nil || [section index] != index) {
5407 _profile(PackageTable$reloadData$Section$Allocate)
5408 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5409 _end
5410
5411 [index_ addObject:[section name]];
5412 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5413
5414 _profile(PackageTable$reloadData$Section$Add)
5415 [sections_ addObject:section];
5416 _end
5417 }
5418
5419 [section addToCount];
5420 }
5421 _end
5422
5423 _profile(PackageTable$reloadData$List)
5424 [list_ reloadData];
5425 _end
5426 }
5427
5428 - (NSString *) title {
5429 return title_;
5430 }
5431
5432 - (void) resetViewAnimated:(BOOL)animated {
5433 [list_ resetViewAnimated:animated];
5434 }
5435
5436 - (void) resetCursor {
5437 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5438 }
5439
5440 - (UITableView *) list {
5441 return list_;
5442 }
5443
5444 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5445 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5446 }
5447
5448 @end
5449 /* }}} */
5450 /* Filtered Package Table {{{ */
5451 @interface FilteredPackageTable : PackageTable {
5452 SEL filter_;
5453 IMP imp_;
5454 id object_;
5455 }
5456
5457 - (void) setObject:(id)object;
5458
5459 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5460
5461 @end
5462
5463 @implementation FilteredPackageTable
5464
5465 - (void) dealloc {
5466 if (object_ != nil)
5467 [object_ release];
5468 [super dealloc];
5469 }
5470
5471 - (void) setObject:(id)object {
5472 if (object_ != nil)
5473 [object_ release];
5474 if (object == nil)
5475 object_ = nil;
5476 else
5477 object_ = [object retain];
5478 }
5479
5480 - (bool) hasPackage:(Package *)package {
5481 _profile(FilteredPackageTable$hasPackage)
5482 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5483 _end
5484 }
5485
5486 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5487 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5488 filter_ = filter;
5489 object_ = object == nil ? nil : [object retain];
5490
5491 /* XXX: this is an unsafe optimization of doomy hell */
5492 Method method(class_getInstanceMethod([Package class], filter));
5493 _assert(method != NULL);
5494 imp_ = method_getImplementation(method);
5495 _assert(imp_ != NULL);
5496
5497 [self reloadData];
5498 } return self;
5499 }
5500
5501 @end
5502 /* }}} */
5503
5504 /* Add Source View {{{ */
5505 @interface AddSourceView : RVPage {
5506 _transient Database *database_;
5507 }
5508
5509 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5510
5511 @end
5512
5513 @implementation AddSourceView
5514
5515 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5516 if ((self = [super initWithBook:book]) != nil) {
5517 database_ = database;
5518 } return self;
5519 }
5520
5521 @end
5522 /* }}} */
5523 /* Source Cell {{{ */
5524 @interface SourceCell : UITableCell {
5525 UIImage *icon_;
5526 NSString *origin_;
5527 NSString *description_;
5528 NSString *label_;
5529 }
5530
5531 - (void) dealloc;
5532
5533 - (SourceCell *) initWithSource:(Source *)source;
5534
5535 @end
5536
5537 @implementation SourceCell
5538
5539 - (void) dealloc {
5540 [icon_ release];
5541 [origin_ release];
5542 [description_ release];
5543 [label_ release];
5544 [super dealloc];
5545 }
5546
5547 - (SourceCell *) initWithSource:(Source *)source {
5548 if ((self = [super init]) != nil) {
5549 if (icon_ == nil)
5550 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5551 if (icon_ == nil)
5552 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5553 icon_ = [icon_ retain];
5554
5555 origin_ = [[source name] retain];
5556 label_ = [[source uri] retain];
5557 description_ = [[source description] retain];
5558 } return self;
5559 }
5560
5561 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5562 if (icon_ != nil)
5563 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5564
5565 if (selected)
5566 UISetColor(White_);
5567
5568 if (!selected)
5569 UISetColor(Black_);
5570 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5571
5572 if (!selected)
5573 UISetColor(Blue_);
5574 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5575
5576 if (!selected)
5577 UISetColor(Gray_);
5578 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5579
5580 [super drawContentInRect:rect selected:selected];
5581 }
5582
5583 @end
5584 /* }}} */
5585 /* Source Table {{{ */
5586 @interface SourceTable : RVPage {
5587 _transient Database *database_;
5588 UISectionList *list_;
5589 NSMutableArray *sources_;
5590 UIActionSheet *alert_;
5591 int offset_;
5592
5593 NSString *href_;
5594 UIProgressHUD *hud_;
5595 NSError *error_;
5596
5597 //NSURLConnection *installer_;
5598 NSURLConnection *trivial_;
5599 NSURLConnection *trivial_bz2_;
5600 NSURLConnection *trivial_gz_;
5601 //NSURLConnection *automatic_;
5602
5603 BOOL cydia_;
5604 }
5605
5606 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5607
5608 @end
5609
5610 @implementation SourceTable
5611
5612 - (void) _deallocConnection:(NSURLConnection *)connection {
5613 if (connection != nil) {
5614 [connection cancel];
5615 //[connection setDelegate:nil];
5616 [connection release];
5617 }
5618 }
5619
5620 - (void) dealloc {
5621 [[list_ table] setDelegate:nil];
5622 [list_ setDataSource:nil];
5623
5624 if (href_ != nil)
5625 [href_ release];
5626 if (hud_ != nil)
5627 [hud_ release];
5628 if (error_ != nil)
5629 [error_ release];
5630
5631 //[self _deallocConnection:installer_];
5632 [self _deallocConnection:trivial_];
5633 [self _deallocConnection:trivial_gz_];
5634 [self _deallocConnection:trivial_bz2_];
5635 //[self _deallocConnection:automatic_];
5636
5637 [sources_ release];
5638 [list_ release];
5639 [super dealloc];
5640 }
5641
5642 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5643 return offset_ == 0 ? 1 : 2;
5644 }
5645
5646 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5647 switch (section + (offset_ == 0 ? 1 : 0)) {
5648 case 0: return UCLocalize("ENTERED_BY_USER");
5649 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5650
5651 _nodefault
5652 }
5653 }
5654
5655 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5656 switch (section + (offset_ == 0 ? 1 : 0)) {
5657 case 0: return 0;
5658 case 1: return offset_;
5659
5660 _nodefault
5661 }
5662 }
5663
5664 - (int) numberOfRowsInTable:(UITable *)table {
5665 return [sources_ count];
5666 }
5667
5668 - (float) table:(UITable *)table heightForRow:(int)row {
5669 Source *source = [sources_ objectAtIndex:row];
5670 return [source description] == nil ? 56 : 73;
5671 }
5672
5673 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5674 Source *source = [sources_ objectAtIndex:row];
5675 // XXX: weird warning, stupid selectors ;P
5676 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5677 }
5678
5679 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5680 return YES;
5681 }
5682
5683 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5684 return YES;
5685 }
5686
5687 - (void) tableRowSelected:(NSNotification*)notification {
5688 UITable *table([list_ table]);
5689 int row([table selectedRow]);
5690 if (row == INT_MAX)
5691 return;
5692
5693 Source *source = [sources_ objectAtIndex:row];
5694
5695 PackageTable *packages = [[[FilteredPackageTable alloc]
5696 initWithBook:book_
5697 database:database_
5698 title:[source label]
5699 filter:@selector(isVisibleInSource:)
5700 with:source
5701 ] autorelease];
5702
5703 [packages setDelegate:delegate_];
5704
5705 [book_ pushPage:packages];
5706 }
5707
5708 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5709 Source *source = [sources_ objectAtIndex:row];
5710 return [source record] != nil;
5711 }
5712
5713 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5714 [[list_ table] setDeleteConfirmationRow:row];
5715 }
5716
5717 - (void) table:(UITable *)table deleteRow:(int)row {
5718 Source *source = [sources_ objectAtIndex:row];
5719 [Sources_ removeObjectForKey:[source key]];
5720 [delegate_ syncData];
5721 }
5722
5723 - (void) complete {
5724 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5725 @"deb", @"Type",
5726 href_, @"URI",
5727 @"./", @"Distribution",
5728 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5729
5730 [delegate_ syncData];
5731 }
5732
5733 - (NSString *) getWarning {
5734 NSString *href(href_);
5735 NSRange colon([href rangeOfString:@"://"]);
5736 if (colon.location != NSNotFound)
5737 href = [href substringFromIndex:(colon.location + 3)];
5738 href = [href stringByAddingPercentEscapes];
5739 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5740 href = [href stringByCachingURLWithCurrentCDN];
5741
5742 NSURL *url([NSURL URLWithString:href]);
5743
5744 NSStringEncoding encoding;
5745 NSError *error(nil);
5746
5747 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5748 return [warning length] == 0 ? nil : warning;
5749 return nil;
5750 }
5751
5752 - (void) _endConnection:(NSURLConnection *)connection {
5753 NSURLConnection **field = NULL;
5754 if (connection == trivial_)
5755 field = &trivial_;
5756 else if (connection == trivial_bz2_)
5757 field = &trivial_bz2_;
5758 else if (connection == trivial_gz_)
5759 field = &trivial_gz_;
5760 _assert(field != NULL);
5761 [connection release];
5762 *field = nil;
5763
5764 if (
5765 trivial_ == nil &&
5766 trivial_bz2_ == nil &&
5767 trivial_gz_ == nil
5768 ) {
5769 bool defer(false);
5770
5771 if (cydia_) {
5772 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5773 defer = true;
5774
5775 UIActionSheet *sheet = [[[UIActionSheet alloc]
5776 initWithTitle:UCLocalize("SOURCE_WARNING")
5777 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5778 defaultButtonIndex:0
5779 delegate:self
5780 context:@"warning"
5781 ] autorelease];
5782
5783 [sheet setNumberOfRows:1];
5784
5785 [sheet setBodyText:warning];
5786 [sheet popupAlertAnimated:YES];
5787 } else
5788 [self complete];
5789 } else if (error_ != nil) {
5790 UIActionSheet *sheet = [[[UIActionSheet alloc]
5791 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5792 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5793 defaultButtonIndex:0
5794 delegate:self
5795 context:@"urlerror"
5796 ] autorelease];
5797
5798 [sheet setBodyText:[error_ localizedDescription]];
5799 [sheet popupAlertAnimated:YES];
5800 } else {
5801 UIActionSheet *sheet = [[[UIActionSheet alloc]
5802 initWithTitle:UCLocalize("NOT_REPOSITORY")
5803 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5804 defaultButtonIndex:0
5805 delegate:self
5806 context:@"trivial"
5807 ] autorelease];
5808
5809 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5810 [sheet popupAlertAnimated:YES];
5811 }
5812
5813 [delegate_ setStatusBarShowsProgress:NO];
5814 [delegate_ removeProgressHUD:hud_];
5815
5816 [hud_ autorelease];
5817 hud_ = nil;
5818
5819 if (!defer) {
5820 [href_ release];
5821 href_ = nil;
5822 }
5823
5824 if (error_ != nil) {
5825 [error_ release];
5826 error_ = nil;
5827 }
5828 }
5829 }
5830
5831 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5832 switch ([response statusCode]) {
5833 case 200:
5834 cydia_ = YES;
5835 }
5836 }
5837
5838 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5839 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5840 if (error_ != nil)
5841 error_ = [error retain];
5842 [self _endConnection:connection];
5843 }
5844
5845 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5846 [self _endConnection:connection];
5847 }
5848
5849 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5850 NSMutableURLRequest *request = [NSMutableURLRequest
5851 requestWithURL:[NSURL URLWithString:href]
5852 cachePolicy:NSURLRequestUseProtocolCachePolicy
5853 timeoutInterval:20.0
5854 ];
5855
5856 [request setHTTPMethod:method];
5857
5858 if (Machine_ != NULL)
5859 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5860 if (UniqueID_ != nil)
5861 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5862
5863 if (Role_ != nil)
5864 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5865
5866 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5867 }
5868
5869 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5870 NSString *context([sheet context]);
5871
5872 if ([context isEqualToString:@"source"]) {
5873 switch (button) {
5874 case 1: {
5875 NSString *href = [[sheet textField] text];
5876
5877 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5878
5879 if (![href hasSuffix:@"/"])
5880 href_ = [href stringByAppendingString:@"/"];
5881 else
5882 href_ = href;
5883 href_ = [href_ retain];
5884
5885 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5886 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5887 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5888 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5889
5890 cydia_ = false;
5891
5892 hud_ = [[delegate_ addProgressHUD] retain];
5893 [hud_ setText:UCLocalize("VERIFYING_URL")];
5894 } break;
5895
5896 case 2:
5897 break;
5898
5899 _nodefault
5900 }
5901
5902 [sheet dismiss];
5903 } else if ([context isEqualToString:@"trivial"])
5904 [sheet dismiss];
5905 else if ([context isEqualToString:@"urlerror"])
5906 [sheet dismiss];
5907 else if ([context isEqualToString:@"warning"]) {
5908 switch (button) {
5909 case 1:
5910 [self complete];
5911 break;
5912
5913 case 2:
5914 break;
5915
5916 _nodefault
5917 }
5918
5919 [href_ release];
5920 href_ = nil;
5921
5922 [sheet dismiss];
5923 }
5924 }
5925
5926 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5927 if ((self = [super initWithBook:book]) != nil) {
5928 database_ = database;
5929 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5930
5931 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5932 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5933 [list_ setShouldHideHeaderInShortLists:NO];
5934
5935 [self addSubview:list_];
5936 [list_ setDataSource:self];
5937
5938 UITableColumn *column = [[UITableColumn alloc]
5939 initWithTitle:UCLocalize("NAME")
5940 identifier:@"name"
5941 width:[self frame].size.width
5942 ];
5943
5944 UITable *table = [list_ table];
5945 [table setSeparatorStyle:1];
5946 [table addTableColumn:column];
5947 [table setDelegate:self];
5948
5949 [self reloadData];
5950
5951 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5952 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5953 } return self;
5954 }
5955
5956 - (void) reloadData {
5957 pkgSourceList list;
5958 if (!list.ReadMainList())
5959 return;
5960
5961 [sources_ removeAllObjects];
5962 [sources_ addObjectsFromArray:[database_ sources]];
5963 _trace();
5964 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5965 _trace();
5966
5967 int count([sources_ count]);
5968 for (offset_ = 0; offset_ != count; ++offset_) {
5969 Source *source = [sources_ objectAtIndex:offset_];
5970 if ([source record] == nil)
5971 break;
5972 }
5973
5974 [list_ reloadData];
5975 }
5976
5977 - (void) resetViewAnimated:(BOOL)animated {
5978 [list_ resetViewAnimated:animated];
5979 }
5980
5981 - (void) _leftButtonClicked {
5982 /*[book_ pushPage:[[[AddSourceView alloc]
5983 initWithBook:book_
5984 database:database_
5985 ] autorelease]];*/
5986
5987 UIActionSheet *sheet = [[[UIActionSheet alloc]
5988 initWithTitle:UCLocalize("ENTER_APT_URL")
5989 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
5990 defaultButtonIndex:0
5991 delegate:self
5992 context:@"source"
5993 ] autorelease];
5994
5995 [sheet setNumberOfRows:1];
5996
5997 [sheet addTextFieldWithValue:@"http://" label:@""];
5998
5999 UITextInputTraits *traits = [[sheet textField] textInputTraits];
6000 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6001 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6002 [traits setKeyboardType:UIKeyboardTypeURL];
6003 // XXX: UIReturnKeyDone
6004 [traits setReturnKeyType:UIReturnKeyNext];
6005
6006 [sheet popupAlertAnimated:YES];
6007 }
6008
6009 - (void) _rightButtonClicked {
6010 UITable *table = [list_ table];
6011 BOOL editing = [table isRowDeletionEnabled];
6012 [table enableRowDeletion:!editing animated:YES];
6013 [book_ reloadButtonsForPage:self];
6014 }
6015
6016 - (NSString *) title {
6017 return UCLocalize("SOURCES");
6018 }
6019
6020 - (NSString *) leftButtonTitle {
6021 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6022 }
6023
6024 - (id) rightButtonTitle {
6025 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6026 }
6027
6028 - (UINavigationButtonStyle) rightButtonStyle {
6029 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6030 }
6031
6032 @end
6033 /* }}} */
6034
6035 /* Installed View {{{ */
6036 @interface InstalledView : RVPage {
6037 _transient Database *database_;
6038 FilteredPackageTable *packages_;
6039 BOOL expert_;
6040 }
6041
6042 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6043
6044 @end
6045
6046 @implementation InstalledView
6047
6048 - (void) dealloc {
6049 [packages_ release];
6050 [super dealloc];
6051 }
6052
6053 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6054 if ((self = [super initWithBook:book]) != nil) {
6055 database_ = database;
6056
6057 packages_ = [[FilteredPackageTable alloc]
6058 initWithBook:book
6059 database:database
6060 title:nil
6061 filter:@selector(isInstalledAndVisible:)
6062 with:[NSNumber numberWithBool:YES]
6063 ];
6064
6065 [self addSubview:packages_];
6066
6067 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6068 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6069 } return self;
6070 }
6071
6072 - (void) resetViewAnimated:(BOOL)animated {
6073 [packages_ resetViewAnimated:animated];
6074 }
6075
6076 - (void) reloadData {
6077 [packages_ reloadData];
6078 }
6079
6080 - (void) _rightButtonClicked {
6081 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6082 [packages_ reloadData];
6083 expert_ = !expert_;
6084 [book_ reloadButtonsForPage:self];
6085 }
6086
6087 - (NSString *) title {
6088 return UCLocalize("INSTALLED");
6089 }
6090
6091 - (NSString *) backButtonTitle {
6092 return UCLocalize("PACKAGES");
6093 }
6094
6095 - (id) rightButtonTitle {
6096 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6097 }
6098
6099 - (UINavigationButtonStyle) rightButtonStyle {
6100 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6101 }
6102
6103 - (void) setDelegate:(id)delegate {
6104 [super setDelegate:delegate];
6105 [packages_ setDelegate:delegate];
6106 }
6107
6108 @end
6109 /* }}} */
6110
6111 /* Home View {{{ */
6112 @interface HomeView : CydiaBrowserView {
6113 }
6114
6115 @end
6116
6117 @implementation HomeView
6118
6119 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6120 NSString *context([sheet context]);
6121
6122 if ([context isEqualToString:@"about"])
6123 [sheet dismiss];
6124 else
6125 [super alertSheet:sheet buttonClicked:button];
6126 }
6127
6128 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6129 [super _setMoreHeaders:request];
6130 if (ChipID_ != nil)
6131 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6132 }
6133
6134 - (void) _leftButtonClicked {
6135 UIActionSheet *sheet = [[[UIActionSheet alloc]
6136 initWithTitle:UCLocalize("ABOUT_CYDIA")
6137 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6138 defaultButtonIndex:0
6139 delegate:self
6140 context:@"about"
6141 ] autorelease];
6142
6143 [sheet setBodyText:
6144 @"Copyright (C) 2008-2009\n"
6145 "Jay Freeman (saurik)\n"
6146 "saurik@saurik.com\n"
6147 "http://www.saurik.com/\n"
6148 "\n"
6149 "The Okori Group\n"
6150 "http://www.theokorigroup.com/\n"
6151 "\n"
6152 "College of Creative Studies,\n"
6153 "University of California,\n"
6154 "Santa Barbara\n"
6155 "http://www.ccs.ucsb.edu/"
6156 ];
6157
6158 [sheet popupAlertAnimated:YES];
6159 }
6160
6161 - (NSString *) leftButtonTitle {
6162 return UCLocalize("ABOUT");
6163 }
6164
6165 @end
6166 /* }}} */
6167 /* Manage View {{{ */
6168 @interface ManageView : CydiaBrowserView {
6169 }
6170
6171 @end
6172
6173 @implementation ManageView
6174
6175 - (NSString *) title {
6176 return UCLocalize("MANAGE");
6177 }
6178
6179 - (void) _leftButtonClicked {
6180 [delegate_ askForSettings];
6181 [delegate_ updateData];
6182 }
6183
6184 - (NSString *) leftButtonTitle {
6185 return UCLocalize("SETTINGS");
6186 }
6187
6188 #if !AlwaysReload
6189 - (id) _rightButtonTitle {
6190 return Queuing_ ? UCLocalize("QUEUE") : nil;
6191 }
6192
6193 - (UINavigationButtonStyle) rightButtonStyle {
6194 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6195 }
6196
6197 - (void) _rightButtonClicked {
6198 [delegate_ queue];
6199 }
6200 #endif
6201
6202 - (bool) isLoading {
6203 return false;
6204 }
6205
6206 @end
6207 /* }}} */
6208
6209 /* Cydia Book {{{ */
6210 @interface CYBook : RVBook <
6211 ProgressDelegate
6212 > {
6213 _transient Database *database_;
6214 UINavigationBar *overlay_;
6215 UINavigationBar *underlay_;
6216 UIProgressIndicator *indicator_;
6217 UITextLabel *prompt_;
6218 UIProgressBar *progress_;
6219 UINavigationButton *cancel_;
6220 bool updating_;
6221 }
6222
6223 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6224 - (void) update;
6225 - (BOOL) updating;
6226
6227 @end
6228
6229 @implementation CYBook
6230
6231 - (void) dealloc {
6232 [overlay_ release];
6233 [indicator_ release];
6234 [prompt_ release];
6235 [progress_ release];
6236 [cancel_ release];
6237 [super dealloc];
6238 }
6239
6240 - (NSString *) getTitleForPage:(RVPage *)page {
6241 return [super getTitleForPage:page];
6242 }
6243
6244 - (BOOL) updating {
6245 return updating_;
6246 }
6247
6248 - (void) update {
6249 [UIView beginAnimations:nil context:NULL];
6250
6251 CGRect ovrframe = [overlay_ frame];
6252 ovrframe.origin.y = 0;
6253 [overlay_ setFrame:ovrframe];
6254
6255 CGRect barframe = [navbar_ frame];
6256 barframe.origin.y += ovrframe.size.height;
6257 [navbar_ setFrame:barframe];
6258
6259 CGRect trnframe = [transition_ frame];
6260 trnframe.origin.y += ovrframe.size.height;
6261 trnframe.size.height -= ovrframe.size.height;
6262 [transition_ setFrame:trnframe];
6263
6264 [UIView endAnimations];
6265
6266 [indicator_ startAnimation];
6267 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6268 [progress_ setProgress:0];
6269
6270 updating_ = true;
6271 [overlay_ addSubview:cancel_];
6272
6273 [NSThread
6274 detachNewThreadSelector:@selector(_update)
6275 toTarget:self
6276 withObject:nil
6277 ];
6278 }
6279
6280 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6281 NSString *context([sheet context]);
6282
6283 if ([context isEqualToString:@"refresh"])
6284 [sheet dismiss];
6285 }
6286
6287 - (void) _update_ {
6288 updating_ = false;
6289
6290 [indicator_ stopAnimation];
6291
6292 [UIView beginAnimations:nil context:NULL];
6293
6294 CGRect ovrframe = [overlay_ frame];
6295 ovrframe.origin.y = -ovrframe.size.height;
6296 [overlay_ setFrame:ovrframe];
6297
6298 CGRect barframe = [navbar_ frame];
6299 barframe.origin.y -= ovrframe.size.height;
6300 [navbar_ setFrame:barframe];
6301
6302 CGRect trnframe = [transition_ frame];
6303 trnframe.origin.y -= ovrframe.size.height;
6304 trnframe.size.height += ovrframe.size.height;
6305 [transition_ setFrame:trnframe];
6306
6307 [UIView commitAnimations];
6308
6309 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6310 }
6311
6312 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6313 if ((self = [super initWithFrame:frame]) != nil) {
6314 database_ = database;
6315
6316 CGRect ovrrect([navbar_ bounds]);
6317 ovrrect.size.height = [UINavigationBar defaultSize].height;
6318 ovrrect.origin.y = -ovrrect.size.height;
6319
6320 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6321 [self addSubview:overlay_];
6322
6323 ovrrect.origin.y = frame.size.height;
6324 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6325 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6326 [self addSubview:underlay_];
6327
6328 [overlay_ setBarStyle:1];
6329 [underlay_ setBarStyle:1];
6330
6331 int barstyle([overlay_ _barStyle:NO]);
6332 bool ugly(barstyle == 0);
6333
6334 UIProgressIndicatorStyle style = ugly ?
6335 UIProgressIndicatorStyleMediumBrown :
6336 UIProgressIndicatorStyleMediumWhite;
6337
6338 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6339 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6340 CGRect indrect = {{indoffset, indoffset}, indsize};
6341
6342 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6343 [indicator_ setStyle:style];
6344 [overlay_ addSubview:indicator_];
6345
6346 CGSize prmsize = {215, indsize.height + 4};
6347
6348 CGRect prmrect = {{
6349 indoffset * 2 + indsize.width,
6350 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6351 }, prmsize};
6352
6353 UIFont *font([UIFont systemFontOfSize:15]);
6354
6355 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6356
6357 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6358 [prompt_ setBackgroundColor:[UIColor clearColor]];
6359 [prompt_ setFont:font];
6360
6361 [overlay_ addSubview:prompt_];
6362
6363 CGSize prgsize = {75, 100};
6364
6365 CGRect prgrect = {{
6366 ovrrect.size.width - prgsize.width - 10,
6367 (ovrrect.size.height - prgsize.height) / 2
6368 } , prgsize};
6369
6370 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6371 [progress_ setStyle:0];
6372 [overlay_ addSubview:progress_];
6373
6374 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6375 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6376
6377 CGRect frame = [cancel_ frame];
6378 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6379 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6380 [cancel_ setFrame:frame];
6381
6382 [cancel_ setBarStyle:barstyle];
6383 } return self;
6384 }
6385
6386 - (void) _onCancel {
6387 updating_ = false;
6388 [cancel_ removeFromSuperview];
6389 }
6390
6391 - (void) _update { _pooled
6392 Status status;
6393 status.setDelegate(self);
6394 [database_ updateWithStatus:status];
6395
6396 [self
6397 performSelectorOnMainThread:@selector(_update_)
6398 withObject:nil
6399 waitUntilDone:NO
6400 ];
6401 }
6402
6403 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6404 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6405 }
6406
6407 /*
6408 UIActionSheet *sheet = [[[UIActionSheet alloc]
6409 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6410 buttons:[NSArray arrayWithObjects:
6411 UCLocalize("OK"),
6412 nil]
6413 defaultButtonIndex:0
6414 delegate:self
6415 context:@"refresh"
6416 ] autorelease];
6417
6418 [sheet setBodyText:error];
6419 [sheet popupAlertAnimated:YES];
6420
6421 [self reloadButtons];
6422 */
6423
6424 - (void) setProgressTitle:(NSString *)title {
6425 [self
6426 performSelectorOnMainThread:@selector(_setProgressTitle:)
6427 withObject:title
6428 waitUntilDone:YES
6429 ];
6430 }
6431
6432 - (void) setProgressPercent:(float)percent {
6433 [self
6434 performSelectorOnMainThread:@selector(_setProgressPercent:)
6435 withObject:[NSNumber numberWithFloat:percent]
6436 waitUntilDone:YES
6437 ];
6438 }
6439
6440 - (void) startProgress {
6441 }
6442
6443 - (void) addProgressOutput:(NSString *)output {
6444 [self
6445 performSelectorOnMainThread:@selector(_addProgressOutput:)
6446 withObject:output
6447 waitUntilDone:YES
6448 ];
6449 }
6450
6451 - (bool) isCancelling:(size_t)received {
6452 return !updating_;
6453 }
6454
6455 - (void) _setProgressTitle:(NSString *)title {
6456 [prompt_ setText:title];
6457 }
6458
6459 - (void) _setProgressPercent:(NSNumber *)percent {
6460 [progress_ setProgress:[percent floatValue]];
6461 }
6462
6463 - (void) _addProgressOutput:(NSString *)output {
6464 }
6465
6466 @end
6467 /* }}} */
6468 /* Cydia:// Protocol {{{ */
6469 @interface CydiaURLProtocol : NSURLProtocol {
6470 }
6471
6472 @end
6473
6474 @implementation CydiaURLProtocol
6475
6476 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6477 NSURL *url([request URL]);
6478 if (url == nil)
6479 return NO;
6480 NSString *scheme([[url scheme] lowercaseString]);
6481 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6482 return NO;
6483 return YES;
6484 }
6485
6486 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6487 return request;
6488 }
6489
6490 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6491 id<NSURLProtocolClient> client([self client]);
6492 if (icon == nil)
6493 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6494 else {
6495 NSData *data(UIImagePNGRepresentation(icon));
6496
6497 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6498 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6499 [client URLProtocol:self didLoadData:data];
6500 [client URLProtocolDidFinishLoading:self];
6501 }
6502 }
6503
6504 - (void) startLoading {
6505 id<NSURLProtocolClient> client([self client]);
6506 NSURLRequest *request([self request]);
6507
6508 NSURL *url([request URL]);
6509 NSString *href([url absoluteString]);
6510
6511 NSString *path([href substringFromIndex:8]);
6512 NSRange slash([path rangeOfString:@"/"]);
6513
6514 NSString *command;
6515 if (slash.location == NSNotFound) {
6516 command = path;
6517 path = nil;
6518 } else {
6519 command = [path substringToIndex:slash.location];
6520 path = [path substringFromIndex:(slash.location + 1)];
6521 }
6522
6523 Database *database([Database sharedInstance]);
6524
6525 if ([command isEqualToString:@"package-icon"]) {
6526 if (path == nil)
6527 goto fail;
6528 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6529 Package *package([database packageWithName:path]);
6530 if (package == nil)
6531 goto fail;
6532 UIImage *icon([package icon]);
6533 [self _returnPNGWithImage:icon forRequest:request];
6534 } else if ([command isEqualToString:@"source-icon"]) {
6535 if (path == nil)
6536 goto fail;
6537 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6538 NSString *source(Simplify(path));
6539 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6540 if (icon == nil)
6541 icon = [UIImage applicationImageNamed:@"unknown.png"];
6542 [self _returnPNGWithImage:icon forRequest:request];
6543 } else if ([command isEqualToString:@"uikit-image"]) {
6544 if (path == nil)
6545 goto fail;
6546 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6547 UIImage *icon(_UIImageWithName(path));
6548 [self _returnPNGWithImage:icon forRequest:request];
6549 } else if ([command isEqualToString:@"section-icon"]) {
6550 if (path == nil)
6551 goto fail;
6552 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6553 NSString *section(Simplify(path));
6554 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6555 if (icon == nil)
6556 icon = [UIImage applicationImageNamed:@"unknown.png"];
6557 [self _returnPNGWithImage:icon forRequest:request];
6558 } else fail: {
6559 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6560 }
6561 }
6562
6563 - (void) stopLoading {
6564 }
6565
6566 @end
6567 /* }}} */
6568
6569 /* Sections View {{{ */
6570 @interface SectionsView : RVPage {
6571 _transient Database *database_;
6572 NSMutableArray *sections_;
6573 NSMutableArray *filtered_;
6574 UITransitionView *transition_;
6575 UITable *list_;
6576 UIView *accessory_;
6577 BOOL editing_;
6578 }
6579
6580 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6581 - (void) reloadData;
6582 - (void) resetView;
6583
6584 @end
6585
6586 @implementation SectionsView
6587
6588 - (void) dealloc {
6589 [list_ setDataSource:nil];
6590 [list_ setDelegate:nil];
6591
6592 [sections_ release];
6593 [filtered_ release];
6594 [transition_ release];
6595 [list_ release];
6596 [accessory_ release];
6597 [super dealloc];
6598 }
6599
6600 - (int) numberOfRowsInTable:(UITable *)table {
6601 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6602 }
6603
6604 - (float) table:(UITable *)table heightForRow:(int)row {
6605 return 45;
6606 }
6607
6608 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6609 if (reusing == nil)
6610 reusing = [[[SectionCell alloc] init] autorelease];
6611 [(SectionCell *)reusing setSection:(editing_ ?
6612 [sections_ objectAtIndex:row] :
6613 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6614 ) editing:editing_];
6615 return reusing;
6616 }
6617
6618 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6619 return !editing_;
6620 }
6621
6622 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6623 return !editing_;
6624 }
6625
6626 - (void) tableRowSelected:(NSNotification *)notification {
6627 int row = [[notification object] selectedRow];
6628 if (row == INT_MAX)
6629 return;
6630
6631 Section *section;
6632 NSString *name;
6633 NSString *title;
6634
6635 if (row == 0) {
6636 section = nil;
6637 name = nil;
6638 title = UCLocalize("ALL_PACKAGES");
6639 } else {
6640 section = [filtered_ objectAtIndex:(row - 1)];
6641 name = [section name];
6642
6643 if (name != nil) {
6644 name = [NSString stringWithString:name];
6645 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6646 } else {
6647 name = @"";
6648 title = UCLocalize("NO_SECTION");
6649 }
6650 }
6651
6652 PackageTable *table = [[[FilteredPackageTable alloc]
6653 initWithBook:book_
6654 database:database_
6655 title:title
6656 filter:@selector(isVisibleInSection:)
6657 with:name
6658 ] autorelease];
6659
6660 [table setDelegate:delegate_];
6661
6662 [book_ pushPage:table];
6663 }
6664
6665 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6666 if ((self = [super initWithBook:book]) != nil) {
6667 database_ = database;
6668
6669 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6670 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6671
6672 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6673 [self addSubview:transition_];
6674
6675 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6676 [transition_ transition:0 toView:list_];
6677
6678 UITableColumn *column = [[[UITableColumn alloc]
6679 initWithTitle:UCLocalize("NAME")
6680 identifier:@"name"
6681 width:[self frame].size.width
6682 ] autorelease];
6683
6684 [list_ setDataSource:self];
6685 [list_ setSeparatorStyle:1];
6686 [list_ addTableColumn:column];
6687 [list_ setDelegate:self];
6688 [list_ setReusesTableCells:YES];
6689
6690 [self reloadData];
6691
6692 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6693 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6694 } return self;
6695 }
6696
6697 - (void) reloadData {
6698 NSArray *packages = [database_ packages];
6699
6700 [sections_ removeAllObjects];
6701 [filtered_ removeAllObjects];
6702
6703 #if 0
6704 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6705 SectionMap sections;
6706 sections.resize(64);
6707 #else
6708 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6709 #endif
6710
6711 _trace();
6712 for (Package *package in packages) {
6713 NSString *name([package section]);
6714 NSString *key(name == nil ? @"" : name);
6715
6716 #if 0
6717 Section **section;
6718
6719 _profile(SectionsView$reloadData$Section)
6720 section = &sections[key];
6721 if (*section == nil) {
6722 _profile(SectionsView$reloadData$Section$Allocate)
6723 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6724 _end
6725 }
6726 _end
6727
6728 [*section addToCount];
6729
6730 _profile(SectionsView$reloadData$Filter)
6731 if (![package valid] || ![package visible])
6732 continue;
6733 _end
6734
6735 [*section addToRow];
6736 #else
6737 Section *section;
6738
6739 _profile(SectionsView$reloadData$Section)
6740 section = [sections objectForKey:key];
6741 if (section == nil) {
6742 _profile(SectionsView$reloadData$Section$Allocate)
6743 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6744 [sections setObject:section forKey:key];
6745 _end
6746 }
6747 _end
6748
6749 [section addToCount];
6750
6751 _profile(SectionsView$reloadData$Filter)
6752 if (![package valid] || ![package visible])
6753 continue;
6754 _end
6755
6756 [section addToRow];
6757 #endif
6758 }
6759 _trace();
6760
6761 #if 0
6762 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6763 [sections_ addObject:i->second];
6764 #else
6765 [sections_ addObjectsFromArray:[sections allValues]];
6766 #endif
6767
6768 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6769
6770 for (Section *section in sections_) {
6771 size_t count([section row]);
6772 if (count == 0)
6773 continue;
6774
6775 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6776 [section setCount:count];
6777 [filtered_ addObject:section];
6778 }
6779
6780 [list_ reloadData];
6781 _trace();
6782 }
6783
6784 - (void) resetView {
6785 if (editing_)
6786 [self _rightButtonClicked];
6787 }
6788
6789 - (void) resetViewAnimated:(BOOL)animated {
6790 [list_ resetViewAnimated:animated];
6791 }
6792
6793 - (void) _rightButtonClicked {
6794 if ((editing_ = !editing_))
6795 [list_ reloadData];
6796 else
6797 [delegate_ updateData];
6798 [book_ reloadTitleForPage:self];
6799 [book_ reloadButtonsForPage:self];
6800 }
6801
6802 - (NSString *) title {
6803 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6804 }
6805
6806 - (NSString *) backButtonTitle {
6807 return UCLocalize("SECTIONS");
6808 }
6809
6810 - (id) rightButtonTitle {
6811 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6812 }
6813
6814 - (UINavigationButtonStyle) rightButtonStyle {
6815 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6816 }
6817
6818 - (UIView *) accessoryView {
6819 return accessory_;
6820 }
6821
6822 @end
6823 /* }}} */
6824 /* Changes View {{{ */
6825 @interface ChangesView : RVPage {
6826 _transient Database *database_;
6827 NSMutableArray *packages_;
6828 NSMutableArray *sections_;
6829 UITableView *list_;
6830 unsigned upgrades_;
6831 }
6832
6833 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6834 - (void) reloadData;
6835
6836 @end
6837
6838 @implementation ChangesView
6839
6840 - (void) dealloc {
6841 [list_ setDelegate:nil];
6842 [list_ setDataSource:nil];
6843
6844 [packages_ release];
6845 [sections_ release];
6846 [list_ release];
6847 [super dealloc];
6848 }
6849
6850 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6851 NSInteger count([sections_ count]);
6852 return count == 0 ? 1 : count;
6853 }
6854
6855 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6856 if ([sections_ count] == 0)
6857 return nil;
6858 return [[sections_ objectAtIndex:section] name];
6859 }
6860
6861 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6862 if ([sections_ count] == 0)
6863 return 0;
6864 return [[sections_ objectAtIndex:section] count];
6865 }
6866
6867 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6868 Section *section([sections_ objectAtIndex:[path section]]);
6869 NSInteger row([path row]);
6870 return [packages_ objectAtIndex:([section row] + row)];
6871 }
6872
6873 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6874 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6875 if (cell == nil)
6876 cell = [[[PackageCell alloc] init] autorelease];
6877 [cell setPackage:[self packageAtIndexPath:path]];
6878 return cell;
6879 }
6880
6881 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6882 return 73;
6883 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6884 }
6885
6886 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6887 Package *package([self packageAtIndexPath:path]);
6888 PackageView *view([delegate_ packageView]);
6889 [view setDelegate:delegate_];
6890 [view setPackage:package];
6891 [book_ pushPage:view];
6892 return path;
6893 }
6894
6895 - (void) _leftButtonClicked {
6896 [(CYBook *)book_ update];
6897 [self reloadButtons];
6898 }
6899
6900 - (void) _rightButtonClicked {
6901 [delegate_ distUpgrade];
6902 }
6903
6904 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6905 if ((self = [super initWithBook:book]) != nil) {
6906 database_ = database;
6907
6908 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6909 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6910
6911 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6912 [self addSubview:list_];
6913
6914 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6915 [list_ setDataSource:self];
6916 [list_ setDelegate:self];
6917 //[list_ setSectionListStyle:1];
6918
6919 [self reloadData];
6920
6921 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6922 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6923 } return self;
6924 }
6925
6926 - (void) reloadData {
6927 NSArray *packages = [database_ packages];
6928
6929 [packages_ removeAllObjects];
6930 [sections_ removeAllObjects];
6931
6932 _trace();
6933 for (Package *package in packages)
6934 if (
6935 [package uninstalled] && [package valid] && [package visible] ||
6936 [package upgradableAndEssential:YES]
6937 )
6938 [packages_ addObject:package];
6939
6940 _trace();
6941 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6942 _trace();
6943
6944 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6945 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6946 Section *section = nil;
6947 NSDate *last = nil;
6948
6949 upgrades_ = 0;
6950 bool unseens = false;
6951
6952 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6953
6954 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6955 Package *package = [packages_ objectAtIndex:offset];
6956
6957 BOOL uae = [package upgradableAndEssential:YES];
6958
6959 if (!uae) {
6960 unseens = true;
6961 NSDate *seen;
6962
6963 _profile(ChangesView$reloadData$Remember)
6964 seen = [package seen];
6965 _end
6966
6967 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6968 last = seen;
6969
6970 NSString *name;
6971 if (seen == nil)
6972 name = UCLocalize("UNKNOWN");
6973 else {
6974 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6975 [name autorelease];
6976 }
6977
6978 _profile(ChangesView$reloadData$Allocate)
6979 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6980 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6981 [sections_ addObject:section];
6982 _end
6983 }
6984
6985 [section addToCount];
6986 } else if ([package ignored])
6987 [ignored addToCount];
6988 else {
6989 ++upgrades_;
6990 [upgradable addToCount];
6991 }
6992 }
6993 _trace();
6994
6995 CFRelease(formatter);
6996
6997 if (unseens) {
6998 Section *last = [sections_ lastObject];
6999 size_t count = [last count];
7000 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7001 [sections_ removeLastObject];
7002 }
7003
7004 if ([ignored count] != 0)
7005 [sections_ insertObject:ignored atIndex:0];
7006 if (upgrades_ != 0)
7007 [sections_ insertObject:upgradable atIndex:0];
7008
7009 [list_ reloadData];
7010 [self reloadButtons];
7011 }
7012
7013 - (void) resetViewAnimated:(BOOL)animated {
7014 [list_ resetViewAnimated:animated];
7015 }
7016
7017 - (NSString *) leftButtonTitle {
7018 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7019 }
7020
7021 - (id) rightButtonTitle {
7022 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7023 }
7024
7025 - (NSString *) title {
7026 return UCLocalize("CHANGES");
7027 }
7028
7029 @end
7030 /* }}} */
7031 /* Search View {{{ */
7032 @protocol SearchViewDelegate
7033 - (void) showKeyboard:(BOOL)show;
7034 @end
7035
7036 @interface SearchView : RVPage {
7037 UIView *accessory_;
7038 UISearchField *field_;
7039 FilteredPackageTable *table_;
7040 UIView *dimmed_;
7041 bool reload_;
7042 }
7043
7044 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7045 - (void) reloadData;
7046
7047 @end
7048
7049 @implementation SearchView
7050
7051 - (void) dealloc {
7052 [field_ setDelegate:nil];
7053
7054 [accessory_ release];
7055 [field_ release];
7056 [table_ release];
7057 [dimmed_ release];
7058 [super dealloc];
7059 }
7060
7061 - (void) _showKeyboard:(BOOL)show {
7062 CGSize keysize = [UIKeyboard defaultSize];
7063 CGRect keydown = [book_ pageBounds];
7064 CGRect keyup = keydown;
7065 keyup.size.height -= keysize.height - ButtonBarHeight_;
7066
7067 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7068
7069 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7070 [animation setSignificantRectFields:8];
7071
7072 if (show) {
7073 [animation setStartFrame:keydown];
7074 [animation setEndFrame:keyup];
7075 } else {
7076 [animation setStartFrame:keyup];
7077 [animation setEndFrame:keydown];
7078 }
7079
7080 UIAnimator *animator = [UIAnimator sharedAnimator];
7081
7082 [animator
7083 addAnimations:[NSArray arrayWithObjects:animation, nil]
7084 withDuration:(KeyboardTime_ - delay)
7085 start:!show
7086 ];
7087
7088 if (show)
7089 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7090
7091 [delegate_ showKeyboard:show];
7092 }
7093
7094 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7095 [self _showKeyboard:YES];
7096 }
7097
7098 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7099 [self _showKeyboard:NO];
7100 }
7101
7102 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7103 if (reload_) {
7104 NSString *text([field_ text]);
7105 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7106 [self reloadData];
7107 reload_ = false;
7108 }
7109 }
7110
7111 - (void) textFieldClearButtonPressed:(UITextField *)field {
7112 reload_ = true;
7113 }
7114
7115 - (void) keyboardInputShouldDelete:(id)input {
7116 reload_ = true;
7117 }
7118
7119 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7120 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7121 reload_ = true;
7122 return YES;
7123 } else {
7124 [field_ resignFirstResponder];
7125 return NO;
7126 }
7127 }
7128
7129 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7130 if ((self = [super initWithBook:book]) != nil) {
7131 CGRect pageBounds = [book_ pageBounds];
7132
7133 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7134 CGColor dimmed(space_, 0, 0, 0, 0.5);
7135 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7136
7137 table_ = [[FilteredPackageTable alloc]
7138 initWithBook:book
7139 database:database
7140 title:nil
7141 filter:@selector(isUnfilteredAndSearchedForBy:)
7142 with:nil
7143 ];
7144
7145 [table_ setShouldHideHeaderInShortLists:NO];
7146 [self addSubview:table_];
7147
7148 CGRect cnfrect = {{7, 38}, {17, 18}};
7149
7150 CGRect area;
7151
7152 area.origin.x = 10;
7153 area.origin.y = 1;
7154
7155 area.size.width = [self bounds].size.width - area.origin.x * 2;
7156 area.size.height = [UISearchField defaultHeight];
7157
7158 field_ = [[UISearchField alloc] initWithFrame:area];
7159
7160 UIFont *font = [UIFont systemFontOfSize:16];
7161 [field_ setFont:font];
7162
7163 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7164 [field_ setDelegate:self];
7165
7166 [field_ setPaddingTop:5];
7167
7168 UITextInputTraits *traits([field_ textInputTraits]);
7169 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7170 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7171 [traits setReturnKeyType:UIReturnKeySearch];
7172
7173 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7174
7175 accessory_ = [[UIView alloc] initWithFrame:accrect];
7176 [accessory_ addSubview:field_];
7177
7178 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7179 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7180 } return self;
7181 }
7182
7183 - (void) resetViewAnimated:(BOOL)animated {
7184 [table_ resetViewAnimated:animated];
7185 }
7186
7187 - (void) _reloadData {
7188 }
7189
7190 - (void) reloadData {
7191 [table_ setObject:[field_ text]];
7192 _profile(SearchView$reloadData)
7193 [table_ reloadData];
7194 _end
7195 PrintTimes();
7196 [table_ resetCursor];
7197 }
7198
7199 - (UIView *) accessoryView {
7200 return accessory_;
7201 }
7202
7203 - (NSString *) title {
7204 return nil;
7205 }
7206
7207 - (NSString *) backButtonTitle {
7208 return UCLocalize("SEARCH");
7209 }
7210
7211 - (void) setDelegate:(id)delegate {
7212 [table_ setDelegate:delegate];
7213 [super setDelegate:delegate];
7214 }
7215
7216 @end
7217 /* }}} */
7218 /* Settings View {{{ */
7219 @interface SettingsView : RVPage {
7220 _transient Database *database_;
7221 NSString *name_;
7222 Package *package_;
7223 UIPreferencesTable *table_;
7224 _UISwitchSlider *subscribedSwitch_;
7225 _UISwitchSlider *ignoredSwitch_;
7226 UIPreferencesControlTableCell *subscribedCell_;
7227 UIPreferencesControlTableCell *ignoredCell_;
7228 }
7229
7230 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7231
7232 @end
7233
7234 @implementation SettingsView
7235
7236 - (void) dealloc {
7237 [table_ setDataSource:nil];
7238
7239 [name_ release];
7240 if (package_ != nil)
7241 [package_ release];
7242 [table_ release];
7243 [subscribedSwitch_ release];
7244 [ignoredSwitch_ release];
7245 [subscribedCell_ release];
7246 [ignoredCell_ release];
7247 [super dealloc];
7248 }
7249
7250 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7251 if (package_ == nil)
7252 return 0;
7253
7254 return 2;
7255 }
7256
7257 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7258 if (package_ == nil)
7259 return nil;
7260
7261 switch (group) {
7262 case 0: return nil;
7263 case 1: return nil;
7264
7265 _nodefault
7266 }
7267
7268 return nil;
7269 }
7270
7271 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7272 if (package_ == nil)
7273 return NO;
7274
7275 switch (group) {
7276 case 0: return NO;
7277 case 1: return YES;
7278
7279 _nodefault
7280 }
7281
7282 return NO;
7283 }
7284
7285 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7286 if (package_ == nil)
7287 return 0;
7288
7289 switch (group) {
7290 case 0: return 1;
7291 case 1: return 1;
7292
7293 _nodefault
7294 }
7295
7296 return 0;
7297 }
7298
7299 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7300 if (package_ == nil)
7301 return;
7302
7303 _UISwitchSlider *slider([cell control]);
7304 BOOL value([slider value] != 0);
7305 NSMutableDictionary *metadata([package_ metadata]);
7306
7307 BOOL before;
7308 if (NSNumber *number = [metadata objectForKey:key])
7309 before = [number boolValue];
7310 else
7311 before = NO;
7312
7313 if (value != before) {
7314 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7315 Changed_ = true;
7316 [delegate_ updateData];
7317 }
7318 }
7319
7320 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7321 [self onSomething:cell withKey:@"IsSubscribed"];
7322 }
7323
7324 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7325 [self onSomething:cell withKey:@"IsIgnored"];
7326 }
7327
7328 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7329 if (package_ == nil)
7330 return nil;
7331
7332 switch (group) {
7333 case 0: switch (row) {
7334 case 0:
7335 return subscribedCell_;
7336 case 1:
7337 return ignoredCell_;
7338 _nodefault
7339 } break;
7340
7341 case 1: switch (row) {
7342 case 0: {
7343 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7344 [cell setShowSelection:NO];
7345 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7346 return cell;
7347 }
7348
7349 _nodefault
7350 } break;
7351
7352 _nodefault
7353 }
7354
7355 return nil;
7356 }
7357
7358 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7359 if ((self = [super initWithBook:book])) {
7360 database_ = database;
7361 name_ = [package retain];
7362
7363 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7364 [self addSubview:table_];
7365
7366 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7367 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7368
7369 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7370 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7371
7372 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7373 [subscribedCell_ setShowSelection:NO];
7374 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7375 [subscribedCell_ setControl:subscribedSwitch_];
7376
7377 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7378 [ignoredCell_ setShowSelection:NO];
7379 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7380 [ignoredCell_ setControl:ignoredSwitch_];
7381
7382 [table_ setDataSource:self];
7383 [self reloadData];
7384 } return self;
7385 }
7386
7387 - (void) resetViewAnimated:(BOOL)animated {
7388 [table_ resetViewAnimated:animated];
7389 }
7390
7391 - (void) reloadData {
7392 if (package_ != nil)
7393 [package_ autorelease];
7394 package_ = [database_ packageWithName:name_];
7395 if (package_ != nil) {
7396 [package_ retain];
7397 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7398 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7399 }
7400
7401 [table_ reloadData];
7402 }
7403
7404 - (NSString *) title {
7405 return UCLocalize("SETTINGS");
7406 }
7407
7408 @end
7409 /* }}} */
7410
7411 /* Signature View {{{ */
7412 @interface SignatureView : CydiaBrowserView {
7413 _transient Database *database_;
7414 NSString *package_;
7415 }
7416
7417 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7418
7419 @end
7420
7421 @implementation SignatureView
7422
7423 - (void) dealloc {
7424 [package_ release];
7425 [super dealloc];
7426 }
7427
7428 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7429 // XXX: dude!
7430 [super webView:sender didClearWindowObject:window forFrame:frame];
7431 }
7432
7433 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7434 if ((self = [super initWithBook:book]) != nil) {
7435 database_ = database;
7436 package_ = [package retain];
7437 [self reloadData];
7438 } return self;
7439 }
7440
7441 - (void) resetViewAnimated:(BOOL)animated {
7442 }
7443
7444 - (void) reloadData {
7445 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7446 }
7447
7448 @end
7449 /* }}} */
7450
7451 @interface Cydia : UIApplication <
7452 ConfirmationViewDelegate,
7453 ProgressViewDelegate,
7454 SearchViewDelegate,
7455 CydiaDelegate
7456 > {
7457 UIWindow *window_;
7458
7459 UIView *underlay_;
7460 UIView *overlay_;
7461 CYBook *book_;
7462 UIToolbar *toolbar_;
7463
7464 RVBook *confirm_;
7465
7466 NSMutableArray *essential_;
7467 NSMutableArray *broken_;
7468
7469 Database *database_;
7470 ProgressView *progress_;
7471
7472 unsigned tag_;
7473
7474 UIKeyboard *keyboard_;
7475 UIProgressHUD *hud_;
7476
7477 SectionsView *sections_;
7478 ChangesView *changes_;
7479 ManageView *manage_;
7480 SearchView *search_;
7481
7482 #if RecyclePackageViews
7483 NSMutableArray *details_;
7484 #endif
7485 }
7486
7487 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7488 - (void) setPage:(RVPage *)page;
7489
7490 @end
7491
7492 static _finline void _setHomePage(Cydia *self) {
7493 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7494 }
7495
7496 @implementation Cydia
7497
7498 - (void) _loaded {
7499 if ([broken_ count] != 0) {
7500 int count = [broken_ count];
7501
7502 UIActionSheet *sheet = [[[UIActionSheet alloc]
7503 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7504 buttons:[NSArray arrayWithObjects:
7505 UCLocalize("FORCIBLY_CLEAR"),
7506 UCLocalize("TEMPORARY_IGNORE"),
7507 nil]
7508 defaultButtonIndex:0
7509 delegate:self
7510 context:@"fixhalf"
7511 ] autorelease];
7512
7513 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7514 [sheet popupAlertAnimated:YES];
7515 } else if (!Ignored_ && [essential_ count] != 0) {
7516 int count = [essential_ count];
7517
7518 UIActionSheet *sheet = [[[UIActionSheet alloc]
7519 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7520 buttons:[NSArray arrayWithObjects:
7521 UCLocalize("UPGRADE_ESSENTIAL"),
7522 UCLocalize("COMPLETE_UPGRADE"),
7523 UCLocalize("TEMPORARY_IGNORE"),
7524 nil]
7525 defaultButtonIndex:0
7526 delegate:self
7527 context:@"upgrade"
7528 ] autorelease];
7529
7530 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7531 [sheet popupAlertAnimated:YES];
7532 }
7533 }
7534
7535 - (void) _saveConfig {
7536 if (Changed_) {
7537 _trace();
7538 NSString *error(nil);
7539 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7540 _trace();
7541 NSError *error(nil);
7542 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7543 NSLog(@"failure to save metadata data: %@", error);
7544 _trace();
7545 } else {
7546 NSLog(@"failure to serialize metadata: %@", error);
7547 return;
7548 }
7549
7550 Changed_ = false;
7551 }
7552 }
7553
7554 - (void) _updateData {
7555 [self _saveConfig];
7556
7557 /* XXX: this is just stupid */
7558 if (tag_ != 2 && sections_ != nil)
7559 [sections_ reloadData];
7560 if (tag_ != 3 && changes_ != nil)
7561 [changes_ reloadData];
7562 if (tag_ != 5 && search_ != nil)
7563 [search_ reloadData];
7564
7565 [book_ reloadData];
7566 }
7567
7568 - (void) _reloadData {
7569 UIView *block();
7570
7571 static bool loaded(false);
7572 UIProgressHUD *hud([self addProgressHUD]);
7573 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7574
7575 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7576 _trace();
7577
7578 [self removeProgressHUD:hud];
7579
7580 size_t changes(0);
7581
7582 [essential_ removeAllObjects];
7583 [broken_ removeAllObjects];
7584
7585 NSArray *packages([database_ packages]);
7586 for (Package *package in packages) {
7587 if ([package half])
7588 [broken_ addObject:package];
7589 if ([package upgradableAndEssential:NO]) {
7590 if ([package essential])
7591 [essential_ addObject:package];
7592 ++changes;
7593 }
7594 }
7595
7596 if (changes != 0) {
7597 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7598 [toolbar_ setBadgeValue:badge forButton:3];
7599 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7600 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7601 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7602 [self setApplicationBadge:badge];
7603 else
7604 [self setApplicationBadgeString:badge];
7605 } else {
7606 [toolbar_ setBadgeValue:nil forButton:3];
7607 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7608 [toolbar_ setBadgeAnimated:NO forButton:3];
7609 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7610 [self removeApplicationBadge];
7611 else // XXX: maybe use setApplicationBadgeString also?
7612 [self setApplicationIconBadgeNumber:0];
7613 }
7614
7615 Queuing_ = false;
7616 [toolbar_ setBadgeValue:nil forButton:4];
7617
7618 [self _updateData];
7619
7620 if (loaded || ManualRefresh) loaded:
7621 [self _loaded];
7622 else {
7623 loaded = true;
7624
7625 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7626 NSTimeInterval interval([update timeIntervalSinceNow]);
7627 if (interval <= 0 && interval > -(15*60))
7628 goto loaded;
7629 }
7630
7631 [book_ update];
7632 }
7633 }
7634
7635 - (void) updateData {
7636 [database_ setVisible];
7637 [self _updateData];
7638 }
7639
7640 - (void) update_ {
7641 [database_ update];
7642 }
7643
7644 - (void) syncData {
7645 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7646 _assert(file != NULL);
7647
7648 for (NSString *key in [Sources_ allKeys]) {
7649 NSDictionary *source([Sources_ objectForKey:key]);
7650
7651 fprintf(file, "%s %s %s\n",
7652 [[source objectForKey:@"Type"] UTF8String],
7653 [[source objectForKey:@"URI"] UTF8String],
7654 [[source objectForKey:@"Distribution"] UTF8String]
7655 );
7656 }
7657
7658 fclose(file);
7659
7660 [self _saveConfig];
7661
7662 [progress_
7663 detachNewThreadSelector:@selector(update_)
7664 toTarget:self
7665 withObject:nil
7666 title:UCLocalize("UPDATING_SOURCES")
7667 ];
7668 }
7669
7670 - (void) reloadData {
7671 @synchronized (self) {
7672 if (confirm_ == nil)
7673 [self _reloadData];
7674 }
7675 }
7676
7677 - (void) resolve {
7678 pkgProblemResolver *resolver = [database_ resolver];
7679
7680 resolver->InstallProtect();
7681 if (!resolver->Resolve(true))
7682 _error->Discard();
7683 }
7684
7685 - (void) popUpBook:(RVBook *)book {
7686 [underlay_ popSubview:book];
7687 }
7688
7689 - (CGRect) popUpBounds {
7690 return [underlay_ bounds];
7691 }
7692
7693 - (bool) perform {
7694 if (![database_ prepare])
7695 return false;
7696
7697 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7698 [confirm_ setDelegate:self];
7699
7700 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7701 [page setDelegate:self];
7702
7703 [confirm_ setPage:page];
7704 [self popUpBook:confirm_];
7705
7706 return true;
7707 }
7708
7709 - (void) queue {
7710 @synchronized (self) {
7711 [self perform];
7712 }
7713 }
7714
7715 - (void) clearPackage:(Package *)package {
7716 @synchronized (self) {
7717 [package clear];
7718 [self resolve];
7719 [self perform];
7720 }
7721 }
7722
7723 - (void) installPackage:(Package *)package {
7724 @synchronized (self) {
7725 [package install];
7726 [self resolve];
7727 [self perform];
7728 }
7729 }
7730
7731 - (void) removePackage:(Package *)package {
7732 @synchronized (self) {
7733 [package remove];
7734 [self resolve];
7735 [self perform];
7736 }
7737 }
7738
7739 - (void) distUpgrade {
7740 @synchronized (self) {
7741 if (![database_ upgrade])
7742 return;
7743 [self perform];
7744 }
7745 }
7746
7747 - (void) cancel {
7748 [self slideUp:[[[UIActionSheet alloc]
7749 initWithTitle:nil
7750 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7751 defaultButtonIndex:1
7752 delegate:self
7753 context:@"cancel"
7754 ] autorelease]];
7755 }
7756
7757 - (void) complete {
7758 @synchronized (self) {
7759 [self _reloadData];
7760
7761 if (confirm_ != nil) {
7762 [confirm_ release];
7763 confirm_ = nil;
7764 }
7765 }
7766 }
7767
7768 - (void) confirm {
7769 [overlay_ removeFromSuperview];
7770 reload_ = true;
7771
7772 [progress_
7773 detachNewThreadSelector:@selector(perform)
7774 toTarget:database_
7775 withObject:nil
7776 title:UCLocalize("RUNNING")
7777 ];
7778 }
7779
7780 - (void) progressViewIsComplete:(ProgressView *)progress {
7781 if (confirm_ != nil) {
7782 [underlay_ addSubview:overlay_];
7783 [confirm_ popFromSuperviewAnimated:NO];
7784 }
7785
7786 [self complete];
7787 }
7788
7789 - (void) setPage:(RVPage *)page {
7790 [page resetViewAnimated:NO];
7791 [page setDelegate:self];
7792 [book_ setPage:page];
7793 }
7794
7795 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7796 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7797 [browser loadURL:url];
7798 return browser;
7799 }
7800
7801 - (SectionsView *) sectionsView {
7802 if (sections_ == nil)
7803 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7804 return sections_;
7805 }
7806
7807 - (void) buttonBarItemTapped:(id)sender {
7808 unsigned tag = [sender tag];
7809 if (tag == tag_) {
7810 [book_ resetViewAnimated:YES];
7811 return;
7812 } else if (tag_ == 2)
7813 [[self sectionsView] resetView];
7814
7815 switch (tag) {
7816 case 1: _setHomePage(self); break;
7817
7818 case 2: [self setPage:[self sectionsView]]; break;
7819 case 3: [self setPage:changes_]; break;
7820 case 4: [self setPage:manage_]; break;
7821 case 5: [self setPage:search_]; break;
7822
7823 _nodefault
7824 }
7825
7826 tag_ = tag;
7827 }
7828
7829 - (void) askForSettings {
7830 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7831
7832 CYActionSheet *role([[[CYActionSheet alloc]
7833 initWithTitle:UCLocalize("WHO_ARE_YOU")
7834 buttons:[NSArray arrayWithObjects:
7835 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7836 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7837 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7838 nil]
7839 defaultButtonIndex:-1
7840 ] autorelease]);
7841
7842 [role setBodyText:UCLocalize("ROLE_EX")];
7843
7844 int button([role yieldToPopupAlertAnimated:YES]);
7845
7846 switch (button) {
7847 case 1: Role_ = @"User"; break;
7848 case 2: Role_ = @"Hacker"; break;
7849 case 3: Role_ = @"Developer"; break;
7850
7851 _nodefault
7852 }
7853
7854 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7855 Role_, @"Role",
7856 nil];
7857
7858 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7859
7860 Changed_ = true;
7861
7862 [role dismiss];
7863 }
7864
7865 - (void) setPackageView:(PackageView *)view {
7866 WebThreadLock();
7867 [view setPackage:nil];
7868 #if RecyclePackageViews
7869 if ([details_ count] < 3)
7870 [details_ addObject:view];
7871 #endif
7872 WebThreadUnlock();
7873 }
7874
7875 - (PackageView *) _packageView {
7876 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7877 }
7878
7879 - (PackageView *) packageView {
7880 #if RecyclePackageViews
7881 PackageView *view;
7882 size_t count([details_ count]);
7883
7884 if (count == 0) {
7885 view = [self _packageView];
7886 renew:
7887 [details_ addObject:[self _packageView]];
7888 } else {
7889 view = [[[details_ lastObject] retain] autorelease];
7890 [details_ removeLastObject];
7891 if (count == 1)
7892 goto renew;
7893 }
7894
7895 return view;
7896 #else
7897 return [self _packageView];
7898 #endif
7899 }
7900
7901 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7902 NSString *context([sheet context]);
7903
7904 if ([context isEqualToString:@"missing"])
7905 [sheet dismiss];
7906 else if ([context isEqualToString:@"cancel"]) {
7907 bool clear;
7908
7909 switch (button) {
7910 case 1:
7911 clear = false;
7912 break;
7913
7914 case 2:
7915 clear = true;
7916 break;
7917
7918 _nodefault
7919 }
7920
7921 [sheet dismiss];
7922
7923 @synchronized (self) {
7924 if (clear)
7925 [self _reloadData];
7926 else {
7927 Queuing_ = true;
7928 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
7929 [book_ reloadData];
7930 }
7931
7932 if (confirm_ != nil) {
7933 [confirm_ release];
7934 confirm_ = nil;
7935 }
7936 }
7937 } else if ([context isEqualToString:@"fixhalf"]) {
7938 switch (button) {
7939 case 1:
7940 @synchronized (self) {
7941 for (Package *broken in broken_) {
7942 [broken remove];
7943
7944 NSString *id = [broken id];
7945 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7946 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7947 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7948 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7949 }
7950
7951 [self resolve];
7952 [self perform];
7953 }
7954 break;
7955
7956 case 2:
7957 [broken_ removeAllObjects];
7958 [self _loaded];
7959 break;
7960
7961 _nodefault
7962 }
7963
7964 [sheet dismiss];
7965 } else if ([context isEqualToString:@"upgrade"]) {
7966 switch (button) {
7967 case 1:
7968 @synchronized (self) {
7969 for (Package *essential in essential_)
7970 [essential install];
7971
7972 [self resolve];
7973 [self perform];
7974 }
7975 break;
7976
7977 case 2:
7978 [self distUpgrade];
7979 break;
7980
7981 case 3:
7982 Ignored_ = YES;
7983 break;
7984
7985 _nodefault
7986 }
7987
7988 [sheet dismiss];
7989 }
7990 }
7991
7992 - (void) system:(NSString *)command { _pooled
7993 system([command UTF8String]);
7994 }
7995
7996 - (void) applicationWillSuspend {
7997 [database_ clean];
7998 [super applicationWillSuspend];
7999 }
8000
8001 - (void) applicationSuspend:(__GSEvent *)event {
8002 if (hud_ == nil && ![progress_ isRunning])
8003 [super applicationSuspend:event];
8004 }
8005
8006 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8007 if (hud_ == nil)
8008 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8009 }
8010
8011 - (void) _setSuspended:(BOOL)value {
8012 if (hud_ == nil)
8013 [super _setSuspended:value];
8014 }
8015
8016 - (UIProgressHUD *) addProgressHUD {
8017 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8018 [window_ setUserInteractionEnabled:NO];
8019 [hud show:YES];
8020 [progress_ addSubview:hud];
8021 return hud;
8022 }
8023
8024 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8025 [hud show:NO];
8026 [hud removeFromSuperview];
8027 [window_ setUserInteractionEnabled:YES];
8028 }
8029
8030 - (RVPage *) pageForPackage:(NSString *)name {
8031 if (Package *package = [database_ packageWithName:name]) {
8032 PackageView *view([self packageView]);
8033 [view setPackage:package];
8034 return view;
8035 } else {
8036 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8037 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8038 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8039 }
8040 }
8041
8042 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8043 if (tag != NULL)
8044 tag = 0;
8045
8046 NSString *href([url absoluteString]);
8047 if ([href hasPrefix:@"apptapp://package/"])
8048 return [self pageForPackage:[href substringFromIndex:18]];
8049
8050 NSString *scheme([[url scheme] lowercaseString]);
8051 if (![scheme isEqualToString:@"cydia"])
8052 return nil;
8053 NSString *path([url absoluteString]);
8054 if ([path length] < 8)
8055 return nil;
8056 path = [path substringFromIndex:8];
8057 if (![path hasPrefix:@"/"])
8058 path = [@"/" stringByAppendingString:path];
8059
8060 if ([path isEqualToString:@"/add-source"])
8061 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8062 else if ([path isEqualToString:@"/storage"])
8063 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8064 else if ([path isEqualToString:@"/sources"])
8065 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8066 else if ([path isEqualToString:@"/packages"])
8067 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8068 else if ([path hasPrefix:@"/url/"])
8069 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8070 else if ([path hasPrefix:@"/launch/"])
8071 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8072 else if ([path hasPrefix:@"/package-settings/"])
8073 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8074 else if ([path hasPrefix:@"/package-signature/"])
8075 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8076 else if ([path hasPrefix:@"/package/"])
8077 return [self pageForPackage:[path substringFromIndex:9]];
8078 else if ([path hasPrefix:@"/files/"]) {
8079 NSString *name = [path substringFromIndex:7];
8080
8081 if (Package *package = [database_ packageWithName:name]) {
8082 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8083 [files setPackage:package];
8084 return files;
8085 }
8086 }
8087
8088 return nil;
8089 }
8090
8091 - (void) applicationOpenURL:(NSURL *)url {
8092 [super applicationOpenURL:url];
8093 int tag;
8094 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8095 [self setPage:page];
8096 [toolbar_ showSelectionForButton:tag];
8097 tag_ = tag;
8098 }
8099 }
8100
8101 - (void) applicationDidFinishLaunching:(id)unused {
8102 [BrowserView _initialize];
8103
8104 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8105
8106 Font12_ = [[UIFont systemFontOfSize:12] retain];
8107 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8108 Font14_ = [[UIFont systemFontOfSize:14] retain];
8109 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8110 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8111
8112 tag_ = 1;
8113
8114 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8115 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8116
8117 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8118 [window_ orderFront:self];
8119 [window_ makeKey:self];
8120 [window_ setHidden:NO];
8121
8122 database_ = [Database sharedInstance];
8123
8124 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8125 [database_ setDelegate:progress_];
8126 [window_ setContentView:progress_];
8127
8128 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8129 [progress_ setContentView:underlay_];
8130
8131 [progress_ resetView];
8132
8133 if (
8134 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8135 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8136 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8137 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8138 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8139 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8140 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8141 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8142 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8143 false
8144 ) {
8145 [self setIdleTimerDisabled:YES];
8146
8147 hud_ = [self addProgressHUD];
8148 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8149 [self setStatusBarShowsProgress:YES];
8150
8151 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8152
8153 [self setStatusBarShowsProgress:NO];
8154 [self removeProgressHUD:hud_];
8155 hud_ = nil;
8156
8157 if (ExecFork() == 0) {
8158 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8159 perror("launchctl stop");
8160 }
8161
8162 return;
8163 }
8164
8165 if (Role_ == nil)
8166 [self askForSettings];
8167
8168 _trace();
8169 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8170
8171 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8172 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8173 0, 0, screenrect.size.width, screenrect.size.height - 48
8174 ) database:database_];
8175
8176 [book_ setDelegate:self];
8177
8178 [overlay_ addSubview:book_];
8179
8180 NSArray *buttonitems = [NSArray arrayWithObjects:
8181 [NSDictionary dictionaryWithObjectsAndKeys:
8182 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8183 @"home-up.png", kUIButtonBarButtonInfo,
8184 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
8185 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
8186 self, kUIButtonBarButtonTarget,
8187 @"Cydia", kUIButtonBarButtonTitle,
8188 @"0", kUIButtonBarButtonType,
8189 nil],
8190
8191 [NSDictionary dictionaryWithObjectsAndKeys:
8192 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8193 @"install-up.png", kUIButtonBarButtonInfo,
8194 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8195 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8196 self, kUIButtonBarButtonTarget,
8197 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8198 @"0", kUIButtonBarButtonType,
8199 nil],
8200
8201 [NSDictionary dictionaryWithObjectsAndKeys:
8202 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8203 @"changes-up.png", kUIButtonBarButtonInfo,
8204 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8205 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8206 self, kUIButtonBarButtonTarget,
8207 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8208 @"0", kUIButtonBarButtonType,
8209 nil],
8210
8211 [NSDictionary dictionaryWithObjectsAndKeys:
8212 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8213 @"manage-up.png", kUIButtonBarButtonInfo,
8214 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8215 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8216 self, kUIButtonBarButtonTarget,
8217 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8218 @"0", kUIButtonBarButtonType,
8219 nil],
8220
8221 [NSDictionary dictionaryWithObjectsAndKeys:
8222 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8223 @"search-up.png", kUIButtonBarButtonInfo,
8224 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8225 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8226 self, kUIButtonBarButtonTarget,
8227 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8228 @"0", kUIButtonBarButtonType,
8229 nil],
8230 nil];
8231
8232 toolbar_ = [[UIToolbar alloc]
8233 initInView:overlay_
8234 withFrame:CGRectMake(
8235 0, screenrect.size.height - ButtonBarHeight_,
8236 screenrect.size.width, ButtonBarHeight_
8237 )
8238 withItemList:buttonitems
8239 ];
8240
8241 [toolbar_ setDelegate:self];
8242 [toolbar_ setBarStyle:1];
8243 [toolbar_ setButtonBarTrackingMode:2];
8244
8245 int buttons[5] = {1, 2, 3, 4, 5};
8246 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8247 [toolbar_ showButtonGroup:0 withDuration:0];
8248
8249 for (int i = 0; i != 5; ++i)
8250 [[toolbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8251 i * 64 + 2, 1, 60, ButtonBarHeight_
8252 )];
8253
8254 [toolbar_ showSelectionForButton:1];
8255 [overlay_ addSubview:toolbar_];
8256
8257 [UIKeyboard initImplementationNow];
8258 CGSize keysize = [UIKeyboard defaultSize];
8259 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8260 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8261 [overlay_ addSubview:keyboard_];
8262
8263 [underlay_ addSubview:overlay_];
8264
8265 [self reloadData];
8266
8267 [self sectionsView];
8268 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
8269 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
8270
8271 manage_ = (ManageView *) [[self
8272 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8273 withClass:[ManageView class]
8274 ] retain];
8275
8276 #if RecyclePackageViews
8277 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8278 [details_ addObject:[self _packageView]];
8279 [details_ addObject:[self _packageView]];
8280 #endif
8281
8282 PrintTimes();
8283
8284 _setHomePage(self);
8285 }
8286
8287 - (void) showKeyboard:(BOOL)show {
8288 CGSize keysize([UIKeyboard defaultSize]);
8289 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8290 CGRect keyup(keydown);
8291 keyup.origin.y -= keysize.height;
8292
8293 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8294 [animation setSignificantRectFields:2];
8295
8296 if (show) {
8297 [animation setStartFrame:keydown];
8298 [animation setEndFrame:keyup];
8299 [keyboard_ activate];
8300 } else {
8301 [animation setStartFrame:keyup];
8302 [animation setEndFrame:keydown];
8303 [keyboard_ deactivate];
8304 }
8305
8306 [[UIAnimator sharedAnimator]
8307 addAnimations:[NSArray arrayWithObjects:animation, nil]
8308 withDuration:KeyboardTime_
8309 start:YES
8310 ];
8311 }
8312
8313 - (void) slideUp:(UIActionSheet *)alert {
8314 [alert presentSheetInView:overlay_];
8315 }
8316
8317 @end
8318
8319 /*IMP alloc_;
8320 id Alloc_(id self, SEL selector) {
8321 id object = alloc_(self, selector);
8322 lprintf("[%s]A-%p\n", self->isa->name, object);
8323 return object;
8324 }*/
8325
8326 /*IMP dealloc_;
8327 id Dealloc_(id self, SEL selector) {
8328 id object = dealloc_(self, selector);
8329 lprintf("[%s]D-%p\n", self->isa->name, object);
8330 return object;
8331 }*/
8332
8333 Class $WebDefaultUIKitDelegate;
8334
8335 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8336 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8337 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8338 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8339 }
8340
8341 int main(int argc, char *argv[]) { _pooled
8342 _trace();
8343
8344 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8345
8346 /* Library Hacks {{{ */
8347 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8348
8349 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8350 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8351 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8352 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8353 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8354 }
8355 /* }}} */
8356 /* Set Locale {{{ */
8357 Locale_ = CFLocaleCopyCurrent();
8358 Languages_ = [NSLocale preferredLanguages];
8359 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8360 //NSLog(@"%@", [Languages_ description]);
8361
8362 const char *lang;
8363 if (Languages_ == nil || [Languages_ count] == 0)
8364 // XXX: consider just setting to C and then falling through?
8365 lang = NULL;
8366 else {
8367 lang = [[Languages_ objectAtIndex:0] UTF8String];
8368 setenv("LANG", lang, true);
8369 }
8370
8371 //std::setlocale(LC_ALL, lang);
8372 NSLog(@"Setting Language: %s", lang);
8373 /* }}} */
8374
8375 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8376
8377 /* Parse Arguments {{{ */
8378 bool substrate(false);
8379
8380 if (argc != 0) {
8381 char **args(argv);
8382 int arge(1);
8383
8384 for (int argi(1); argi != argc; ++argi)
8385 if (strcmp(argv[argi], "--") == 0) {
8386 arge = argi;
8387 argv[argi] = argv[0];
8388 argv += argi;
8389 argc -= argi;
8390 break;
8391 }
8392
8393 for (int argi(1); argi != arge; ++argi)
8394 if (strcmp(args[argi], "--substrate") == 0)
8395 substrate = true;
8396 else
8397 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8398 }
8399 /* }}} */
8400
8401 App_ = [[NSBundle mainBundle] bundlePath];
8402 Home_ = NSHomeDirectory();
8403 Advanced_ = YES;
8404
8405 setuid(0);
8406 setgid(0);
8407
8408 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8409 alloc_ = alloc->method_imp;
8410 alloc->method_imp = (IMP) &Alloc_;*/
8411
8412 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8413 dealloc_ = dealloc->method_imp;
8414 dealloc->method_imp = (IMP) &Dealloc_;*/
8415
8416 /* System Information {{{ */
8417 size_t size;
8418
8419 int maxproc;
8420 size = sizeof(maxproc);
8421 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8422 perror("sysctlbyname(\"kern.maxproc\", ?)");
8423 else if (maxproc < 64) {
8424 maxproc = 64;
8425 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8426 perror("sysctlbyname(\"kern.maxproc\", #)");
8427 }
8428
8429 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8430 char *osversion = new char[size];
8431 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8432 perror("sysctlbyname(\"kern.osversion\", ?)");
8433 else
8434 System_ = [NSString stringWithUTF8String:osversion];
8435
8436 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8437 char *machine = new char[size];
8438 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8439 perror("sysctlbyname(\"hw.machine\", ?)");
8440 else
8441 Machine_ = machine;
8442
8443 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8444 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8445 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8446 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8447 CFRelease(serial);
8448 }
8449
8450 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8451 NSData *data((NSData *) ecid);
8452 size_t length([data length]);
8453 uint8_t bytes[length];
8454 [data getBytes:bytes];
8455 char string[length * 2 + 1];
8456 for (size_t i(0); i != length; ++i)
8457 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8458 ChipID_ = [NSString stringWithUTF8String:string];
8459 CFRelease(ecid);
8460 }
8461
8462 IOObjectRelease(service);
8463 }
8464 }
8465
8466 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8467
8468 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8469 Build_ = [system objectForKey:@"ProductBuildVersion"];
8470 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8471 Product_ = [info objectForKey:@"SafariProductVersion"];
8472 Safari_ = [info objectForKey:@"CFBundleVersion"];
8473 }
8474 /* }}} */
8475 /* Load Database {{{ */
8476 _trace();
8477 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8478 _trace();
8479 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8480 _trace();
8481
8482 if (Metadata_ == NULL)
8483 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8484 else {
8485 Settings_ = [Metadata_ objectForKey:@"Settings"];
8486
8487 Packages_ = [Metadata_ objectForKey:@"Packages"];
8488 Sections_ = [Metadata_ objectForKey:@"Sections"];
8489 Sources_ = [Metadata_ objectForKey:@"Sources"];
8490 }
8491
8492 if (Settings_ != nil)
8493 Role_ = [Settings_ objectForKey:@"Role"];
8494
8495 if (Packages_ == nil) {
8496 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8497 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8498 }
8499
8500 if (Sections_ == nil) {
8501 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8502 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8503 }
8504
8505 if (Sources_ == nil) {
8506 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8507 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8508 }
8509 /* }}} */
8510
8511 #if RecycleWebViews
8512 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8513 #endif
8514
8515 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8516
8517 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8518 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8519 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8520 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8521
8522 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8523 unlink("/tmp/.cydia.fw");
8524 goto firmware;
8525 } else if (access("/User", F_OK) != 0) {
8526 firmware:
8527 _trace();
8528 system("/usr/libexec/cydia/firmware.sh");
8529 _trace();
8530 }
8531
8532 _assert([[NSFileManager defaultManager]
8533 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8534 withIntermediateDirectories:YES
8535 attributes:nil
8536 error:NULL
8537 ]);
8538
8539 if (access("/tmp/cydia.chk", F_OK) == 0) {
8540 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8541 _assert(errno == ENOENT);
8542 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8543 _assert(errno == ENOENT);
8544 }
8545
8546 /* APT Initialization {{{ */
8547 _assert(pkgInitConfig(*_config));
8548 _assert(pkgInitSystem(*_config, _system));
8549
8550 if (lang != NULL)
8551 _config->Set("APT::Acquire::Translation", lang);
8552 _config->Set("Acquire::http::Timeout", 15);
8553 _config->Set("Acquire::http::MaxParallel", 3);
8554 /* }}} */
8555 /* Color Choices {{{ */
8556 space_ = CGColorSpaceCreateDeviceRGB();
8557
8558 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8559 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8560 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8561 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8562 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8563 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8564 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8565 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8566 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8567
8568 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8569 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8570 /* }}}*/
8571 /* UIKit Configuration {{{ */
8572 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8573 if ($GSFontSetUseLegacyFontMetrics != NULL)
8574 $GSFontSetUseLegacyFontMetrics(YES);
8575
8576 UIKeyboardDisableAutomaticAppearance();
8577 /* }}} */
8578
8579 Colon_ = UCLocalize("COLON_DELIMITED");
8580 Error_ = UCLocalize("ERROR");
8581 Warning_ = UCLocalize("WARNING");
8582
8583 _trace();
8584 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8585
8586 CGColorSpaceRelease(space_);
8587 CFRelease(Locale_);
8588
8589 return value;
8590 }