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