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