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