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