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