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