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