]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Add Italian translation from qwertyuiop.
[cydia.git] / MobileCydia.mm
1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
3 */
4
5 /* Modified BSD License {{{ */
6 /*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38 /* }}} */
39
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
42
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
46
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
49
50 #include <CoreGraphics/CoreGraphics.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 #include <SystemConfiguration/SystemConfiguration.h>
63
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
66
67 #include <IOKit/IOKitLib.h>
68
69 #include <WebCore/WebCoreThread.h>
70
71 #include <algorithm>
72 #include <iomanip>
73 #include <sstream>
74 #include <string>
75
76 #include <ext/stdio_filebuf.h>
77
78 #undef ABS
79
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
97
98 #include <apr-1/apr_pools.h>
99
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
106
107 #include <fcntl.h>
108 #include <notify.h>
109 #include <dlfcn.h>
110
111 extern "C" {
112 #include <mach-o/nlist.h>
113 }
114
115 #include <cstdio>
116 #include <cstdlib>
117 #include <cstring>
118
119 #include <errno.h>
120
121 #include <Cytore.hpp>
122
123 #include "UICaboodle/BrowserView.h"
124 #include "UICaboodle/NSString-UICaboodle.h"
125 #include "UICaboodle/PerlCompatibleRegEx.hpp"
126
127 #include "SDURLCache/SDURLCache.h"
128
129 #include "substrate.h"
130 /* }}} */
131
132 /* Profiler {{{ */
133 struct timeval _ltv;
134 bool _itv;
135
136 #define _timestamp ({ \
137 struct timeval tv; \
138 gettimeofday(&tv, NULL); \
139 tv.tv_sec * 1000000 + tv.tv_usec; \
140 })
141
142 typedef std::vector<class ProfileTime *> TimeList;
143 TimeList times_;
144
145 class ProfileTime {
146 private:
147 const char *name_;
148 uint64_t total_;
149 uint64_t count_;
150
151 public:
152 ProfileTime(const char *name) :
153 name_(name),
154 total_(0)
155 {
156 times_.push_back(this);
157 }
158
159 void AddTime(uint64_t time) {
160 total_ += time;
161 ++count_;
162 }
163
164 void Print() {
165 if (total_ != 0)
166 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
167 total_ = 0;
168 count_ = 0;
169 }
170 };
171
172 class ProfileTimer {
173 private:
174 ProfileTime &time_;
175 uint64_t start_;
176
177 public:
178 ProfileTimer(ProfileTime &time) :
179 time_(time),
180 start_(_timestamp)
181 {
182 }
183
184 ~ProfileTimer() {
185 time_.AddTime(_timestamp - start_);
186 }
187 };
188
189 void PrintTimes() {
190 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
191 (*i)->Print();
192 std::cerr << "========" << std::endl;
193 }
194
195 #define _profile(name) { \
196 static ProfileTime name(#name); \
197 ProfileTimer _ ## name(name);
198
199 #define _end }
200 /* }}} */
201
202 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
203
204 #define CYPoolStart() \
205 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
206 do
207 #define CYPoolEnd() \
208 while (false); \
209 [_pool release];
210
211 #define Cydia_ CYDIA_VERSION
212
213 #define lprintf(args...) fprintf(stderr, args)
214
215 #define ForRelease 1
216 #define TraceLogging (1 && !ForRelease)
217 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
218 #define ProfileTimes (0 && !ForRelease)
219 #define ForSaurik (0 && !ForRelease)
220 #define LogBrowser (0 && !ForRelease)
221 #define TrackResize (0 && !ForRelease)
222 #define ManualRefresh (1 && !ForRelease)
223 #define ShowInternals (0 && !ForRelease)
224 #define AlwaysReload (0 && !ForRelease)
225 #define TryIndexedCollation (0 && !ForRelease)
226
227 #if !TraceLogging
228 #undef _trace
229 #define _trace(args...)
230 #endif
231
232 #if !ProfileTimes
233 #undef _profile
234 #define _profile(name) {
235 #undef _end
236 #define _end }
237 #define PrintTimes() do {} while (false)
238 #endif
239
240 // Hash Functions/Structures {{{
241 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
242
243 union SplitHash {
244 uint32_t u32;
245 uint16_t u16[2];
246 };
247 // }}}
248
249 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
250
251 static _finline NSString *CydiaURL(NSString *path) {
252 char page[26];
253 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
254 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
255 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
256 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
257 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
258 page[25] = '\0';
259 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
260 }
261
262 static _finline void UpdateExternalStatus(uint64_t newStatus) {
263 int notify_token;
264 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
265 notify_set_state(notify_token, newStatus);
266 notify_cancel(notify_token);
267 }
268 notify_post("com.saurik.Cydia.status");
269 }
270
271 /* [NSObject yieldToSelector:(withObject:)] {{{*/
272 @interface NSObject (Cydia)
273 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
274 - (id) yieldToSelector:(SEL)selector;
275 @end
276
277 @implementation NSObject (Cydia)
278
279 - (void) doNothing {
280 }
281
282 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
283 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
284 id object([[context objectAtIndex:1] nonretainedObjectValue]);
285 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
286
287 /* XXX: deal with exceptions */
288 id value([self performSelector:selector withObject:object]);
289
290 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
291 [context removeAllObjects];
292 if ([signature methodReturnLength] != 0 && value != nil)
293 [context addObject:value];
294
295 stopped = true;
296
297 [self
298 performSelectorOnMainThread:@selector(doNothing)
299 withObject:nil
300 waitUntilDone:NO
301 ];
302 }
303
304 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
305 volatile bool stopped(false);
306
307 NSMutableArray *context([NSMutableArray arrayWithObjects:
308 [NSValue valueWithPointer:selector],
309 [NSValue valueWithNonretainedObject:object],
310 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
311 nil]);
312
313 NSThread *thread([[[NSThread alloc]
314 initWithTarget:self
315 selector:@selector(_yieldToContext:)
316 object:context
317 ] autorelease]);
318
319 [thread start];
320
321 NSRunLoop *loop([NSRunLoop currentRunLoop]);
322 NSDate *future([NSDate distantFuture]);
323 NSString *mode([loop currentMode] ?: NSDefaultRunLoopMode);
324
325 _trace();
326 while (!stopped && [loop runMode:mode beforeDate:future]);
327 _trace();
328
329 return [context count] == 0 ? nil : [context objectAtIndex:0];
330 }
331
332 - (id) yieldToSelector:(SEL)selector {
333 return [self yieldToSelector:selector withObject:nil];
334 }
335
336 @end
337 /* }}} */
338
339 /* Cydia Alert View {{{ */
340 @interface CYAlertView : UIAlertView {
341 unsigned button_;
342 }
343
344 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
345
346 @end
347
348 @implementation CYAlertView
349
350 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
351 if ((self = [super init]) != nil) {
352 [self setTitle:title];
353 [self setDelegate:self];
354 for (NSString *button in buttons) [self addButtonWithTitle:button];
355 [self setCancelButtonIndex:index];
356 } return self;
357 }
358
359 - (void) _updateFrameForDisplay {
360 [super _updateFrameForDisplay];
361 if ([self cancelButtonIndex] == -1) {
362 NSArray *buttons = [self buttons];
363 if ([buttons count]) {
364 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
365 for (UIThreePartButton *button in buttons)
366 [button setBackground:background forState:0];
367 }
368 }
369 }
370
371 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
372 button_ = buttonIndex + 1;
373 }
374
375 - (void) dismiss {
376 [self dismissWithClickedButtonIndex:-1 animated:YES];
377 }
378
379 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
380 [self setRunsModal:YES];
381 button_ = 0;
382 [self show];
383 return button_;
384 }
385
386 @end
387 /* }}} */
388
389 /* NSForcedOrderingSearch doesn't work on the iPhone */
390 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
391 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
392 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
393
394 /* Radix Sort {{{ */
395 typedef uint32_t (*SKRadixFunction)(id, void *);
396
397 @interface NSMutableArray (Radix)
398 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
399 @end
400
401 struct RadixItem_ {
402 size_t index;
403 uint32_t key;
404 };
405
406 @implementation NSMutableArray (Radix)
407
408 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
409 size_t count([self count]);
410 struct RadixItem_ *swap(new RadixItem_[count * 2]);
411
412 for (size_t i(0); i != count; ++i) {
413 RadixItem_ &item(swap[i]);
414 item.index = i;
415
416 id object([self objectAtIndex:i]);
417 item.key = function(object, argument);
418 }
419
420 struct RadixItem_ *lhs(swap), *rhs(swap + count);
421
422 static const size_t width = 32;
423 static const size_t bits = 11;
424 static const size_t slots = 1 << bits;
425 static const size_t passes = (width + (bits - 1)) / bits;
426
427 size_t *hist(new size_t[slots]);
428
429 for (size_t pass(0); pass != passes; ++pass) {
430 memset(hist, 0, sizeof(size_t) * slots);
431
432 for (size_t i(0); i != count; ++i) {
433 uint32_t key(lhs[i].key);
434 key >>= pass * bits;
435 key &= _not(uint32_t) >> width - bits;
436 ++hist[key];
437 }
438
439 size_t offset(0);
440 for (size_t i(0); i != slots; ++i) {
441 size_t local(offset);
442 offset += hist[i];
443 hist[i] = local;
444 }
445
446 for (size_t i(0); i != count; ++i) {
447 uint32_t key(lhs[i].key);
448 key >>= pass * bits;
449 key &= _not(uint32_t) >> width - bits;
450 rhs[hist[key]++] = lhs[i];
451 }
452
453 RadixItem_ *tmp(lhs);
454 lhs = rhs;
455 rhs = tmp;
456 }
457
458 delete [] hist;
459
460 const void **values(new const void *[count]);
461 for (size_t i(0); i != count; ++i)
462 values[i] = [self objectAtIndex:lhs[i].index];
463 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
464 delete [] values;
465
466 delete [] swap;
467 }
468
469 @end
470 /* }}} */
471 /* Insertion Sort {{{ */
472
473 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
474 const char *ptr = (const char *)list;
475 while (0 < count) {
476 CFIndex half = count / 2;
477 const char *probe = ptr + elementSize * half;
478 CFComparisonResult cr = comparator(element, probe, context);
479 if (0 == cr) return (probe - (const char *)list) / elementSize;
480 ptr = (cr < 0) ? ptr : probe + elementSize;
481 count = (cr < 0) ? half : (half + (count & 1) - 1);
482 }
483 return (ptr - (const char *)list) / elementSize;
484 }
485
486 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
487 const char *ptr = (const char *)list;
488 while (0 < count) {
489 CFIndex half = count / 2;
490 const char *probe = ptr + elementSize * half;
491 CFComparisonResult cr = comparator(element, probe, context);
492 if (0 == cr) return (probe - (const char *)list) / elementSize;
493 ptr = (cr < 0) ? ptr : probe + elementSize;
494 count = (cr < 0) ? half : (half + (count & 1) - 1);
495 }
496 return (ptr - (const char *)list) / elementSize;
497 }
498
499 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
500 if (range.length == 0)
501 return;
502 const void **values(new const void *[range.length]);
503 CFArrayGetValues(array, range, values);
504
505 #if HistogramInsertionSort > 0
506 uint32_t total(0), *offsets(new uint32_t[range.length]);
507 #endif
508
509 for (CFIndex index(1); index != range.length; ++index) {
510 const void *value(values[index]);
511 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
512 CFIndex correct(index);
513 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
514 #if HistogramInsertionSort > 1
515 NSLog(@"%@ < %@", value, values[correct - 1]);
516 #endif
517 if (--correct == 0)
518 break;
519 }
520 if (correct != index) {
521 size_t offset(index - correct);
522 #if HistogramInsertionSort
523 total += offset;
524 ++offsets[offset];
525 if (offset > 10)
526 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
527 #endif
528 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
529 values[correct] = value;
530 }
531 }
532
533 CFArrayReplaceValues(array, range, values, range.length);
534 delete [] values;
535
536 #if HistogramInsertionSort > 0
537 for (CFIndex index(0); index != range.length; ++index)
538 if (offsets[index] != 0)
539 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
540 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
541 delete [] offsets;
542 #endif
543 }
544
545 /* }}} */
546
547 /* Apple Bug Fixes {{{ */
548 @implementation UIWebDocumentView (Cydia)
549
550 - (void) _setScrollerOffset:(CGPoint)offset {
551 UIScroller *scroller([self _scroller]);
552
553 CGSize size([scroller contentSize]);
554 CGSize bounds([scroller bounds].size);
555
556 CGPoint max;
557 max.x = size.width - bounds.width;
558 max.y = size.height - bounds.height;
559
560 // wtf Apple?!
561 if (max.x < 0)
562 max.x = 0;
563 if (max.y < 0)
564 max.y = 0;
565
566 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
567 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
568
569 [scroller setOffset:offset];
570 }
571
572 @end
573 /* }}} */
574
575 @interface NSInvocation (Cydia)
576 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
577 @end
578
579 @implementation NSInvocation (Cydia)
580
581 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
582 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
583 [invocation setTarget:target];
584 [invocation setSelector:selector];
585 return invocation;
586 }
587
588 @end
589
590 @implementation WebScriptObject (NSFastEnumeration)
591
592 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
593 size_t length([self count] - state->state);
594 if (length <= 0)
595 return 0;
596 else if (length > count)
597 length = count;
598 for (size_t i(0); i != length; ++i)
599 objects[i] = [self objectAtIndex:state->state++];
600 state->itemsPtr = objects;
601 state->mutationsPtr = (unsigned long *) self;
602 return length;
603 }
604
605 @end
606
607 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
608 size_t length([self length] - state->state);
609 if (length <= 0)
610 return 0;
611 else if (length > count)
612 length = count;
613 for (size_t i(0); i != length; ++i)
614 objects[i] = [self item:state->state++];
615 state->itemsPtr = objects;
616 state->mutationsPtr = (unsigned long *) self;
617 return length;
618 }
619
620 /* Cydia NSString Additions {{{ */
621 @interface NSString (Cydia)
622 - (NSComparisonResult) compareByPath:(NSString *)other;
623 - (NSString *) stringByCachingURLWithCurrentCDN;
624 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
625 @end
626
627 @implementation NSString (UICaboodle)
628
629 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
630 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
631 }
632
633 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
634 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
635 }
636
637 @end
638
639 @implementation NSString (Cydia)
640
641 - (NSComparisonResult) compareByPath:(NSString *)other {
642 NSString *prefix = [self commonPrefixWithString:other options:0];
643 size_t length = [prefix length];
644
645 NSRange lrange = NSMakeRange(length, [self length] - length);
646 NSRange rrange = NSMakeRange(length, [other length] - length);
647
648 lrange = [self rangeOfString:@"/" options:0 range:lrange];
649 rrange = [other rangeOfString:@"/" options:0 range:rrange];
650
651 NSComparisonResult value;
652
653 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
654 value = NSOrderedSame;
655 else if (lrange.location == NSNotFound)
656 value = NSOrderedAscending;
657 else if (rrange.location == NSNotFound)
658 value = NSOrderedDescending;
659 else
660 value = NSOrderedSame;
661
662 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
663 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
664 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
665 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
666
667 NSComparisonResult result = [lpath compare:rpath];
668 return result == NSOrderedSame ? value : result;
669 }
670
671 - (NSString *) stringByCachingURLWithCurrentCDN {
672 return [self
673 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
674 withString:@"://cache.cydia.saurik.com/"
675 ];
676 }
677
678 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
679 return [(id)CFURLCreateStringByAddingPercentEscapes(
680 kCFAllocatorDefault,
681 (CFStringRef) self,
682 NULL,
683 CFSTR(";/?:@&=+$,"),
684 kCFStringEncodingUTF8
685 ) autorelease];
686 }
687
688 @end
689 /* }}} */
690
691 /* C++ NSString Wrapper Cache {{{ */
692 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
693 return size == 0 ? NULL :
694 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
695 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
696 }
697
698 static _finline CFStringRef CYStringCreate(const char *data) {
699 return CYStringCreate(data, strlen(data));
700 }
701
702 class CYString {
703 private:
704 char *data_;
705 size_t size_;
706 CFStringRef cache_;
707
708 _finline void clear_() {
709 if (cache_ != NULL) {
710 CFRelease(cache_);
711 cache_ = NULL;
712 }
713 }
714
715 public:
716 _finline bool empty() const {
717 return size_ == 0;
718 }
719
720 _finline size_t size() const {
721 return size_;
722 }
723
724 _finline char *data() const {
725 return data_;
726 }
727
728 _finline void clear() {
729 size_ = 0;
730 clear_();
731 }
732
733 _finline CYString() :
734 data_(0),
735 size_(0),
736 cache_(NULL)
737 {
738 }
739
740 _finline ~CYString() {
741 clear_();
742 }
743
744 void operator =(const CYString &rhs) {
745 data_ = rhs.data_;
746 size_ = rhs.size_;
747
748 if (rhs.cache_ == nil)
749 cache_ = NULL;
750 else
751 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
752 }
753
754 void copy(apr_pool_t *pool) {
755 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
756 memcpy(temp, data_, size_);
757 temp[size_] = '\0';
758 data_ = temp;
759 }
760
761 void set(apr_pool_t *pool, const char *data, size_t size) {
762 if (size == 0)
763 clear();
764 else {
765 clear_();
766
767 data_ = const_cast<char *>(data);
768 size_ = size;
769
770 if (pool != NULL)
771 copy(pool);
772 }
773 }
774
775 _finline void set(apr_pool_t *pool, const char *data) {
776 set(pool, data, data == NULL ? 0 : strlen(data));
777 }
778
779 _finline void set(apr_pool_t *pool, const std::string &rhs) {
780 set(pool, rhs.data(), rhs.size());
781 }
782
783 bool operator ==(const CYString &rhs) const {
784 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
785 }
786
787 _finline operator CFStringRef() {
788 if (cache_ == NULL)
789 cache_ = CYStringCreate(data_, size_);
790 return cache_;
791 }
792
793 _finline operator id() {
794 return (NSString *) static_cast<CFStringRef>(*this);
795 }
796
797 _finline operator const char *() {
798 return reinterpret_cast<const char *>(data_);
799 }
800 };
801 /* }}} */
802 /* C++ NSString Algorithm Adapters {{{ */
803 extern "C" {
804 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
805 }
806
807 struct NSStringMapHash :
808 std::unary_function<NSString *, size_t>
809 {
810 _finline size_t operator ()(NSString *value) const {
811 return CFStringHashNSString((CFStringRef) value);
812 }
813 };
814
815 struct NSStringMapLess :
816 std::binary_function<NSString *, NSString *, bool>
817 {
818 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
819 return [lhs compare:rhs] == NSOrderedAscending;
820 }
821 };
822
823 struct NSStringMapEqual :
824 std::binary_function<NSString *, NSString *, bool>
825 {
826 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
827 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
828 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
829 //[lhs isEqualToString:rhs];
830 }
831 };
832 /* }}} */
833
834 /* Mime Addresses {{{ */
835 @interface Address : NSObject {
836 NSString *name_;
837 NSString *address_;
838 }
839
840 - (NSString *) name;
841 - (NSString *) address;
842
843 - (void) setAddress:(NSString *)address;
844
845 + (Address *) addressWithString:(NSString *)string;
846 - (Address *) initWithString:(NSString *)string;
847
848 @end
849
850 @implementation Address
851
852 - (void) dealloc {
853 [name_ release];
854 if (address_ != nil)
855 [address_ release];
856 [super dealloc];
857 }
858
859 - (NSString *) name {
860 return name_;
861 }
862
863 - (NSString *) address {
864 return address_;
865 }
866
867 - (void) setAddress:(NSString *)address {
868 if (address_ != nil)
869 [address_ autorelease];
870 if (address == nil)
871 address_ = nil;
872 else
873 address_ = [address retain];
874 }
875
876 + (Address *) addressWithString:(NSString *)string {
877 return [[[Address alloc] initWithString:string] autorelease];
878 }
879
880 + (NSArray *) _attributeKeys {
881 return [NSArray arrayWithObjects:
882 @"address",
883 @"name",
884 nil];
885 }
886
887 - (NSArray *) attributeKeys {
888 return [[self class] _attributeKeys];
889 }
890
891 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
892 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
893 }
894
895 - (Address *) initWithString:(NSString *)string {
896 if ((self = [super init]) != nil) {
897 const char *data = [string UTF8String];
898 size_t size = [string length];
899
900 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
901
902 if (address_r(data, size)) {
903 name_ = [address_r[1] retain];
904 address_ = [address_r[2] retain];
905 } else {
906 name_ = [string retain];
907 address_ = nil;
908 }
909 } return self;
910 }
911
912 @end
913 /* }}} */
914 /* CoreGraphics Primitives {{{ */
915 class CYColor {
916 private:
917 CGColorRef color_;
918
919 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
920 CGFloat color[] = {red, green, blue, alpha};
921 return CGColorCreate(space, color);
922 }
923
924 public:
925 CYColor() :
926 color_(NULL)
927 {
928 }
929
930 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
931 color_(Create_(space, red, green, blue, alpha))
932 {
933 Set(space, red, green, blue, alpha);
934 }
935
936 void Clear() {
937 if (color_ != NULL)
938 CGColorRelease(color_);
939 }
940
941 ~CYColor() {
942 Clear();
943 }
944
945 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
946 Clear();
947 color_ = Create_(space, red, green, blue, alpha);
948 }
949
950 operator CGColorRef() {
951 return color_;
952 }
953 };
954 /* }}} */
955
956 /* Random Global Variables {{{ */
957 static const int PulseInterval_ = 50000;
958
959 static const NSString *UI_;
960
961 static int Finish_;
962 static bool RestartSubstrate_;
963 static NSArray *Finishes_;
964
965 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
966 #define NotifyConfig_ "/etc/notify.conf"
967
968 static bool Queuing_;
969
970 static CYColor Blue_;
971 static CYColor Blueish_;
972 static CYColor Black_;
973 static CYColor Off_;
974 static CYColor White_;
975 static CYColor Gray_;
976 static CYColor Green_;
977 static CYColor Purple_;
978 static CYColor Purplish_;
979
980 static UIColor *InstallingColor_;
981 static UIColor *RemovingColor_;
982
983 static NSString *App_;
984
985 static BOOL Advanced_;
986 static BOOL Ignored_;
987
988 static UIFont *Font12_;
989 static UIFont *Font12Bold_;
990 static UIFont *Font14_;
991 static UIFont *Font18Bold_;
992 static UIFont *Font22Bold_;
993
994 static const char *Machine_ = NULL;
995 static NSString *System_ = nil;
996 static NSString *SerialNumber_ = nil;
997 static NSString *ChipID_ = nil;
998 static _H<NSString> Token_;
999 static NSString *UniqueID_ = nil;
1000 static NSString *PLMN_ = nil;
1001 static NSString *Build_ = nil;
1002 static NSString *Product_ = nil;
1003 static NSString *Safari_ = nil;
1004
1005 static CFLocaleRef Locale_;
1006 static NSArray *Languages_;
1007 static CGColorSpaceRef space_;
1008
1009 static NSDictionary *SectionMap_;
1010 static NSMutableDictionary *Metadata_;
1011 static _transient NSMutableDictionary *Settings_;
1012 static _transient NSString *Role_;
1013 static _transient NSMutableDictionary *Packages_;
1014 static _transient NSMutableDictionary *Sections_;
1015 static _transient NSMutableDictionary *Sources_;
1016 static bool Changed_;
1017 static time_t now_;
1018
1019 bool IsWildcat_;
1020 static CGFloat ScreenScale_;
1021 static NSString *Idiom_;
1022
1023 static NSMutableDictionary *SessionData_;
1024 static NSObject *HostConfig_;
1025 static NSMutableSet *BridgedHosts_;
1026 static NSMutableSet *PipelinedHosts_;
1027
1028 static NSString *kCydiaProgressEventTypeError = @"Error";
1029 static NSString *kCydiaProgressEventTypeInformation = @"Information";
1030 static NSString *kCydiaProgressEventTypeStatus = @"Status";
1031 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
1032 /* }}} */
1033
1034 /* Display Helpers {{{ */
1035 inline float Interpolate(float begin, float end, float fraction) {
1036 return (end - begin) * fraction + begin;
1037 }
1038
1039 static _finline const char *StripVersion_(const char *version) {
1040 const char *colon(strchr(version, ':'));
1041 return colon == NULL ? version : colon + 1;
1042 }
1043
1044 NSString *LocalizeSection(NSString *section) {
1045 static Pcre title_r("^(.*?) \\((.*)\\)$");
1046 if (title_r(section)) {
1047 NSString *parent(title_r[1]);
1048 NSString *child(title_r[2]);
1049
1050 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1051 LocalizeSection(parent),
1052 LocalizeSection(child)
1053 ];
1054 }
1055
1056 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1057 }
1058
1059 NSString *Simplify(NSString *title) {
1060 const char *data = [title UTF8String];
1061 size_t size = [title length];
1062
1063 static Pcre square_r("^\\[(.*)\\]$");
1064 if (square_r(data, size))
1065 return Simplify(square_r[1]);
1066
1067 static Pcre paren_r("^\\((.*)\\)$");
1068 if (paren_r(data, size))
1069 return Simplify(paren_r[1]);
1070
1071 static Pcre title_r("^(.*?) \\((.*)\\)$");
1072 if (title_r(data, size))
1073 return Simplify(title_r[1]);
1074
1075 return title;
1076 }
1077 /* }}} */
1078
1079 NSString *GetLastUpdate() {
1080 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1081
1082 if (update == nil)
1083 return UCLocalize("NEVER_OR_UNKNOWN");
1084
1085 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1086 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1087
1088 CFRelease(formatter);
1089
1090 return [(NSString *) formatted autorelease];
1091 }
1092
1093 bool isSectionVisible(NSString *section) {
1094 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1095 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1096 return hidden == nil || ![hidden boolValue];
1097 }
1098
1099 @class Cydia;
1100
1101 /* Delegate Prototypes {{{ */
1102 @class Package;
1103 @class Source;
1104 @class CydiaProgressEvent;
1105
1106 @protocol DatabaseDelegate
1107 - (void) repairWithSelector:(SEL)selector;
1108 - (void) setConfigurationData:(NSString *)data;
1109 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1110 @end
1111
1112 @class CYPackageController;
1113
1114 @protocol CydiaDelegate
1115 - (void) retainNetworkActivityIndicator;
1116 - (void) releaseNetworkActivityIndicator;
1117 - (void) clearPackage:(Package *)package;
1118 - (void) installPackage:(Package *)package;
1119 - (void) installPackages:(NSArray *)packages;
1120 - (void) removePackage:(Package *)package;
1121 - (void) beginUpdate;
1122 - (BOOL) updating;
1123 - (void) distUpgrade;
1124 - (void) loadData;
1125 - (void) updateData;
1126 - (void) syncData;
1127 - (void) addTrivialSource:(NSString *)href;
1128 - (void) showSettings;
1129 - (UIProgressHUD *) addProgressHUD;
1130 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1131 - (CYViewController *) pageForPackage:(NSString *)name;
1132 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1133 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1134 @end
1135 /* }}} */
1136
1137 /* ProgressEvent Interface/Delegate {{{ */
1138 @interface CydiaProgressEvent : NSObject {
1139 _H<NSString> message_;
1140 _H<NSString> type_;
1141
1142 _H<NSArray> item_;
1143 _H<NSString> package_;
1144 _H<NSString> url_;
1145 _H<NSString> version_;
1146 }
1147
1148 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1149 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1150 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1151
1152 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1153
1154 - (NSString *) message;
1155 - (NSString *) type;
1156
1157 - (NSArray *) item;
1158 - (NSString *) package;
1159 - (NSString *) url;
1160 - (NSString *) version;
1161
1162 - (void) setItem:(NSArray *)item;
1163 - (void) setPackage:(NSString *)package;
1164 - (void) setURL:(NSString *)url;
1165 - (void) setVersion:(NSString *)version;
1166
1167 - (NSString *) compound:(NSString *)value;
1168 - (NSString *) compoundMessage;
1169 - (NSString *) compoundTitle;
1170
1171 @end
1172
1173 @protocol ProgressDelegate
1174 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1175 - (void) setProgressPercent:(NSNumber *)percent;
1176 - (void) setProgressStatus:(NSDictionary *)status;
1177 - (void) setProgressCancellable:(NSNumber *)cancellable;
1178 - (bool) isProgressCancelled;
1179 - (void) setTitle:(NSString *)title;
1180 @end
1181 /* }}} */
1182 /* Status Delegation {{{ */
1183 class Status :
1184 public pkgAcquireStatus
1185 {
1186 private:
1187 _transient NSObject<ProgressDelegate> *delegate_;
1188 bool cancelled_;
1189
1190 public:
1191 Status() :
1192 delegate_(nil),
1193 cancelled_(false)
1194 {
1195 }
1196
1197 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1198 delegate_ = delegate;
1199 }
1200
1201 NSObject<ProgressDelegate> *getDelegate() const {
1202 return delegate_;
1203 }
1204
1205 virtual bool MediaChange(std::string media, std::string drive) {
1206 return false;
1207 }
1208
1209 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1210 }
1211
1212 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1213 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1214 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1215 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1216 }
1217
1218 virtual void Done(pkgAcquire::ItemDesc &item) {
1219 }
1220
1221 virtual void Fail(pkgAcquire::ItemDesc &item) {
1222 if (
1223 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1224 item.Owner->Status == pkgAcquire::Item::StatDone
1225 )
1226 return;
1227
1228 std::string &error(item.Owner->ErrorText);
1229 if (error.empty())
1230 return;
1231
1232 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1233 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1234 }
1235
1236 virtual bool Pulse(pkgAcquire *Owner) {
1237 bool value = pkgAcquireStatus::Pulse(Owner);
1238
1239 double percent(
1240 double(CurrentBytes + CurrentItems) /
1241 double(TotalBytes + TotalItems)
1242 );
1243
1244 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1245 [NSNumber numberWithDouble:percent], @"Percent",
1246
1247 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1248 [NSNumber numberWithDouble:TotalBytes], @"Total",
1249 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1250 nil] waitUntilDone:YES];
1251
1252 if (value && ![delegate_ isProgressCancelled])
1253 return true;
1254 else {
1255 cancelled_ = true;
1256 return false;
1257 }
1258 }
1259
1260 _finline bool WasCancelled() const {
1261 return cancelled_;
1262 }
1263
1264 virtual void Start() {
1265 pkgAcquireStatus::Start();
1266 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1267 }
1268
1269 virtual void Stop() {
1270 pkgAcquireStatus::Stop();
1271 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1272 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1273 }
1274 };
1275 /* }}} */
1276 /* Database Interface {{{ */
1277 typedef std::map< unsigned long, _H<Source> > SourceMap;
1278
1279 @interface Database : NSObject {
1280 NSZone *zone_;
1281 apr_pool_t *pool_;
1282
1283 unsigned era_;
1284
1285 pkgCacheFile cache_;
1286 pkgDepCache::Policy *policy_;
1287 pkgRecords *records_;
1288 pkgProblemResolver *resolver_;
1289 pkgAcquire *fetcher_;
1290 FileFd *lock_;
1291 SPtr<pkgPackageManager> manager_;
1292 pkgSourceList *list_;
1293
1294 SourceMap sourceMap_;
1295 NSMutableArray *sourceList_;
1296
1297 CFMutableArrayRef packages_;
1298
1299 _transient NSObject<DatabaseDelegate> *delegate_;
1300 _transient NSObject<ProgressDelegate> *progress_;
1301
1302 Status status_;
1303
1304 int cydiafd_;
1305 int statusfd_;
1306 FILE *input_;
1307
1308 std::map<const char *, _H<NSString> > sections_;
1309 }
1310
1311 + (Database *) sharedInstance;
1312 - (unsigned) era;
1313
1314 - (void) _readCydia:(NSNumber *)fd;
1315 - (void) _readStatus:(NSNumber *)fd;
1316 - (void) _readOutput:(NSNumber *)fd;
1317
1318 - (FILE *) input;
1319
1320 - (Package *) packageWithName:(NSString *)name;
1321
1322 - (pkgCacheFile &) cache;
1323 - (pkgDepCache::Policy *) policy;
1324 - (pkgRecords *) records;
1325 - (pkgProblemResolver *) resolver;
1326 - (pkgAcquire &) fetcher;
1327 - (pkgSourceList &) list;
1328 - (NSArray *) packages;
1329 - (NSArray *) sources;
1330 - (Source *) sourceWithKey:(NSString *)key;
1331 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1332
1333 - (void) configure;
1334 - (bool) prepare;
1335 - (void) perform;
1336 - (bool) upgrade;
1337 - (void) update;
1338
1339 - (void) updateWithStatus:(Status &)status;
1340
1341 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1342
1343 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1344 - (NSObject<ProgressDelegate> *) progressDelegate;
1345
1346 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1347
1348 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1349
1350 @end
1351 /* }}} */
1352 /* ProgressEvent Implementation {{{ */
1353 @implementation CydiaProgressEvent
1354
1355 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1356 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1357 }
1358
1359 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1360 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1361 [event setPackage:package];
1362 return event;
1363 }
1364
1365 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1366 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1367
1368 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1369 NSArray *fields([description componentsSeparatedByString:@" "]);
1370 [event setItem:fields];
1371
1372 if ([fields count] > 3) {
1373 [event setPackage:[fields objectAtIndex:2]];
1374 [event setVersion:[fields objectAtIndex:3]];
1375 }
1376
1377 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1378
1379 return event;
1380 }
1381
1382 + (NSArray *) _attributeKeys {
1383 return [NSArray arrayWithObjects:
1384 @"item",
1385 @"message",
1386 @"package",
1387 @"type",
1388 @"url",
1389 @"version",
1390 nil];
1391 }
1392
1393 - (NSArray *) attributeKeys {
1394 return [[self class] _attributeKeys];
1395 }
1396
1397 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1398 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1399 }
1400
1401 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1402 if ((self = [super init]) != nil) {
1403 message_ = message;
1404 type_ = type;
1405 } return self;
1406 }
1407
1408 - (NSString *) message {
1409 return message_;
1410 }
1411
1412 - (NSString *) type {
1413 return type_;
1414 }
1415
1416 - (NSArray *) item {
1417 return (id) item_ ?: [NSNull null];
1418 }
1419
1420 - (void) setItem:(NSArray *)item {
1421 item_ = item;
1422 }
1423
1424 - (NSString *) package {
1425 return (id) package_ ?: [NSNull null];
1426 }
1427
1428 - (void) setPackage:(NSString *)package {
1429 package_ = package;
1430 }
1431
1432 - (NSString *) url {
1433 return (id) url_ ?: [NSNull null];
1434 }
1435
1436 - (void) setURL:(NSString *)url {
1437 url_ = url;
1438 }
1439
1440 - (void) setVersion:(NSString *)version {
1441 version_ = version;
1442 }
1443
1444 - (NSString *) version {
1445 return (id) version_ ?: [NSNull null];
1446 }
1447
1448 - (NSString *) compound:(NSString *)value {
1449 if (value != nil) {
1450 NSString *mode(nil); {
1451 NSString *type([self type]);
1452 if ([type isEqualToString:kCydiaProgressEventTypeError])
1453 mode = UCLocalize("ERROR");
1454 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1455 mode = UCLocalize("WARNING");
1456 }
1457
1458 if (mode != nil)
1459 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1460 }
1461
1462 return value;
1463 }
1464
1465 - (NSString *) compoundMessage {
1466 return [self compound:[self message]];
1467 }
1468
1469 - (NSString *) compoundTitle {
1470 NSString *title;
1471
1472 if (package_ == nil)
1473 title = nil;
1474 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1475 title = [package name];
1476 else
1477 title = package_;
1478
1479 return [self compound:title];
1480 }
1481
1482 @end
1483 /* }}} */
1484
1485 // Cytore Definitions {{{
1486 struct PackageValue :
1487 Cytore::Block
1488 {
1489 Cytore::Offset<PackageValue> next_;
1490
1491 uint32_t index_ : 23;
1492 uint32_t subscribed_ : 1;
1493 uint32_t : 8;
1494
1495 int32_t first_;
1496 int32_t last_;
1497
1498 uint16_t vhash_;
1499 uint16_t nhash_;
1500
1501 char version_[8];
1502 char name_[];
1503 };
1504
1505 struct MetaValue :
1506 Cytore::Block
1507 {
1508 uint32_t active_;
1509 Cytore::Offset<PackageValue> packages_[1 << 16];
1510 };
1511
1512 static Cytore::File<MetaValue> MetaFile_;
1513 // }}}
1514 // Cytore Helper Functions {{{
1515 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1516 SplitHash nhash = { hashlittle(name, length) };
1517
1518 PackageValue *metadata;
1519
1520 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1521 offset: if (offset->IsNull()) {
1522 *offset = MetaFile_.New<PackageValue>(length + 1);
1523 metadata = &MetaFile_.Get(*offset);
1524
1525 if (metadata == NULL) {
1526 if (fail != NULL)
1527 *fail = true;
1528
1529 metadata = new PackageValue();
1530 memset(metadata, 0, sizeof(*metadata));
1531 }
1532
1533 memcpy(metadata->name_, name, length + 1);
1534 metadata->nhash_ = nhash.u16[1];
1535 } else {
1536 metadata = &MetaFile_.Get(*offset);
1537
1538 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1539 offset = &metadata->next_;
1540 goto offset;
1541 }
1542 }
1543
1544 return metadata;
1545 }
1546
1547 static void PackageImport(const void *key, const void *value, void *context) {
1548 bool &fail(*reinterpret_cast<bool *>(context));
1549
1550 char buffer[1024];
1551 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1552 NSLog(@"failed to import package %@", key);
1553 return;
1554 }
1555
1556 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1557 NSDictionary *package((NSDictionary *) value);
1558
1559 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1560 if ([subscribed boolValue] && !metadata->subscribed_)
1561 metadata->subscribed_ = true;
1562
1563 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1564 time_t time([date timeIntervalSince1970]);
1565 if (metadata->first_ > time || metadata->first_ == 0)
1566 metadata->first_ = time;
1567 }
1568
1569 NSDate *date([package objectForKey:@"LastSeen"]);
1570 NSString *version([package objectForKey:@"LastVersion"]);
1571
1572 if (date != nil && version != nil) {
1573 time_t time([date timeIntervalSince1970]);
1574 if (metadata->last_ < time || metadata->last_ == 0)
1575 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1576 size_t length(strlen(buffer));
1577 uint16_t vhash(hashlittle(buffer, length));
1578
1579 size_t capped(std::min<size_t>(8, length));
1580 char *latest(buffer + length - capped);
1581
1582 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1583 metadata->vhash_ = vhash;
1584
1585 metadata->last_ = time;
1586 }
1587 }
1588 }
1589 // }}}
1590
1591 /* Source Class {{{ */
1592 @interface Source : NSObject {
1593 CYString depiction_;
1594 CYString description_;
1595 CYString label_;
1596 CYString origin_;
1597 CYString support_;
1598
1599 CYString uri_;
1600 CYString distribution_;
1601 CYString type_;
1602 CYString version_;
1603
1604 _H<NSString> host_;
1605 _H<NSString> authority_;
1606
1607 CYString defaultIcon_;
1608
1609 _H<NSDictionary> record_;
1610 BOOL trusted_;
1611 }
1612
1613 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1614
1615 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1616
1617 - (NSString *) depictionForPackage:(NSString *)package;
1618 - (NSString *) supportForPackage:(NSString *)package;
1619
1620 - (NSDictionary *) record;
1621 - (BOOL) trusted;
1622
1623 - (NSString *) uri;
1624 - (NSString *) distribution;
1625 - (NSString *) type;
1626 - (NSString *) key;
1627 - (NSString *) host;
1628
1629 - (NSString *) name;
1630 - (NSString *) shortDescription;
1631 - (NSString *) label;
1632 - (NSString *) origin;
1633 - (NSString *) version;
1634
1635 - (NSString *) defaultIcon;
1636
1637 @end
1638
1639 @implementation Source
1640
1641 - (void) _clear {
1642 uri_.clear();
1643 distribution_.clear();
1644 type_.clear();
1645
1646 description_.clear();
1647 label_.clear();
1648 origin_.clear();
1649 depiction_.clear();
1650 support_.clear();
1651 version_.clear();
1652 defaultIcon_.clear();
1653
1654 record_ = nil;
1655 host_ = nil;
1656 authority_ = nil;
1657 }
1658
1659 - (void) dealloc {
1660 // XXX: this is a very inefficient way to call these deconstructors
1661 [self _clear];
1662 [super dealloc];
1663 }
1664
1665 + (NSArray *) _attributeKeys {
1666 return [NSArray arrayWithObjects:
1667 @"distribution",
1668 @"host",
1669 @"key",
1670 @"label",
1671 @"name",
1672 @"origin",
1673 @"shortDescription",
1674 @"trusted",
1675 @"type",
1676 @"uri",
1677 @"version",
1678 nil];
1679 }
1680
1681 - (NSArray *) attributeKeys {
1682 return [[self class] _attributeKeys];
1683 }
1684
1685 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1686 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1687 }
1688
1689 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1690 [self _clear];
1691
1692 trusted_ = index->IsTrusted();
1693
1694 uri_.set(pool, index->GetURI());
1695 distribution_.set(pool, index->GetDist());
1696 type_.set(pool, index->GetType());
1697
1698 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1699 if (dindex != NULL) {
1700 FileFd fd;
1701 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1702 _error->Discard();
1703 else {
1704 pkgTagFile tags(&fd);
1705
1706 pkgTagSection section;
1707 tags.Step(section);
1708
1709 struct {
1710 const char *name_;
1711 CYString *value_;
1712 } names[] = {
1713 {"default-icon", &defaultIcon_},
1714 {"depiction", &depiction_},
1715 {"description", &description_},
1716 {"label", &label_},
1717 {"origin", &origin_},
1718 {"support", &support_},
1719 {"version", &version_},
1720 };
1721
1722 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1723 const char *start, *end;
1724
1725 if (section.Find(names[i].name_, start, end)) {
1726 CYString &value(*names[i].value_);
1727 value.set(pool, start, end - start);
1728 }
1729 }
1730 }
1731 }
1732
1733 record_ = [Sources_ objectForKey:[self key]];
1734
1735 NSURL *url([NSURL URLWithString:uri_]);
1736
1737 host_ = [url host];
1738 if (host_ != nil)
1739 host_ = [host_ lowercaseString];
1740
1741 if (host_ != nil)
1742 // XXX: this is due to a bug in _H<>
1743 authority_ = (id) host_;
1744 else
1745 authority_ = [url path];
1746 }
1747
1748 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1749 if ((self = [super init]) != nil) {
1750 [self setMetaIndex:index inPool:pool];
1751 } return self;
1752 }
1753
1754 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1755 NSDictionary *lhr = [self record];
1756 NSDictionary *rhr = [source record];
1757
1758 if (lhr != rhr)
1759 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1760
1761 NSString *lhs = [self name];
1762 NSString *rhs = [source name];
1763
1764 if ([lhs length] != 0 && [rhs length] != 0) {
1765 unichar lhc = [lhs characterAtIndex:0];
1766 unichar rhc = [rhs characterAtIndex:0];
1767
1768 if (isalpha(lhc) && !isalpha(rhc))
1769 return NSOrderedAscending;
1770 else if (!isalpha(lhc) && isalpha(rhc))
1771 return NSOrderedDescending;
1772 }
1773
1774 return [lhs compare:rhs options:LaxCompareOptions_];
1775 }
1776
1777 - (NSString *) depictionForPackage:(NSString *)package {
1778 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1779 }
1780
1781 - (NSString *) supportForPackage:(NSString *)package {
1782 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1783 }
1784
1785 - (NSDictionary *) record {
1786 return record_;
1787 }
1788
1789 - (BOOL) trusted {
1790 return trusted_;
1791 }
1792
1793 - (NSString *) uri {
1794 return uri_;
1795 }
1796
1797 - (NSString *) distribution {
1798 return distribution_;
1799 }
1800
1801 - (NSString *) type {
1802 return type_;
1803 }
1804
1805 - (NSString *) key {
1806 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1807 }
1808
1809 - (NSString *) host {
1810 return host_;
1811 }
1812
1813 - (NSString *) name {
1814 return origin_.empty() ? (id) authority_ : origin_;
1815 }
1816
1817 - (NSString *) shortDescription {
1818 return description_;
1819 }
1820
1821 - (NSString *) label {
1822 return label_.empty() ? (id) authority_ : label_;
1823 }
1824
1825 - (NSString *) origin {
1826 return origin_;
1827 }
1828
1829 - (NSString *) version {
1830 return version_;
1831 }
1832
1833 - (NSString *) defaultIcon {
1834 return defaultIcon_;
1835 }
1836
1837 @end
1838 /* }}} */
1839 /* CydiaOperation Class {{{ */
1840 @interface CydiaOperation : NSObject {
1841 NSString *operator_;
1842 NSString *value_;
1843 }
1844
1845 - (NSString *) operator;
1846 - (NSString *) value;
1847
1848 @end
1849
1850 @implementation CydiaOperation
1851
1852 - (void) dealloc {
1853 [operator_ release];
1854 [value_ release];
1855 [super dealloc];
1856 }
1857
1858 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1859 if ((self = [super init]) != nil) {
1860 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1861 value_ = [[NSString alloc] initWithUTF8String:value];
1862 } return self;
1863 }
1864
1865 + (NSArray *) _attributeKeys {
1866 return [NSArray arrayWithObjects:
1867 @"operator",
1868 @"value",
1869 nil];
1870 }
1871
1872 - (NSArray *) attributeKeys {
1873 return [[self class] _attributeKeys];
1874 }
1875
1876 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1877 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1878 }
1879
1880 - (NSString *) operator {
1881 return operator_;
1882 }
1883
1884 - (NSString *) value {
1885 return value_;
1886 }
1887
1888 @end
1889 /* }}} */
1890 /* CydiaClause Class {{{ */
1891 @interface CydiaClause : NSObject {
1892 NSString *package_;
1893 CydiaOperation *version_;
1894 }
1895
1896 - (NSString *) package;
1897 - (CydiaOperation *) version;
1898
1899 @end
1900
1901 @implementation CydiaClause
1902
1903 - (void) dealloc {
1904 [package_ release];
1905 [version_ release];
1906 [super dealloc];
1907 }
1908
1909 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1910 if ((self = [super init]) != nil) {
1911 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1912
1913 if (const char *version = dep.TargetVer())
1914 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1915 else
1916 version_ = [[NSNull null] retain];
1917 } return self;
1918 }
1919
1920 + (NSArray *) _attributeKeys {
1921 return [NSArray arrayWithObjects:
1922 @"package",
1923 @"version",
1924 nil];
1925 }
1926
1927 - (NSArray *) attributeKeys {
1928 return [[self class] _attributeKeys];
1929 }
1930
1931 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1932 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1933 }
1934
1935 - (NSString *) package {
1936 return package_;
1937 }
1938
1939 - (CydiaOperation *) version {
1940 return version_;
1941 }
1942
1943 @end
1944 /* }}} */
1945 /* CydiaRelation Class {{{ */
1946 @interface CydiaRelation : NSObject {
1947 NSString *relationship_;
1948 NSMutableArray *clauses_;
1949 }
1950
1951 - (NSString *) relationship;
1952 - (NSArray *) clauses;
1953
1954 @end
1955
1956 @implementation CydiaRelation
1957
1958 - (void) dealloc {
1959 [relationship_ release];
1960 [clauses_ release];
1961 [super dealloc];
1962 }
1963
1964 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1965 if ((self = [super init]) != nil) {
1966 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1967 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1968
1969 pkgCache::DepIterator start;
1970 pkgCache::DepIterator end;
1971 dep.GlobOr(start, end); // ++dep
1972
1973 _forever {
1974 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1975
1976 // yes, seriously. (wtf?)
1977 if (start == end)
1978 break;
1979 ++start;
1980 }
1981 } return self;
1982 }
1983
1984 + (NSArray *) _attributeKeys {
1985 return [NSArray arrayWithObjects:
1986 @"clauses",
1987 @"relationship",
1988 nil];
1989 }
1990
1991 - (NSArray *) attributeKeys {
1992 return [[self class] _attributeKeys];
1993 }
1994
1995 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1996 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1997 }
1998
1999 - (NSString *) relationship {
2000 return relationship_;
2001 }
2002
2003 - (NSArray *) clauses {
2004 return clauses_;
2005 }
2006
2007 - (void) addClause:(CydiaClause *)clause {
2008 [clauses_ addObject:clause];
2009 }
2010
2011 @end
2012 /* }}} */
2013 /* Package Class {{{ */
2014 struct ParsedPackage {
2015 CYString tagline_;
2016
2017 CYString icon_;
2018
2019 CYString depiction_;
2020 CYString homepage_;
2021
2022 CYString sponsor_;
2023 CYString author_;
2024
2025 CYString bugs_;
2026 CYString support_;
2027 };
2028
2029 @interface Package : NSObject {
2030 uint32_t era_ : 26;
2031 uint32_t role_ : 3;
2032 uint32_t essential_ : 1;
2033 uint32_t obsolete_ : 1;
2034 uint32_t ignored_ : 1;
2035
2036 apr_pool_t *pool_;
2037
2038 _transient Database *database_;
2039
2040 pkgCache::VerIterator version_;
2041 pkgCache::PkgIterator iterator_;
2042 pkgCache::VerFileIterator file_;
2043
2044 CYString id_;
2045 CYString name_;
2046
2047 CYString latest_;
2048 CYString installed_;
2049
2050 const char *section_;
2051 _transient NSString *section$_;
2052
2053 Source *source_;
2054
2055 PackageValue *metadata_;
2056 ParsedPackage *parsed_;
2057
2058 NSMutableArray *tags_;
2059 }
2060
2061 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2062 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2063
2064 - (pkgCache::PkgIterator) iterator;
2065 - (void) parse;
2066
2067 - (NSString *) section;
2068 - (NSString *) simpleSection;
2069
2070 - (NSString *) longSection;
2071 - (NSString *) shortSection;
2072
2073 - (NSString *) uri;
2074
2075 - (Address *) maintainer;
2076 - (size_t) size;
2077 - (NSString *) longDescription;
2078 - (NSString *) shortDescription;
2079 - (unichar) index;
2080
2081 - (PackageValue *) metadata;
2082 - (time_t) seen;
2083
2084 - (bool) subscribed;
2085 - (bool) setSubscribed:(bool)subscribed;
2086
2087 - (BOOL) ignored;
2088
2089 - (NSString *) latest;
2090 - (NSString *) installed;
2091 - (BOOL) uninstalled;
2092
2093 - (BOOL) valid;
2094 - (BOOL) upgradableAndEssential:(BOOL)essential;
2095 - (BOOL) essential;
2096 - (BOOL) broken;
2097 - (BOOL) unfiltered;
2098 - (BOOL) visible;
2099
2100 - (BOOL) half;
2101 - (BOOL) halfConfigured;
2102 - (BOOL) halfInstalled;
2103 - (BOOL) hasMode;
2104 - (NSString *) mode;
2105
2106 - (NSString *) id;
2107 - (NSString *) name;
2108 - (UIImage *) icon;
2109 - (NSString *) homepage;
2110 - (NSString *) depiction;
2111 - (Address *) author;
2112
2113 - (NSString *) support;
2114
2115 - (NSArray *) files;
2116 - (NSArray *) warnings;
2117 - (NSArray *) applications;
2118
2119 - (Source *) source;
2120
2121 - (BOOL) matches:(NSString *)text;
2122
2123 - (bool) hasSupportingRole;
2124 - (BOOL) hasTag:(NSString *)tag;
2125 - (NSString *) primaryPurpose;
2126 - (NSArray *) purposes;
2127 - (bool) isCommercial;
2128
2129 - (void) setIndex:(size_t)index;
2130
2131 - (CYString &) cyname;
2132
2133 - (uint32_t) compareBySection:(NSArray *)sections;
2134
2135 - (void) install;
2136 - (void) remove;
2137
2138 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2139 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2140 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2141 - (bool) isVisibleInSection:(NSString *)section;
2142 - (bool) isVisibleInSource:(Source *)source;
2143
2144 @end
2145
2146 uint32_t PackageChangesRadix(Package *self, void *) {
2147 union {
2148 uint32_t key;
2149
2150 struct {
2151 uint32_t timestamp : 30;
2152 uint32_t ignored : 1;
2153 uint32_t upgradable : 1;
2154 } bits;
2155 } value;
2156
2157 bool upgradable([self upgradableAndEssential:YES]);
2158 value.bits.upgradable = upgradable ? 1 : 0;
2159
2160 if (upgradable) {
2161 value.bits.timestamp = 0;
2162 value.bits.ignored = [self ignored] ? 0 : 1;
2163 value.bits.upgradable = 1;
2164 } else {
2165 value.bits.timestamp = [self seen] >> 2;
2166 value.bits.ignored = 0;
2167 value.bits.upgradable = 0;
2168 }
2169
2170 return _not(uint32_t) - value.key;
2171 }
2172
2173 uint32_t PackagePrefixRadix(Package *self, void *context) {
2174 size_t offset(reinterpret_cast<size_t>(context));
2175 CYString &name([self cyname]);
2176
2177 size_t size(name.size());
2178 if (size == 0)
2179 return 0;
2180 char *text(name.data());
2181
2182 size_t zeros;
2183 if (!isdigit(text[0]))
2184 zeros = 0;
2185 else {
2186 size_t digits(1);
2187 while (size != digits && isdigit(text[digits]))
2188 if (++digits == 4)
2189 break;
2190 zeros = 4 - digits;
2191 }
2192
2193 uint8_t data[4];
2194
2195 if (offset == 0 && zeros != 0) {
2196 memset(data, '0', zeros);
2197 memcpy(data + zeros, text, 4 - zeros);
2198 } else {
2199 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2200 if (size <= offset - zeros)
2201 return 0;
2202
2203 text += offset - zeros;
2204 size -= offset - zeros;
2205
2206 if (size >= 4)
2207 memcpy(data, text, 4);
2208 else {
2209 memcpy(data, text, size);
2210 memset(data + size, 0, 4 - size);
2211 }
2212
2213 for (size_t i(0); i != 4; ++i)
2214 if (isalpha(data[i]))
2215 data[i] |= 0x20;
2216 }
2217
2218 if (offset == 0)
2219 if (data[0] == '@')
2220 data[0] = 0x7f;
2221 else
2222 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2223
2224 /* XXX: ntohl may be more honest */
2225 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2226 }
2227
2228 CYString &(*PackageName)(Package *self, SEL sel);
2229
2230 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2231 _profile(PackageNameCompare)
2232 CYString &lhi(PackageName(lhs, @selector(cyname)));
2233 CYString &rhi(PackageName(rhs, @selector(cyname)));
2234 CFStringRef lhn(lhi), rhn(rhi);
2235
2236 if (lhn == NULL)
2237 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2238 else if (rhn == NULL)
2239 return NSOrderedDescending;
2240
2241 _profile(PackageNameCompare$NumbersLast)
2242 if (!lhi.empty() && !rhi.empty()) {
2243 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2244 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2245 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2246 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2247 return lha ? NSOrderedAscending : NSOrderedDescending;
2248 }
2249 _end
2250
2251 CFIndex length = CFStringGetLength(lhn);
2252
2253 _profile(PackageNameCompare$Compare)
2254 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2255 _end
2256 _end
2257 }
2258
2259 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2260 return PackageNameCompare(*lhs, *rhs, context);
2261 }
2262
2263 struct PackageNameOrdering :
2264 std::binary_function<Package *, Package *, bool>
2265 {
2266 _finline bool operator ()(Package *lhs, Package *rhs) const {
2267 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2268 }
2269 };
2270
2271 @implementation Package
2272
2273 - (NSString *) description {
2274 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2275 }
2276
2277 - (void) dealloc {
2278 if (parsed_ != NULL)
2279 delete parsed_;
2280 if (source_ != nil)
2281 [source_ release];
2282 if (tags_ != nil)
2283 [tags_ release];
2284 [super dealloc];
2285 }
2286
2287 + (NSString *) webScriptNameForSelector:(SEL)selector {
2288 if (false);
2289 else if (selector == @selector(clear))
2290 return @"clear";
2291 else if (selector == @selector(getField:))
2292 return @"getField";
2293 else if (selector == @selector(hasTag:))
2294 return @"hasTag";
2295 else if (selector == @selector(install))
2296 return @"install";
2297 else if (selector == @selector(remove))
2298 return @"remove";
2299 else
2300 return nil;
2301 }
2302
2303 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2304 return [self webScriptNameForSelector:selector] == nil;
2305 }
2306
2307 + (NSArray *) _attributeKeys {
2308 return [NSArray arrayWithObjects:
2309 @"applications",
2310 @"author",
2311 @"depiction",
2312 @"essential",
2313 @"homepage",
2314 @"icon",
2315 @"id",
2316 @"installed",
2317 @"latest",
2318 @"longDescription",
2319 @"longSection",
2320 @"maintainer",
2321 @"mode",
2322 @"name",
2323 @"purposes",
2324 @"relations",
2325 @"section",
2326 @"selection",
2327 @"shortDescription",
2328 @"shortSection",
2329 @"simpleSection",
2330 @"size",
2331 @"source",
2332 @"sponsor",
2333 @"state",
2334 @"support",
2335 @"tags",
2336 @"warnings",
2337 nil];
2338 }
2339
2340 - (NSArray *) attributeKeys {
2341 return [[self class] _attributeKeys];
2342 }
2343
2344 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2345 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2346 }
2347
2348 - (NSArray *) relations {
2349 @synchronized (database_) {
2350 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2351 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2352 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2353 return relations;
2354 } }
2355
2356 - (NSString *) getField:(NSString *)name {
2357 @synchronized (database_) {
2358 if ([database_ era] != era_ || file_.end())
2359 return nil;
2360
2361 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2362
2363 const char *start, *end;
2364 if (!parser.Find([name UTF8String], start, end))
2365 return (NSString *) [NSNull null];
2366
2367 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2368 } }
2369
2370 - (void) parse {
2371 if (parsed_ != NULL)
2372 return;
2373 @synchronized (database_) {
2374 if ([database_ era] != era_ || file_.end())
2375 return;
2376
2377 ParsedPackage *parsed(new ParsedPackage);
2378 parsed_ = parsed;
2379
2380 _profile(Package$parse)
2381 pkgRecords::Parser *parser;
2382
2383 _profile(Package$parse$Lookup)
2384 parser = &[database_ records]->Lookup(file_);
2385 _end
2386
2387 CYString website;
2388
2389 _profile(Package$parse$Find)
2390 struct {
2391 const char *name_;
2392 CYString *value_;
2393 } names[] = {
2394 {"icon", &parsed->icon_},
2395 {"depiction", &parsed->depiction_},
2396 {"homepage", &parsed->homepage_},
2397 {"website", &website},
2398 {"bugs", &parsed->bugs_},
2399 {"support", &parsed->support_},
2400 {"sponsor", &parsed->sponsor_},
2401 {"author", &parsed->author_},
2402 };
2403
2404 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2405 const char *start, *end;
2406
2407 if (parser->Find(names[i].name_, start, end)) {
2408 CYString &value(*names[i].value_);
2409 _profile(Package$parse$Value)
2410 value.set(pool_, start, end - start);
2411 _end
2412 }
2413 }
2414 _end
2415
2416 _profile(Package$parse$Tagline)
2417 const char *start, *end;
2418 if (parser->ShortDesc(start, end)) {
2419 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2420 if (stop == NULL)
2421 stop = end;
2422 while (stop != start && stop[-1] == '\r')
2423 --stop;
2424 parsed->tagline_.set(pool_, start, stop - start);
2425 }
2426 _end
2427
2428 _profile(Package$parse$Retain)
2429 if (parsed->homepage_.empty())
2430 parsed->homepage_ = website;
2431 if (parsed->homepage_ == parsed->depiction_)
2432 parsed->homepage_.clear();
2433 _end
2434 _end
2435 } }
2436
2437 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2438 if ((self = [super init]) != nil) {
2439 _profile(Package$initWithVersion)
2440 pool_ = pool;
2441
2442 database_ = database;
2443 era_ = [database era];
2444
2445 version_ = version;
2446
2447 pkgCache::PkgIterator iterator(version.ParentPkg());
2448 iterator_ = iterator;
2449
2450 _profile(Package$initWithVersion$Version)
2451 if (!version_.end())
2452 file_ = version_.FileList();
2453 else {
2454 pkgCache &cache([database_ cache]);
2455 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2456 }
2457 _end
2458
2459 _profile(Package$initWithVersion$Cache)
2460 name_.set(NULL, iterator.Display());
2461
2462 latest_.set(NULL, StripVersion_(version_.VerStr()));
2463
2464 pkgCache::VerIterator current(iterator.CurrentVer());
2465 if (!current.end())
2466 installed_.set(NULL, StripVersion_(current.VerStr()));
2467 _end
2468
2469 _profile(Package$initWithVersion$Tags)
2470 pkgCache::TagIterator tag(iterator.TagList());
2471 if (!tag.end()) {
2472 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2473 do {
2474 const char *name(tag.Name());
2475 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2476
2477 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2478 if (strcmp(name + 6, "enduser") == 0)
2479 role_ = 1;
2480 else if (strcmp(name + 6, "hacker") == 0)
2481 role_ = 2;
2482 else if (strcmp(name + 6, "developer") == 0)
2483 role_ = 3;
2484 else if (strcmp(name + 6, "cydia") == 0)
2485 role_ = 7;
2486 else
2487 role_ = 4;
2488 }
2489
2490 if (strncmp(name, "cydia::", 7) == 0) {
2491 if (strcmp(name + 7, "essential") == 0)
2492 essential_ = true;
2493 else if (strcmp(name + 7, "obsolete") == 0)
2494 obsolete_ = true;
2495 }
2496
2497 ++tag;
2498 } while (!tag.end());
2499 }
2500 _end
2501
2502 _profile(Package$initWithVersion$Metadata)
2503 const char *mixed(iterator.Name());
2504 size_t size(strlen(mixed));
2505 char lower[size + 1];
2506
2507 for (size_t i(0); i != size; ++i)
2508 lower[i] = mixed[i] | 0x20;
2509 lower[size] = '\0';
2510
2511 PackageValue *metadata(PackageFind(lower, size));
2512 metadata_ = metadata;
2513
2514 id_.set(NULL, metadata->name_, size);
2515
2516 const char *latest(version_.VerStr());
2517 size_t length(strlen(latest));
2518
2519 uint16_t vhash(hashlittle(latest, length));
2520
2521 size_t capped(std::min<size_t>(8, length));
2522 latest = latest + length - capped;
2523
2524 if (metadata->first_ == 0)
2525 metadata->first_ = now_;
2526
2527 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2528 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2529 metadata->vhash_ = vhash;
2530 metadata->last_ = now_;
2531 } else if (metadata->last_ == 0)
2532 metadata->last_ = metadata->first_;
2533 _end
2534
2535 _profile(Package$initWithVersion$Section)
2536 section_ = iterator.Section();
2537 _end
2538
2539 _profile(Package$initWithVersion$Flags)
2540 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2541 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2542 _end
2543 _end } return self;
2544 }
2545
2546 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2547 pkgCache::VerIterator version;
2548
2549 _profile(Package$packageWithIterator$GetCandidateVer)
2550 version = [database policy]->GetCandidateVer(iterator);
2551 _end
2552
2553 if (version.end())
2554 return nil;
2555
2556 Package *package;
2557
2558 _profile(Package$packageWithIterator$Allocate)
2559 package = [Package allocWithZone:zone];
2560 _end
2561
2562 _profile(Package$packageWithIterator$Initialize)
2563 package = [package
2564 initWithVersion:version
2565 withZone:zone
2566 inPool:pool
2567 database:database
2568 ];
2569 _end
2570
2571 _profile(Package$packageWithIterator$Autorelease)
2572 package = [package autorelease];
2573 _end
2574
2575 return package;
2576 }
2577
2578 - (pkgCache::PkgIterator) iterator {
2579 return iterator_;
2580 }
2581
2582 - (NSString *) section {
2583 if (section$_ == nil) {
2584 if (section_ == NULL)
2585 return nil;
2586
2587 _profile(Package$section$mappedSectionForPointer)
2588 section$_ = [database_ mappedSectionForPointer:section_];
2589 _end
2590 } return section$_;
2591 }
2592
2593 - (NSString *) simpleSection {
2594 if (NSString *section = [self section])
2595 return Simplify(section);
2596 else
2597 return nil;
2598 }
2599
2600 - (NSString *) longSection {
2601 return LocalizeSection([self section]);
2602 }
2603
2604 - (NSString *) shortSection {
2605 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2606 }
2607
2608 - (NSString *) uri {
2609 return nil;
2610 #if 0
2611 pkgIndexFile *index;
2612 pkgCache::PkgFileIterator file(file_.File());
2613 if (![database_ list].FindIndex(file, index))
2614 return nil;
2615 return [NSString stringWithUTF8String:iterator_->Path];
2616 //return [NSString stringWithUTF8String:file.Site()];
2617 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2618 #endif
2619 }
2620
2621 - (Address *) maintainer {
2622 @synchronized (database_) {
2623 if ([database_ era] != era_ || file_.end())
2624 return nil;
2625
2626 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2627 const std::string &maintainer(parser->Maintainer());
2628 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2629 } }
2630
2631 - (size_t) size {
2632 @synchronized (database_) {
2633 if ([database_ era] != era_ || version_.end())
2634 return 0;
2635
2636 return version_->InstalledSize;
2637 } }
2638
2639 - (NSString *) longDescription {
2640 @synchronized (database_) {
2641 if ([database_ era] != era_ || file_.end())
2642 return nil;
2643
2644 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2645 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2646
2647 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2648 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2649 if ([lines count] < 2)
2650 return nil;
2651
2652 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2653 for (size_t i(1), e([lines count]); i != e; ++i) {
2654 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2655 [trimmed addObject:trim];
2656 }
2657
2658 return [trimmed componentsJoinedByString:@"\n"];
2659 } }
2660
2661 - (NSString *) shortDescription {
2662 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2663 }
2664
2665 - (unichar) index {
2666 _profile(Package$index)
2667 CFStringRef name((CFStringRef) [self name]);
2668 if (CFStringGetLength(name) == 0)
2669 return '#';
2670 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2671 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2672 return '#';
2673 return toupper(character);
2674 _end
2675 }
2676
2677 - (PackageValue *) metadata {
2678 return metadata_;
2679 }
2680
2681 - (time_t) seen {
2682 PackageValue *metadata([self metadata]);
2683 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2684 }
2685
2686 - (bool) subscribed {
2687 return [self metadata]->subscribed_;
2688 }
2689
2690 - (bool) setSubscribed:(bool)subscribed {
2691 PackageValue *metadata([self metadata]);
2692 if (metadata->subscribed_ == subscribed)
2693 return false;
2694 metadata->subscribed_ = subscribed;
2695 return true;
2696 }
2697
2698 - (BOOL) ignored {
2699 return ignored_;
2700 }
2701
2702 - (NSString *) latest {
2703 return latest_;
2704 }
2705
2706 - (NSString *) installed {
2707 return installed_;
2708 }
2709
2710 - (BOOL) uninstalled {
2711 return installed_.empty();
2712 }
2713
2714 - (BOOL) valid {
2715 return !version_.end();
2716 }
2717
2718 - (BOOL) upgradableAndEssential:(BOOL)essential {
2719 _profile(Package$upgradableAndEssential)
2720 pkgCache::VerIterator current(iterator_.CurrentVer());
2721 if (current.end())
2722 return essential && essential_;
2723 else
2724 return !version_.end() && version_ != current;
2725 _end
2726 }
2727
2728 - (BOOL) essential {
2729 return essential_;
2730 }
2731
2732 - (BOOL) broken {
2733 return [database_ cache][iterator_].InstBroken();
2734 }
2735
2736 - (BOOL) unfiltered {
2737 _profile(Package$unfiltered$obsolete)
2738 if (_unlikely(obsolete_))
2739 return false;
2740 _end
2741
2742 _profile(Package$unfiltered$hasSupportingRole)
2743 if (_unlikely(![self hasSupportingRole]))
2744 return false;
2745 _end
2746
2747 return true;
2748 }
2749
2750 - (BOOL) visible {
2751 if (![self unfiltered])
2752 return false;
2753
2754 NSString *section;
2755
2756 _profile(Package$visible$section)
2757 section = [self section];
2758 _end
2759
2760 _profile(Package$visible$isSectionVisible)
2761 if (!isSectionVisible(section))
2762 return false;
2763 _end
2764
2765 return true;
2766 }
2767
2768 - (BOOL) half {
2769 unsigned char current(iterator_->CurrentState);
2770 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2771 }
2772
2773 - (BOOL) halfConfigured {
2774 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2775 }
2776
2777 - (BOOL) halfInstalled {
2778 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2779 }
2780
2781 - (BOOL) hasMode {
2782 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2783 return state.Mode != pkgDepCache::ModeKeep;
2784 }
2785
2786 - (NSString *) mode {
2787 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2788
2789 switch (state.Mode) {
2790 case pkgDepCache::ModeDelete:
2791 if ((state.iFlags & pkgDepCache::Purge) != 0)
2792 return @"PURGE";
2793 else
2794 return @"REMOVE";
2795 case pkgDepCache::ModeKeep:
2796 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2797 return @"REINSTALL";
2798 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2799 return nil;*/
2800 else
2801 return nil;
2802 case pkgDepCache::ModeInstall:
2803 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2804 return @"REINSTALL";
2805 else*/ switch (state.Status) {
2806 case -1:
2807 return @"DOWNGRADE";
2808 case 0:
2809 return @"INSTALL";
2810 case 1:
2811 return @"UPGRADE";
2812 case 2:
2813 return @"NEW_INSTALL";
2814 _nodefault
2815 }
2816 _nodefault
2817 }
2818 }
2819
2820 - (NSString *) id {
2821 return id_;
2822 }
2823
2824 - (NSString *) name {
2825 return name_.empty() ? id_ : name_;
2826 }
2827
2828 - (UIImage *) icon {
2829 NSString *section = [self simpleSection];
2830
2831 UIImage *icon(nil);
2832 if (parsed_ != NULL)
2833 if (NSString *href = parsed_->icon_)
2834 if ([href hasPrefix:@"file:///"])
2835 // XXX: correct escaping
2836 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2837 if (icon == nil) if (section != nil)
2838 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2839 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2840 if ([dicon hasPrefix:@"file:///"])
2841 // XXX: correct escaping
2842 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2843 if (icon == nil)
2844 icon = [UIImage applicationImageNamed:@"unknown.png"];
2845 return icon;
2846 }
2847
2848 - (NSString *) homepage {
2849 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2850 }
2851
2852 - (NSString *) depiction {
2853 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2854 }
2855
2856 - (Address *) sponsor {
2857 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2858 }
2859
2860 - (Address *) author {
2861 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2862 }
2863
2864 - (NSString *) support {
2865 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2866 }
2867
2868 - (NSArray *) files {
2869 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2870 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2871
2872 std::ifstream fin;
2873 fin.open([path UTF8String]);
2874 if (!fin.is_open())
2875 return nil;
2876
2877 std::string line;
2878 while (std::getline(fin, line))
2879 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2880
2881 return files;
2882 }
2883
2884 - (NSString *) state {
2885 @synchronized (database_) {
2886 if ([database_ era] != era_ || file_.end())
2887 return nil;
2888
2889 switch (iterator_->CurrentState) {
2890 case pkgCache::State::NotInstalled:
2891 return @"NotInstalled";
2892 case pkgCache::State::UnPacked:
2893 return @"UnPacked";
2894 case pkgCache::State::HalfConfigured:
2895 return @"HalfConfigured";
2896 case pkgCache::State::HalfInstalled:
2897 return @"HalfInstalled";
2898 case pkgCache::State::ConfigFiles:
2899 return @"ConfigFiles";
2900 case pkgCache::State::Installed:
2901 return @"Installed";
2902 case pkgCache::State::TriggersAwaited:
2903 return @"TriggersAwaited";
2904 case pkgCache::State::TriggersPending:
2905 return @"TriggersPending";
2906 }
2907
2908 return (NSString *) [NSNull null];
2909 } }
2910
2911 - (NSString *) selection {
2912 @synchronized (database_) {
2913 if ([database_ era] != era_ || file_.end())
2914 return nil;
2915
2916 switch (iterator_->SelectedState) {
2917 case pkgCache::State::Unknown:
2918 return @"Unknown";
2919 case pkgCache::State::Install:
2920 return @"Install";
2921 case pkgCache::State::Hold:
2922 return @"Hold";
2923 case pkgCache::State::DeInstall:
2924 return @"DeInstall";
2925 case pkgCache::State::Purge:
2926 return @"Purge";
2927 }
2928
2929 return (NSString *) [NSNull null];
2930 } }
2931
2932 - (NSArray *) warnings {
2933 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2934 const char *name(iterator_.Name());
2935
2936 size_t length(strlen(name));
2937 if (length < 2) invalid:
2938 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2939 else for (size_t i(0); i != length; ++i)
2940 if (
2941 /* XXX: technically this is not allowed */
2942 (name[i] < 'A' || name[i] > 'Z') &&
2943 (name[i] < 'a' || name[i] > 'z') &&
2944 (name[i] < '0' || name[i] > '9') &&
2945 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2946 ) goto invalid;
2947
2948 if (strcmp(name, "cydia") != 0) {
2949 bool cydia = false;
2950 bool user = false;
2951 bool _private = false;
2952 bool stash = false;
2953
2954 bool repository = [[self section] isEqualToString:@"Repositories"];
2955
2956 if (NSArray *files = [self files])
2957 for (NSString *file in files)
2958 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2959 cydia = true;
2960 else if (!user && [file isEqualToString:@"/User"])
2961 user = true;
2962 else if (!_private && [file isEqualToString:@"/private"])
2963 _private = true;
2964 else if (!stash && [file isEqualToString:@"/var/stash"])
2965 stash = true;
2966
2967 /* XXX: this is not sensitive enough. only some folders are valid. */
2968 if (cydia && !repository)
2969 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2970 if (user)
2971 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2972 if (_private)
2973 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2974 if (stash)
2975 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2976 }
2977
2978 return [warnings count] == 0 ? nil : warnings;
2979 }
2980
2981 - (NSArray *) applications {
2982 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2983
2984 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2985
2986 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2987 if (NSArray *files = [self files])
2988 for (NSString *file in files)
2989 if (application_r(file)) {
2990 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2991 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2992 if ([id isEqualToString:me])
2993 continue;
2994
2995 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2996 if (display == nil)
2997 display = application_r[1];
2998
2999 NSString *bundle([file stringByDeletingLastPathComponent]);
3000 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3001 if (icon == nil || [icon length] == 0)
3002 icon = @"icon.png";
3003 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3004
3005 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3006 [applications addObject:application];
3007
3008 [application addObject:id];
3009 [application addObject:display];
3010 [application addObject:url];
3011 }
3012
3013 return [applications count] == 0 ? nil : applications;
3014 }
3015
3016 - (Source *) source {
3017 if (source_ == nil) {
3018 @synchronized (database_) {
3019 if ([database_ era] != era_ || file_.end())
3020 source_ = (Source *) [NSNull null];
3021 else
3022 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3023 }
3024 }
3025
3026 return source_ == (Source *) [NSNull null] ? nil : source_;
3027 }
3028
3029 - (BOOL) matches:(NSString *)text {
3030 if (text == nil)
3031 return NO;
3032
3033 NSRange range;
3034
3035 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3036 if (range.location != NSNotFound)
3037 return YES;
3038
3039 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3040 if (range.location != NSNotFound)
3041 return YES;
3042
3043 [self parse];
3044
3045 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3046 if (range.location != NSNotFound)
3047 return YES;
3048
3049 return NO;
3050 }
3051
3052 - (bool) hasSupportingRole {
3053 if (role_ == 0)
3054 return true;
3055 if (role_ == 1)
3056 return true;
3057 if ([Role_ isEqualToString:@"User"])
3058 return false;
3059 if (role_ == 2)
3060 return true;
3061 if ([Role_ isEqualToString:@"Hacker"])
3062 return false;
3063 if (role_ == 3)
3064 return true;
3065 if ([Role_ isEqualToString:@"Developer"])
3066 return false;
3067 _assert(false);
3068 }
3069
3070 - (NSArray *) tags {
3071 return tags_;
3072 }
3073
3074 - (BOOL) hasTag:(NSString *)tag {
3075 return tags_ == nil ? NO : [tags_ containsObject:tag];
3076 }
3077
3078 - (NSString *) primaryPurpose {
3079 for (NSString *tag in tags_)
3080 if ([tag hasPrefix:@"purpose::"])
3081 return [tag substringFromIndex:9];
3082 return nil;
3083 }
3084
3085 - (NSArray *) purposes {
3086 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3087 for (NSString *tag in tags_)
3088 if ([tag hasPrefix:@"purpose::"])
3089 [purposes addObject:[tag substringFromIndex:9]];
3090 return [purposes count] == 0 ? nil : purposes;
3091 }
3092
3093 - (bool) isCommercial {
3094 return [self hasTag:@"cydia::commercial"];
3095 }
3096
3097 - (void) setIndex:(size_t)index {
3098 if (metadata_->index_ != index)
3099 metadata_->index_ = index;
3100 }
3101
3102 - (CYString &) cyname {
3103 return name_.empty() ? id_ : name_;
3104 }
3105
3106 - (uint32_t) compareBySection:(NSArray *)sections {
3107 NSString *section([self section]);
3108 for (size_t i(0), e([sections count]); i != e; ++i) {
3109 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3110 return i;
3111 }
3112
3113 return _not(uint32_t);
3114 }
3115
3116 - (void) clear {
3117 @synchronized (database_) {
3118 pkgProblemResolver *resolver = [database_ resolver];
3119 resolver->Clear(iterator_);
3120
3121 pkgCacheFile &cache([database_ cache]);
3122 cache->SetReInstall(iterator_, false);
3123 cache->MarkKeep(iterator_, false);
3124 } }
3125
3126 - (void) install {
3127 @synchronized (database_) {
3128 pkgProblemResolver *resolver = [database_ resolver];
3129 resolver->Clear(iterator_);
3130 resolver->Protect(iterator_);
3131
3132 pkgCacheFile &cache([database_ cache]);
3133 cache->SetReInstall(iterator_, false);
3134 cache->MarkInstall(iterator_, false);
3135
3136 pkgDepCache::StateCache &state((*cache)[iterator_]);
3137 if (!state.Install())
3138 cache->SetReInstall(iterator_, true);
3139 } }
3140
3141 - (void) remove {
3142 @synchronized (database_) {
3143 pkgProblemResolver *resolver = [database_ resolver];
3144 resolver->Clear(iterator_);
3145 resolver->Remove(iterator_);
3146 resolver->Protect(iterator_);
3147
3148 pkgCacheFile &cache([database_ cache]);
3149 cache->SetReInstall(iterator_, false);
3150 cache->MarkDelete(iterator_, true);
3151 } }
3152
3153 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3154 _profile(Package$isUnfilteredAndSearchedForBy)
3155 bool value(true);
3156
3157 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3158 value &= [self unfiltered];
3159 _end
3160
3161 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3162 value &= [self matches:search];
3163 _end
3164
3165 return value;
3166 _end
3167 }
3168
3169 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3170 if ([search length] == 0)
3171 return false;
3172
3173 _profile(Package$isUnfilteredAndSelectedForBy)
3174 bool value(true);
3175
3176 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3177 value &= [self unfiltered];
3178 _end
3179
3180 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3181 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3182 _end
3183
3184 return value;
3185 _end
3186 }
3187
3188 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3189 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3190 }
3191
3192 - (bool) isVisibleInSection:(NSString *)name {
3193 NSString *section([self section]);
3194
3195 return (
3196 name == nil ||
3197 section == nil && [name length] == 0 ||
3198 [name isEqualToString:section]
3199 ) && [self visible];
3200 }
3201
3202 - (bool) isVisibleInSource:(Source *)source {
3203 return [self source] == source && [self visible];
3204 }
3205
3206 @end
3207 /* }}} */
3208 /* Section Class {{{ */
3209 @interface Section : NSObject {
3210 NSString *name_;
3211 unichar index_;
3212 size_t row_;
3213 size_t count_;
3214 NSString *localized_;
3215 }
3216
3217 - (NSComparisonResult) compareByLocalized:(Section *)section;
3218 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3219 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3220 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3221 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3222 - (NSString *) name;
3223 - (unichar) index;
3224
3225 - (size_t) row;
3226 - (size_t) count;
3227
3228 - (void) addToRow;
3229 - (void) addToCount;
3230
3231 - (void) setCount:(size_t)count;
3232 - (NSString *) localized;
3233
3234 @end
3235
3236 @implementation Section
3237
3238 - (void) dealloc {
3239 [name_ release];
3240 if (localized_ != nil)
3241 [localized_ release];
3242 [super dealloc];
3243 }
3244
3245 - (NSComparisonResult) compareByLocalized:(Section *)section {
3246 NSString *lhs(localized_);
3247 NSString *rhs([section localized]);
3248
3249 /*if ([lhs length] != 0 && [rhs length] != 0) {
3250 unichar lhc = [lhs characterAtIndex:0];
3251 unichar rhc = [rhs characterAtIndex:0];
3252
3253 if (isalpha(lhc) && !isalpha(rhc))
3254 return NSOrderedAscending;
3255 else if (!isalpha(lhc) && isalpha(rhc))
3256 return NSOrderedDescending;
3257 }*/
3258
3259 return [lhs compare:rhs options:LaxCompareOptions_];
3260 }
3261
3262 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3263 if ((self = [self initWithName:name localize:NO]) != nil) {
3264 if (localized != nil)
3265 localized_ = [localized retain];
3266 } return self;
3267 }
3268
3269 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3270 return [self initWithName:name row:0 localize:localize];
3271 }
3272
3273 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3274 if ((self = [super init]) != nil) {
3275 name_ = [name retain];
3276 index_ = '\0';
3277 row_ = row;
3278 if (localize)
3279 localized_ = [LocalizeSection(name_) retain];
3280 } return self;
3281 }
3282
3283 /* XXX: localize the index thingees */
3284 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3285 if ((self = [super init]) != nil) {
3286 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3287 index_ = index;
3288 row_ = row;
3289 } return self;
3290 }
3291
3292 - (NSString *) name {
3293 return name_;
3294 }
3295
3296 - (unichar) index {
3297 return index_;
3298 }
3299
3300 - (size_t) row {
3301 return row_;
3302 }
3303
3304 - (size_t) count {
3305 return count_;
3306 }
3307
3308 - (void) addToRow {
3309 ++row_;
3310 }
3311
3312 - (void) addToCount {
3313 ++count_;
3314 }
3315
3316 - (void) setCount:(size_t)count {
3317 count_ = count;
3318 }
3319
3320 - (NSString *) localized {
3321 return localized_;
3322 }
3323
3324 @end
3325 /* }}} */
3326
3327 static NSString *Colon_;
3328 static NSString *Elision_;
3329 static NSString *Error_;
3330 static NSString *Warning_;
3331
3332 /* Database Implementation {{{ */
3333 @implementation Database
3334
3335 + (Database *) sharedInstance {
3336 static Database *instance;
3337 if (instance == nil)
3338 instance = [[Database alloc] init];
3339 return instance;
3340 }
3341
3342 - (unsigned) era {
3343 return era_;
3344 }
3345
3346 - (void) releasePackages {
3347 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3348 CFArrayRemoveAllValues(packages_);
3349 }
3350
3351 - (void) dealloc {
3352 // XXX: actually implement this thing
3353 _assert(false);
3354 [sourceList_ release];
3355 [self releasePackages];
3356 apr_pool_destroy(pool_);
3357 NSRecycleZone(zone_);
3358 [super dealloc];
3359 }
3360
3361 - (void) _readCydia:(NSNumber *)fd { _pooled
3362 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3363 std::istream is(&ib);
3364 std::string line;
3365
3366 static Pcre finish_r("^finish:([^:]*)$");
3367
3368 while (std::getline(is, line)) {
3369 const char *data(line.c_str());
3370 size_t size = line.size();
3371 lprintf("C:%s\n", data);
3372
3373 if (finish_r(data, size)) {
3374 NSString *finish = finish_r[1];
3375 int index = [Finishes_ indexOfObject:finish];
3376 if (index != INT_MAX && index > Finish_)
3377 Finish_ = index;
3378 }
3379 }
3380
3381 _assume(false);
3382 }
3383
3384 - (void) _readStatus:(NSNumber *)fd { _pooled
3385 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3386 std::istream is(&ib);
3387 std::string line;
3388
3389 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3390 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3391
3392 while (std::getline(is, line)) {
3393 const char *data(line.c_str());
3394 size_t size(line.size());
3395 lprintf("S:%s\n", data);
3396
3397 if (conffile_r(data, size)) {
3398 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3399 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3400 } else if (strncmp(data, "status: ", 8) == 0) {
3401 // status: <package>: {unpacked,half-configured,installed}
3402 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3403 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3404 } else if (strncmp(data, "processing: ", 12) == 0) {
3405 // processing: configure: config-test
3406 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3407 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3408 } else if (pmstatus_r(data, size)) {
3409 std::string type([pmstatus_r[1] UTF8String]);
3410
3411 NSString *package = pmstatus_r[2];
3412 if ([package isEqualToString:@"dpkg-exec"])
3413 package = nil;
3414
3415 float percent([pmstatus_r[3] floatValue]);
3416 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3417
3418 NSString *string = pmstatus_r[4];
3419
3420 if (type == "pmerror") {
3421 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3422 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3423 } else if (type == "pmstatus") {
3424 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3425 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3426 } else if (type == "pmconffile")
3427 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3428 else
3429 lprintf("E:unknown pmstatus\n");
3430 } else
3431 lprintf("E:unknown status\n");
3432 }
3433
3434 _assume(false);
3435 }
3436
3437 - (void) _readOutput:(NSNumber *)fd { _pooled
3438 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3439 std::istream is(&ib);
3440 std::string line;
3441
3442 while (std::getline(is, line)) {
3443 lprintf("O:%s\n", line.c_str());
3444
3445 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3446 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3447 }
3448
3449 _assume(false);
3450 }
3451
3452 - (FILE *) input {
3453 return input_;
3454 }
3455
3456 - (Package *) packageWithName:(NSString *)name {
3457 @synchronized (self) {
3458 if (static_cast<pkgDepCache *>(cache_) == NULL)
3459 return nil;
3460 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3461 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3462 } }
3463
3464 - (id) init {
3465 if ((self = [super init]) != nil) {
3466 policy_ = NULL;
3467 records_ = NULL;
3468 resolver_ = NULL;
3469 fetcher_ = NULL;
3470 lock_ = NULL;
3471
3472 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3473 apr_pool_create(&pool_, NULL);
3474
3475 size_t capacity(MetaFile_->active_);
3476 if (capacity == 0)
3477 capacity = 16384;
3478 else
3479 capacity += 1024;
3480
3481 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3482 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3483
3484 int fds[2];
3485
3486 _assert(pipe(fds) != -1);
3487 cydiafd_ = fds[1];
3488
3489 _config->Set("APT::Keep-Fds::", cydiafd_);
3490 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3491
3492 [NSThread
3493 detachNewThreadSelector:@selector(_readCydia:)
3494 toTarget:self
3495 withObject:[NSNumber numberWithInt:fds[0]]
3496 ];
3497
3498 _assert(pipe(fds) != -1);
3499 statusfd_ = fds[1];
3500
3501 [NSThread
3502 detachNewThreadSelector:@selector(_readStatus:)
3503 toTarget:self
3504 withObject:[NSNumber numberWithInt:fds[0]]
3505 ];
3506
3507 _assert(pipe(fds) != -1);
3508 _assert(dup2(fds[0], 0) != -1);
3509 _assert(close(fds[0]) != -1);
3510
3511 input_ = fdopen(fds[1], "a");
3512
3513 _assert(pipe(fds) != -1);
3514 _assert(dup2(fds[1], 1) != -1);
3515 _assert(close(fds[1]) != -1);
3516
3517 [NSThread
3518 detachNewThreadSelector:@selector(_readOutput:)
3519 toTarget:self
3520 withObject:[NSNumber numberWithInt:fds[0]]
3521 ];
3522 } return self;
3523 }
3524
3525 - (pkgCacheFile &) cache {
3526 return cache_;
3527 }
3528
3529 - (pkgDepCache::Policy *) policy {
3530 return policy_;
3531 }
3532
3533 - (pkgRecords *) records {
3534 return records_;
3535 }
3536
3537 - (pkgProblemResolver *) resolver {
3538 return resolver_;
3539 }
3540
3541 - (pkgAcquire &) fetcher {
3542 return *fetcher_;
3543 }
3544
3545 - (pkgSourceList &) list {
3546 return *list_;
3547 }
3548
3549 - (NSArray *) packages {
3550 return (NSArray *) packages_;
3551 }
3552
3553 - (NSArray *) sources {
3554 return sourceList_;
3555 }
3556
3557 - (Source *) sourceWithKey:(NSString *)key {
3558 for (Source *source in [self sources]) {
3559 if ([[source key] isEqualToString:key])
3560 return source;
3561 } return nil;
3562 }
3563
3564 - (bool) popErrorWithTitle:(NSString *)title {
3565 bool fatal(false);
3566
3567 while (!_error->empty()) {
3568 std::string error;
3569 bool warning(!_error->PopMessage(error));
3570 if (!warning)
3571 fatal = true;
3572
3573 for (;;) {
3574 size_t size(error.size());
3575 if (size == 0 || error[size - 1] != '\n')
3576 break;
3577 error.resize(size - 1);
3578 }
3579
3580 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3581
3582 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3583 }
3584
3585 return fatal;
3586 }
3587
3588 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3589 return [self popErrorWithTitle:title] || !success;
3590 }
3591
3592 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3593 @synchronized (self) {
3594 ++era_;
3595
3596 [self releasePackages];
3597
3598 sourceMap_.clear();
3599 [sourceList_ removeAllObjects];
3600
3601 _error->Discard();
3602
3603 delete list_;
3604 list_ = NULL;
3605 manager_ = NULL;
3606 delete lock_;
3607 lock_ = NULL;
3608 delete fetcher_;
3609 fetcher_ = NULL;
3610 delete resolver_;
3611 resolver_ = NULL;
3612 delete records_;
3613 records_ = NULL;
3614 delete policy_;
3615 policy_ = NULL;
3616
3617 cache_.Close();
3618
3619 apr_pool_clear(pool_);
3620
3621 NSRecycleZone(zone_);
3622 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3623
3624 int chk(creat("/tmp/cydia.chk", 0644));
3625 if (chk != -1)
3626 close(chk);
3627
3628 if (invocation != nil)
3629 [invocation invoke];
3630
3631 NSString *title(UCLocalize("DATABASE"));
3632
3633 _trace();
3634 OpProgress progress;
3635 while (!cache_.Open(progress, true)) { pop:
3636 std::string error;
3637 bool warning(!_error->PopMessage(error));
3638 lprintf("cache_.Open():[%s]\n", error.c_str());
3639
3640 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3641 [delegate_ repairWithSelector:@selector(configure)];
3642 else if (error == "The package lists or status file could not be parsed or opened.")
3643 [delegate_ repairWithSelector:@selector(update)];
3644 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3645 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3646 // else if (error == "Malformed Status line")
3647 // else if (error == "The list of sources could not be read.")
3648 else {
3649 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3650 return;
3651 }
3652
3653 if (warning)
3654 goto pop;
3655 _error->Discard();
3656 }
3657 _trace();
3658
3659 unlink("/tmp/cydia.chk");
3660
3661 now_ = [[NSDate date] timeIntervalSince1970];
3662
3663 policy_ = new pkgDepCache::Policy();
3664 records_ = new pkgRecords(cache_);
3665 resolver_ = new pkgProblemResolver(cache_);
3666 fetcher_ = new pkgAcquire(&status_);
3667 lock_ = NULL;
3668
3669 list_ = new pkgSourceList();
3670 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3671 return;
3672
3673 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3674 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3675 return;
3676 }
3677
3678 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3679 return;
3680
3681 if (cache_->BrokenCount() != 0) {
3682 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3683 return;
3684
3685 if (cache_->BrokenCount() != 0) {
3686 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3687 return;
3688 }
3689
3690 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3691 return;
3692 }
3693
3694 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3695 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3696 [sourceList_ addObject:object];
3697
3698 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3699 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3700 // XXX: this could be more intelligent
3701 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3702 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3703 if (!cached.end())
3704 sourceMap_[cached->ID] = object;
3705 }
3706 }
3707
3708 {
3709 /*std::vector<Package *> packages;
3710 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3711 [packages_ release];
3712 packages_ = nil;*/
3713
3714 _trace();
3715
3716 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3717 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3718 //packages.push_back(package);
3719 CFArrayAppendValue(packages_, [package retain]);
3720
3721 _trace();
3722
3723 /*if (packages.empty())
3724 packages_ = [[NSArray alloc] init];
3725 else
3726 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3727 _trace();*/
3728
3729 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3730 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3731 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3732
3733 /*_trace();
3734 PrintTimes();
3735 _trace();*/
3736
3737 _trace();
3738
3739 /*if (!packages.empty())
3740 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3741 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3742
3743 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3744
3745 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3746
3747 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3748
3749 _trace();
3750
3751 size_t count(CFArrayGetCount(packages_));
3752 MetaFile_->active_ = count;
3753
3754 for (size_t index(0); index != count; ++index)
3755 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3756
3757 _trace();
3758 }
3759 } } CYPoolEnd() _trace(); }
3760
3761 - (void) clear {
3762 @synchronized (self) {
3763 delete resolver_;
3764 resolver_ = new pkgProblemResolver(cache_);
3765
3766 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3767 if (!cache_[iterator].Keep())
3768 cache_->MarkKeep(iterator, false);
3769 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3770 cache_->SetReInstall(iterator, false);
3771 } }
3772
3773 - (void) configure {
3774 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3775 _trace();
3776 system([dpkg UTF8String]);
3777 _trace();
3778 }
3779
3780 - (bool) clean {
3781 // XXX: I don't remember this condition
3782 if (lock_ != NULL)
3783 return false;
3784
3785 FileFd Lock;
3786 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3787
3788 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3789
3790 if ([self popErrorWithTitle:title])
3791 return false;
3792
3793 pkgAcquire fetcher;
3794 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3795
3796 class LogCleaner :
3797 public pkgArchiveCleaner
3798 {
3799 protected:
3800 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3801 unlink(File);
3802 }
3803 } cleaner;
3804
3805 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3806 return false;
3807
3808 return true;
3809 }
3810
3811 - (bool) prepare {
3812 fetcher_->Shutdown();
3813
3814 pkgRecords records(cache_);
3815
3816 lock_ = new FileFd();
3817 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3818
3819 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3820
3821 if ([self popErrorWithTitle:title])
3822 return false;
3823
3824 pkgSourceList list;
3825 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3826 return false;
3827
3828 manager_ = (_system->CreatePM(cache_));
3829 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3830 return false;
3831
3832 return true;
3833 }
3834
3835 - (void) perform {
3836 bool substrate(RestartSubstrate_);
3837 RestartSubstrate_ = false;
3838
3839 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3840
3841 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3842 pkgSourceList list;
3843 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3844 return;
3845 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3846 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3847 }
3848
3849 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3850
3851 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3852 _trace();
3853 [self popErrorWithTitle:title];
3854 return;
3855 }
3856
3857 bool failed = false;
3858 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3859 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3860 continue;
3861 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3862 continue;
3863
3864 failed = true;
3865 }
3866
3867 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3868
3869 if (failed) {
3870 _trace();
3871 return;
3872 }
3873
3874 if (substrate)
3875 RestartSubstrate_ = true;
3876
3877 _system->UnLock();
3878 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3879
3880 if (_error->PendingError()) {
3881 _trace();
3882 return;
3883 }
3884
3885 if (result == pkgPackageManager::Failed) {
3886 _trace();
3887 return;
3888 }
3889
3890 if (result != pkgPackageManager::Completed) {
3891 _trace();
3892 return;
3893 }
3894
3895 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3896 pkgSourceList list;
3897 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3898 return;
3899 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3900 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3901 }
3902
3903 if (![before isEqualToArray:after])
3904 [self update];
3905 }
3906
3907 - (bool) upgrade {
3908 NSString *title(UCLocalize("UPGRADE"));
3909 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3910 return false;
3911 return true;
3912 }
3913
3914 - (void) update {
3915 [self updateWithStatus:status_];
3916 }
3917
3918 - (void) updateWithStatus:(Status &)status {
3919 NSString *title(UCLocalize("REFRESHING_DATA"));
3920
3921 pkgSourceList list;
3922 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3923 return;
3924
3925 FileFd lock;
3926 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3927 if ([self popErrorWithTitle:title])
3928 return;
3929
3930 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3931
3932 bool success(ListUpdate(status, list, PulseInterval_));
3933 if (status.WasCancelled())
3934 _error->Discard();
3935 else
3936 [self popErrorWithTitle:title forOperation:success];
3937
3938 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3939
3940 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3941 Changed_ = true;
3942 }
3943
3944 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3945 delegate_ = delegate;
3946 }
3947
3948 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3949 progress_ = delegate;
3950 status_.setDelegate(delegate);
3951 }
3952
3953 - (NSObject<ProgressDelegate> *) progressDelegate {
3954 return progress_;
3955 }
3956
3957 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3958 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3959 return i == sourceMap_.end() ? nil : i->second;
3960 }
3961
3962 - (NSString *) mappedSectionForPointer:(const char *)section {
3963 _H<NSString> *mapped;
3964
3965 _profile(Database$mappedSectionForPointer$Cache)
3966 mapped = &sections_[section];
3967 _end
3968
3969 if (*mapped == NULL) {
3970 size_t length(strlen(section));
3971 char spaced[length + 1];
3972
3973 _profile(Database$mappedSectionForPointer$Replace)
3974 for (size_t index(0); index != length; ++index)
3975 spaced[index] = section[index] == '_' ? ' ' : section[index];
3976 spaced[length] = '\0';
3977 _end
3978
3979 NSString *string;
3980
3981 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3982 string = [NSString stringWithUTF8String:spaced];
3983 _end
3984
3985 _profile(Database$mappedSectionForPointer$Map)
3986 string = [SectionMap_ objectForKey:string] ?: string;
3987 _end
3988
3989 *mapped = string;
3990 } return *mapped;
3991 }
3992
3993 @end
3994 /* }}} */
3995
3996 static NSMutableSet *Diversions_;
3997
3998 @interface Diversion : NSObject {
3999 Pcre pattern_;
4000 _H<NSString> key_;
4001 _H<NSString> format_;
4002 }
4003
4004 @end
4005
4006 @implementation Diversion
4007
4008 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4009 if ((self = [super init]) != nil) {
4010 pattern_ = [from UTF8String];
4011 key_ = from;
4012 format_ = to;
4013 } return self;
4014 }
4015
4016 - (NSString *) divert:(NSString *)url {
4017 return !pattern_(url) ? nil : pattern_->*format_;
4018 }
4019
4020 + (NSURL *) divertURL:(NSURL *)url {
4021 divert:
4022 NSString *href([url absoluteString]);
4023
4024 for (Diversion *diversion in Diversions_)
4025 if (NSString *diverted = [diversion divert:href]) {
4026 url = [NSURL URLWithString:diverted];
4027 goto divert;
4028 }
4029
4030 return url;
4031 }
4032
4033 - (NSString *) key {
4034 return key_;
4035 }
4036
4037 - (NSUInteger) hash {
4038 return [key_ hash];
4039 }
4040
4041 - (BOOL) isEqual:(Diversion *)object {
4042 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4043 }
4044
4045 @end
4046
4047 @interface CydiaObject : NSObject {
4048 id indirect_;
4049 _transient id delegate_;
4050 }
4051
4052 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4053
4054 @end
4055
4056 @interface CYBrowserController : BrowserController {
4057 CydiaObject *cydia_;
4058 }
4059
4060 + (void) addDiversion:(Diversion *)diversion;
4061
4062 @end
4063
4064 /* Web Scripting {{{ */
4065 @implementation CydiaObject
4066
4067 - (void) dealloc {
4068 [indirect_ release];
4069 [super dealloc];
4070 }
4071
4072 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4073 if ((self = [super init]) != nil) {
4074 indirect_ = [indirect retain];
4075 } return self;
4076 }
4077
4078 - (void) setDelegate:(id)delegate {
4079 delegate_ = delegate;
4080 }
4081
4082 + (NSArray *) _attributeKeys {
4083 return [NSArray arrayWithObjects:
4084 @"device",
4085 @"ecid",
4086 @"firmware",
4087 @"hostname",
4088 @"idiom",
4089 @"model",
4090 @"plmn",
4091 @"role",
4092 @"serial",
4093 @"token",
4094 @"version",
4095 nil];
4096 }
4097
4098 - (NSArray *) attributeKeys {
4099 return [[self class] _attributeKeys];
4100 }
4101
4102 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4103 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4104 }
4105
4106 - (NSString *) version {
4107 return @ Cydia_;
4108 }
4109
4110 - (NSString *) device {
4111 return [[UIDevice currentDevice] uniqueIdentifier];
4112 }
4113
4114 - (NSString *) firmware {
4115 return [[UIDevice currentDevice] systemVersion];
4116 }
4117
4118 - (NSString *) hostname {
4119 return [[UIDevice currentDevice] name];
4120 }
4121
4122 - (NSString *) idiom {
4123 return (id) Idiom_ ?: [NSNull null];
4124 }
4125
4126 - (NSString *) plmn {
4127 return (id) PLMN_ ?: [NSNull null];
4128 }
4129
4130 - (NSString *) ecid {
4131 return (id) ChipID_ ?: [NSNull null];
4132 }
4133
4134 - (NSString *) serial {
4135 return SerialNumber_;
4136 }
4137
4138 - (NSString *) role {
4139 return (id) Role_ ?: [NSNull null];
4140 }
4141
4142 - (NSString *) model {
4143 return [NSString stringWithUTF8String:Machine_];
4144 }
4145
4146 - (NSString *) token {
4147 return (id) Token_ ?: [NSNull null];
4148 }
4149
4150 + (NSString *) webScriptNameForSelector:(SEL)selector {
4151 if (false);
4152 else if (selector == @selector(addBridgedHost:))
4153 return @"addBridgedHost";
4154 else if (selector == @selector(addPipelinedHost:scheme:))
4155 return @"addPipelinedHost";
4156 else if (selector == @selector(addTrivialSource:))
4157 return @"addTrivialSource";
4158 else if (selector == @selector(close))
4159 return @"close";
4160 else if (selector == @selector(divert::))
4161 return @"divert";
4162 else if (selector == @selector(du:))
4163 return @"du";
4164 else if (selector == @selector(stringWithFormat:arguments:))
4165 return @"format";
4166 else if (selector == @selector(getAllSources))
4167 return @"getAllSourcs";
4168 else if (selector == @selector(getKernelNumber:))
4169 return @"getKernelNumber";
4170 else if (selector == @selector(getKernelString:))
4171 return @"getKernelString";
4172 else if (selector == @selector(getInstalledPackages))
4173 return @"getInstalledPackages";
4174 else if (selector == @selector(getPackageById:))
4175 return @"getPackageById";
4176 else if (selector == @selector(getSessionValue:))
4177 return @"getSessionValue";
4178 else if (selector == @selector(installPackages:))
4179 return @"installPackages";
4180 else if (selector == @selector(localizedStringForKey:value:table:))
4181 return @"localize";
4182 else if (selector == @selector(popViewController:))
4183 return @"popViewController";
4184 else if (selector == @selector(refreshSources))
4185 return @"refreshSources";
4186 else if (selector == @selector(removeButton))
4187 return @"removeButton";
4188 else if (selector == @selector(setSessionValue::))
4189 return @"setSessionValue";
4190 else if (selector == @selector(substitutePackageNames:))
4191 return @"substitutePackageNames";
4192 else if (selector == @selector(scrollToBottom:))
4193 return @"scrollToBottom";
4194 else if (selector == @selector(setAllowsNavigationAction:))
4195 return @"setAllowsNavigationAction";
4196 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4197 return @"setButtonImage";
4198 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4199 return @"setButtonTitle";
4200 else if (selector == @selector(setHidesBackButton:))
4201 return @"setHidesBackButton";
4202 else if (selector == @selector(setHidesNavigationBar:))
4203 return @"setHidesNavigationBar";
4204 else if (selector == @selector(setNavigationBarStyle:))
4205 return @"setNavigationBarStyle";
4206 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4207 return @"setNavigationBarTintColor";
4208 else if (selector == @selector(setToken:))
4209 return @"setToken";
4210 else if (selector == @selector(setViewportWidth:))
4211 return @"setViewportWidth";
4212 else if (selector == @selector(statfs:))
4213 return @"statfs";
4214 else if (selector == @selector(supports:))
4215 return @"supports";
4216 else
4217 return nil;
4218 }
4219
4220 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4221 return [self webScriptNameForSelector:selector] == nil;
4222 }
4223
4224 - (BOOL) supports:(NSString *)feature {
4225 return [feature isEqualToString:@"window.open"];
4226 }
4227
4228 - (void) divert:(NSString *)from :(NSString *)to {
4229 [CYBrowserController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4230 }
4231
4232 - (NSNumber *) getKernelNumber:(NSString *)name {
4233 const char *string([name UTF8String]);
4234
4235 size_t size;
4236 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4237 return (id) [NSNull null];
4238
4239 if (size != sizeof(int))
4240 return (id) [NSNull null];
4241
4242 int value;
4243 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4244 return (id) [NSNull null];
4245
4246 return [NSNumber numberWithInt:value];
4247 }
4248
4249 - (NSString *) getKernelString:(NSString *)name {
4250 const char *string([name UTF8String]);
4251
4252 size_t size;
4253 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4254 return (id) [NSNull null];
4255
4256 char value[size + 1];
4257 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4258 return (id) [NSNull null];
4259
4260 // XXX: just in case you request something ludicrous
4261 value[size] = '\0';
4262
4263 return [NSString stringWithCString:value];
4264 }
4265
4266 - (id) getSessionValue:(NSString *)key {
4267 @synchronized (SessionData_) {
4268 return [SessionData_ objectForKey:key];
4269 } }
4270
4271 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4272 @synchronized (SessionData_) {
4273 if (value == (id) [WebUndefined undefined])
4274 [SessionData_ removeObjectForKey:key];
4275 else
4276 [SessionData_ setObject:value forKey:key];
4277 } }
4278
4279 - (void) addBridgedHost:(NSString *)host {
4280 @synchronized (HostConfig_) {
4281 [BridgedHosts_ addObject:host];
4282 } }
4283
4284 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4285 @synchronized (HostConfig_) {
4286 if (scheme != (id) [WebUndefined undefined])
4287 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4288
4289 [PipelinedHosts_ addObject:host];
4290 } }
4291
4292 - (void) popViewController:(NSNumber *)value {
4293 if (value == (id) [WebUndefined undefined])
4294 value = [NSNumber numberWithBool:YES];
4295 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4296 }
4297
4298 - (void) addTrivialSource:(NSString *)href {
4299 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4300 }
4301
4302 - (void) refreshSources {
4303 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4304 }
4305
4306 - (NSArray *) getAllSources {
4307 return [[Database sharedInstance] sources];
4308 }
4309
4310 - (NSArray *) getInstalledPackages {
4311 Database *database([Database sharedInstance]);
4312 @synchronized (database) {
4313 NSArray *packages([database packages]);
4314 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4315 for (Package *package in packages)
4316 if (![package uninstalled])
4317 [installed addObject:package];
4318 return installed;
4319 } }
4320
4321 - (Package *) getPackageById:(NSString *)id {
4322 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4323 [package parse];
4324 return package;
4325 } else
4326 return (Package *) [NSNull null];
4327 }
4328
4329 - (NSArray *) statfs:(NSString *)path {
4330 struct statfs stat;
4331
4332 if (path == nil || statfs([path UTF8String], &stat) == -1)
4333 return nil;
4334
4335 return [NSArray arrayWithObjects:
4336 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4337 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4338 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4339 nil];
4340 }
4341
4342 - (NSNumber *) du:(NSString *)path {
4343 NSNumber *value(nil);
4344
4345 int fds[2];
4346 _assert(pipe(fds) != -1);
4347
4348 pid_t pid(ExecFork());
4349 if (pid == 0) {
4350 _assert(dup2(fds[1], 1) != -1);
4351 _assert(close(fds[0]) != -1);
4352 _assert(close(fds[1]) != -1);
4353 /* XXX: this should probably not use du */
4354 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4355 exit(1);
4356 _assert(false);
4357 }
4358
4359 _assert(close(fds[1]) != -1);
4360
4361 if (FILE *du = fdopen(fds[0], "r")) {
4362 char line[1024];
4363 while (fgets(line, sizeof(line), du) != NULL) {
4364 size_t length(strlen(line));
4365 while (length != 0 && line[length - 1] == '\n')
4366 line[--length] = '\0';
4367 if (char *tab = strchr(line, '\t')) {
4368 *tab = '\0';
4369 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4370 }
4371 }
4372
4373 fclose(du);
4374 } else _assert(close(fds[0]));
4375
4376 int status;
4377 wait:
4378 if (waitpid(pid, &status, 0) == -1)
4379 if (errno == EINTR)
4380 goto wait;
4381 else _assert(false);
4382
4383 return value;
4384 }
4385
4386 - (void) close {
4387 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4388 }
4389
4390 - (void) installPackages:(NSArray *)packages {
4391 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4392 }
4393
4394 - (NSString *) substitutePackageNames:(NSString *)message {
4395 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4396 for (size_t i(0), e([words count]); i != e; ++i) {
4397 NSString *word([words objectAtIndex:i]);
4398 if (Package *package = [[Database sharedInstance] packageWithName:word])
4399 [words replaceObjectAtIndex:i withObject:[package name]];
4400 }
4401
4402 return [words componentsJoinedByString:@" "];
4403 }
4404
4405 - (void) removeButton {
4406 [indirect_ removeButton];
4407 }
4408
4409 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4410 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4411 }
4412
4413 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4414 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4415 }
4416
4417 - (void) setAllowsNavigationAction:(NSString *)value {
4418 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4419 }
4420
4421 - (void) setHidesBackButton:(NSString *)value {
4422 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4423 }
4424
4425 - (void) setHidesNavigationBar:(NSString *)value {
4426 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4427 }
4428
4429 - (void) setNavigationBarStyle:(NSString *)value {
4430 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4431 }
4432
4433 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4434 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4435 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4436 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4437 }
4438
4439 - (void) _setToken:(NSString *)token {
4440 Token_ = token;
4441
4442 if (token == nil)
4443 [Metadata_ removeObjectForKey:@"Token"];
4444 else
4445 [Metadata_ setObject:Token_ forKey:@"Token"];
4446
4447 Changed_ = true;
4448 }
4449
4450 - (void) setToken:(NSString *)token {
4451 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4452 }
4453
4454 - (void) scrollToBottom:(NSNumber *)animated {
4455 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4456 }
4457
4458 - (void) setViewportWidth:(float)width {
4459 [indirect_ setViewportWidthOnMainThread:width];
4460 }
4461
4462 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4463 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4464 unsigned count([arguments count]);
4465 id values[count];
4466 for (unsigned i(0); i != count; ++i)
4467 values[i] = [arguments objectAtIndex:i];
4468 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4469 }
4470
4471 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4472 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4473 value = nil;
4474 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4475 table = nil;
4476 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4477 }
4478
4479 @end
4480 /* }}} */
4481
4482 /* @ Loading... Indicator {{{ */
4483 @interface CYLoadingIndicator : UIView {
4484 _H<UIActivityIndicatorView> spinner_;
4485 _H<UILabel> label_;
4486 _H<UIView> container_;
4487 }
4488
4489 @property (readonly, nonatomic) UILabel *label;
4490 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4491
4492 @end
4493
4494 @implementation CYLoadingIndicator
4495
4496 - (id) initWithFrame:(CGRect)frame {
4497 if ((self = [super initWithFrame:frame]) != nil) {
4498 container_ = [[[UIView alloc] init] autorelease];
4499 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4500
4501 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4502 [spinner_ startAnimating];
4503 [container_ addSubview:spinner_];
4504
4505 label_ = [[[UILabel alloc] init] autorelease];
4506 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4507 [label_ setBackgroundColor:[UIColor clearColor]];
4508 [label_ setTextColor:[UIColor blackColor]];
4509 [label_ setShadowColor:[UIColor whiteColor]];
4510 [label_ setShadowOffset:CGSizeMake(0, 1)];
4511 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4512 [container_ addSubview:label_];
4513
4514 CGSize viewsize = frame.size;
4515 CGSize spinnersize = [spinner_ bounds].size;
4516 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4517 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4518
4519 CGRect containrect = {
4520 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4521 CGSizeMake(bothwidth, spinnersize.height)
4522 };
4523 CGRect textrect = {
4524 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4525 textsize
4526 };
4527 CGRect spinrect = {
4528 CGPointZero,
4529 spinnersize
4530 };
4531
4532 [container_ setFrame:containrect];
4533 [spinner_ setFrame:spinrect];
4534 [label_ setFrame:textrect];
4535 [self addSubview:container_];
4536 } return self;
4537 }
4538
4539 - (UILabel *) label {
4540 return label_;
4541 }
4542
4543 - (UIActivityIndicatorView *) activityIndicatorView {
4544 return spinner_;
4545 }
4546
4547 @end
4548 /* }}} */
4549 /* Emulated Loading Controller {{{ */
4550 @interface CYEmulatedLoadingController : CYViewController {
4551 _transient Database *database_;
4552 _H<CYLoadingIndicator> indicator_;
4553 _H<UITabBar> tabbar_;
4554 _H<UINavigationBar> navbar_;
4555 }
4556
4557 @end
4558
4559 @implementation CYEmulatedLoadingController
4560
4561 - (id) initWithDatabase:(Database *)database {
4562 if ((self = [super init]) != nil) {
4563 database_ = database;
4564 } return self;
4565 }
4566
4567 - (void) loadView {
4568 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4569
4570 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4571 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4572 [[self view] addSubview:table];
4573
4574 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4575 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4576 [[self view] addSubview:indicator_];
4577
4578 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4579 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4580 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4581 [[self view] addSubview:tabbar_];
4582
4583 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4584 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4585 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4586 [[self view] addSubview:navbar_];
4587 }
4588
4589 - (void) releaseSubviews {
4590 indicator_ = nil;
4591 tabbar_ = nil;
4592 navbar_ = nil;
4593 }
4594
4595 @end
4596 /* }}} */
4597
4598 /* Cydia Browser Controller {{{ */
4599 @implementation CYBrowserController
4600
4601 - (void) dealloc {
4602 [cydia_ release];
4603 [super dealloc];
4604 }
4605
4606 - (NSURL *) navigationURL {
4607 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4608 }
4609
4610 + (void) initialize {
4611 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4612 }
4613
4614 + (void) addDiversion:(Diversion *)diversion {
4615 [Diversions_ addObject:diversion];
4616 }
4617
4618 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4619 [super webView:view didClearWindowObject:window forFrame:frame];
4620
4621 WebDataSource *source([frame dataSource]);
4622 NSURLResponse *response([source response]);
4623 NSURL *url([response URL]);
4624 NSString *scheme([[url scheme] lowercaseString]);
4625
4626 bool bridged(false);
4627
4628 @synchronized (HostConfig_) {
4629 if ([scheme isEqualToString:@"file"])
4630 bridged = true;
4631 else if ([scheme isEqualToString:@"https"])
4632 if ([BridgedHosts_ containsObject:[url host]])
4633 bridged = true;
4634 }
4635
4636 if (bridged)
4637 [window setValue:cydia_ forKey:@"cydia"];
4638 }
4639
4640 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4641 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4642
4643 [copy setURL:[Diversion divertURL:[copy URL]]];
4644
4645 if (System_ != NULL)
4646 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4647 if (Machine_ != NULL)
4648 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4649 if (Token_ != nil)
4650 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4651
4652 return copy;
4653 }
4654
4655 - (void) setDelegate:(id)delegate {
4656 [super setDelegate:delegate];
4657 [cydia_ setDelegate:delegate];
4658 }
4659
4660 - (id) init {
4661 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4662 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4663
4664 WebView *webview([[webview_ _documentView] webView]);
4665
4666 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4667
4668 if (Safari_ != nil)
4669 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4670 if (Build_ != nil)
4671 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4672 if (Product_ != nil)
4673 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4674
4675 [webview setApplicationNameForUserAgent:application];
4676 } return self;
4677 }
4678
4679 @end
4680 /* }}} */
4681
4682 // CydiaScript {{{
4683 @interface NSObject (CydiaScript)
4684 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4685 @end
4686
4687 @implementation NSObject (CydiaScript)
4688
4689 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4690 return self;
4691 }
4692
4693 @end
4694
4695 @implementation NSArray (CydiaScript)
4696
4697 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4698 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4699 for (size_t i(0), e([self count]); i != e; ++i)
4700 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4701 return object;
4702 }
4703
4704 @end
4705
4706 @implementation NSDictionary (CydiaScript)
4707
4708 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4709 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4710 for (id i in self)
4711 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4712 return object;
4713 }
4714
4715 @end
4716 // }}}
4717
4718 /* Confirmation Controller {{{ */
4719 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4720 if (!iterator.end())
4721 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4722 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4723 continue;
4724 pkgCache::PkgIterator package(dep.TargetPkg());
4725 if (package.end())
4726 continue;
4727 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4728 return true;
4729 }
4730
4731 return false;
4732 }
4733
4734 @protocol ConfirmationControllerDelegate
4735 - (void) cancelAndClear:(bool)clear;
4736 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4737 - (void) queue;
4738 @end
4739
4740 @interface ConfirmationController : CYBrowserController {
4741 _transient Database *database_;
4742
4743 UIAlertView *essential_;
4744
4745 NSDictionary *changes_;
4746 NSMutableArray *issues_;
4747 NSDictionary *sizes_;
4748
4749 BOOL substrate_;
4750 }
4751
4752 - (id) initWithDatabase:(Database *)database;
4753
4754 @end
4755
4756 @implementation ConfirmationController
4757
4758 - (void) dealloc {
4759 [changes_ release];
4760 [issues_ release];
4761 [sizes_ release];
4762
4763 if (essential_ != nil)
4764 [essential_ release];
4765
4766 [super dealloc];
4767 }
4768
4769 - (void) complete {
4770 if (substrate_)
4771 RestartSubstrate_ = true;
4772 [delegate_ confirmWithNavigationController:[self navigationController]];
4773 }
4774
4775 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4776 NSString *context([alert context]);
4777
4778 if ([context isEqualToString:@"remove"]) {
4779 if (button == [alert cancelButtonIndex])
4780 [self dismissModalViewControllerAnimated:YES];
4781 else if (button == [alert firstOtherButtonIndex]) {
4782 [self complete];
4783 }
4784
4785 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4786 } else if ([context isEqualToString:@"unable"]) {
4787 [self dismissModalViewControllerAnimated:YES];
4788 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4789 } else {
4790 [super alertView:alert clickedButtonAtIndex:button];
4791 }
4792 }
4793
4794 - (void) _doContinue {
4795 [self dismissModalViewControllerAnimated:YES];
4796 [delegate_ cancelAndClear:NO];
4797 }
4798
4799 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4800 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4801 return nil;
4802 }
4803
4804 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4805 [super webView:view didClearWindowObject:window forFrame:frame];
4806
4807 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4808 changes_, @"changes",
4809 issues_, @"issues",
4810 sizes_, @"sizes",
4811 self, @"queue",
4812 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4813 }
4814
4815 - (id) initWithDatabase:(Database *)database {
4816 if ((self = [super init]) != nil) {
4817 database_ = database;
4818
4819 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4820 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4821 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4822 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4823 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4824
4825 bool remove(false);
4826
4827 pkgCacheFile &cache([database_ cache]);
4828 NSArray *packages([database_ packages]);
4829 pkgDepCache::Policy *policy([database_ policy]);
4830
4831 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4832
4833 for (Package *package in packages) {
4834 pkgCache::PkgIterator iterator([package iterator]);
4835 NSString *name([package id]);
4836
4837 if ([package broken]) {
4838 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4839
4840 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4841 name, @"package",
4842 reasons, @"reasons",
4843 nil]];
4844
4845 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4846 if (ver.end())
4847 continue;
4848
4849 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4850 pkgCache::DepIterator start;
4851 pkgCache::DepIterator end;
4852 dep.GlobOr(start, end); // ++dep
4853
4854 if (!cache->IsImportantDep(end))
4855 continue;
4856 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4857 continue;
4858
4859 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4860
4861 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4862 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4863 clauses, @"clauses",
4864 nil]];
4865
4866 _forever {
4867 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4868
4869 pkgCache::PkgIterator target(start.TargetPkg());
4870 if (target->ProvidesList != 0)
4871 reason = @"missing";
4872 else {
4873 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4874 if (!ver.end()) {
4875 reason = @"installed";
4876 installed = [NSString stringWithUTF8String:ver.VerStr()];
4877 } else if (!cache[target].CandidateVerIter(cache).end())
4878 reason = @"uninstalled";
4879 else if (target->ProvidesList == 0)
4880 reason = @"uninstallable";
4881 else
4882 reason = @"virtual";
4883 }
4884
4885 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4886 [NSString stringWithUTF8String:start.CompType()], @"operator",
4887 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4888 nil]);
4889
4890 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4891 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4892 version, @"version",
4893 reason, @"reason",
4894 installed, @"installed",
4895 nil]];
4896
4897 // yes, seriously. (wtf?)
4898 if (start == end)
4899 break;
4900 ++start;
4901 }
4902 }
4903 }
4904
4905 pkgDepCache::StateCache &state(cache[iterator]);
4906
4907 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4908
4909 if (state.NewInstall())
4910 [installs addObject:name];
4911 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4912 [reinstalls addObject:name];
4913 else if (state.Upgrade())
4914 [upgrades addObject:name];
4915 else if (state.Downgrade())
4916 [downgrades addObject:name];
4917 else if (!state.Delete())
4918 continue;
4919 else if (special_r(name))
4920 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4921 [NSNull null], @"package",
4922 [NSArray arrayWithObjects:
4923 [NSDictionary dictionaryWithObjectsAndKeys:
4924 @"Conflicts", @"relationship",
4925 [NSArray arrayWithObjects:
4926 [NSDictionary dictionaryWithObjectsAndKeys:
4927 name, @"package",
4928 [NSNull null], @"version",
4929 @"installed", @"reason",
4930 nil],
4931 nil], @"clauses",
4932 nil],
4933 nil], @"reasons",
4934 nil]];
4935 else {
4936 if ([package essential])
4937 remove = true;
4938 [removes addObject:name];
4939 }
4940
4941 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4942 substrate_ |= DepSubstrate(iterator.CurrentVer());
4943 }
4944
4945 if (!remove)
4946 essential_ = nil;
4947 else if (Advanced_) {
4948 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4949
4950 essential_ = [[UIAlertView alloc]
4951 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4952 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4953 delegate:self
4954 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4955 otherButtonTitles:
4956 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4957 nil
4958 ];
4959
4960 [essential_ setContext:@"remove"];
4961 } else {
4962 essential_ = [[UIAlertView alloc]
4963 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4964 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4965 delegate:self
4966 cancelButtonTitle:UCLocalize("OKAY")
4967 otherButtonTitles:nil
4968 ];
4969
4970 [essential_ setContext:@"unable"];
4971 }
4972
4973 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4974 installs, @"installs",
4975 reinstalls, @"reinstalls",
4976 upgrades, @"upgrades",
4977 downgrades, @"downgrades",
4978 removes, @"removes",
4979 nil];
4980
4981 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4982 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4983 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4984 nil];
4985
4986 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4987
4988 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4989 initWithTitle:UCLocalize("CANCEL")
4990 style:UIBarButtonItemStylePlain
4991 target:self
4992 action:@selector(cancelButtonClicked)
4993 ] autorelease]];
4994 } return self;
4995 }
4996
4997 #if !AlwaysReload
4998 - (void) applyRightButton {
4999 if ([issues_ count] == 0 && ![self isLoading])
5000 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5001 initWithTitle:UCLocalize("CONFIRM")
5002 style:UIBarButtonItemStyleDone
5003 target:self
5004 action:@selector(confirmButtonClicked)
5005 ] autorelease]];
5006 else
5007 [[self navigationItem] setRightBarButtonItem:nil];
5008 }
5009 #endif
5010
5011 - (void) cancelButtonClicked {
5012 [self dismissModalViewControllerAnimated:YES];
5013 [delegate_ cancelAndClear:YES];
5014 }
5015
5016 #if !AlwaysReload
5017 - (void) confirmButtonClicked {
5018 if (essential_ != nil)
5019 [essential_ show];
5020 else
5021 [self complete];
5022 }
5023 #endif
5024
5025 @end
5026 /* }}} */
5027
5028 /* Progress Data {{{ */
5029 @interface CydiaProgressData : NSObject {
5030 _transient id delegate_;
5031
5032 bool running_;
5033 float percent_;
5034
5035 float current_;
5036 float total_;
5037 float speed_;
5038
5039 _H<NSMutableArray> events_;
5040 _H<NSString> title_;
5041
5042 _H<NSString> status_;
5043 _H<NSString> finish_;
5044 }
5045
5046 @end
5047
5048 @implementation CydiaProgressData
5049
5050 + (NSArray *) _attributeKeys {
5051 return [NSArray arrayWithObjects:
5052 @"current",
5053 @"events",
5054 @"finish",
5055 @"percent",
5056 @"running",
5057 @"speed",
5058 @"title",
5059 @"total",
5060 nil];
5061 }
5062
5063 - (NSArray *) attributeKeys {
5064 return [[self class] _attributeKeys];
5065 }
5066
5067 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5068 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5069 }
5070
5071 - (id) init {
5072 if ((self = [super init]) != nil) {
5073 events_ = [NSMutableArray arrayWithCapacity:32];
5074 } return self;
5075 }
5076
5077 - (void) setDelegate:(id)delegate {
5078 delegate_ = delegate;
5079 }
5080
5081 - (void) setPercent:(float)value {
5082 percent_ = value;
5083 }
5084
5085 - (NSNumber *) percent {
5086 return [NSNumber numberWithFloat:percent_];
5087 }
5088
5089 - (void) setCurrent:(float)value {
5090 current_ = value;
5091 }
5092
5093 - (NSNumber *) current {
5094 return [NSNumber numberWithFloat:current_];
5095 }
5096
5097 - (void) setTotal:(float)value {
5098 total_ = value;
5099 }
5100
5101 - (NSNumber *) total {
5102 return [NSNumber numberWithFloat:total_];
5103 }
5104
5105 - (void) setSpeed:(float)value {
5106 speed_ = value;
5107 }
5108
5109 - (NSNumber *) speed {
5110 return [NSNumber numberWithFloat:speed_];
5111 }
5112
5113 - (NSArray *) events {
5114 return events_;
5115 }
5116
5117 - (void) removeAllEvents {
5118 [events_ removeAllObjects];
5119 }
5120
5121 - (void) addEvent:(CydiaProgressEvent *)event {
5122 [events_ addObject:event];
5123 }
5124
5125 - (void) setTitle:(NSString *)text {
5126 title_ = text;
5127 }
5128
5129 - (NSString *) title {
5130 return title_;
5131 }
5132
5133 - (void) setFinish:(NSString *)text {
5134 finish_ = text;
5135 }
5136
5137 - (NSString *) finish {
5138 return (id) finish_ ?: [NSNull null];
5139 }
5140
5141 - (void) setRunning:(bool)running {
5142 running_ = running;
5143 }
5144
5145 - (NSNumber *) running {
5146 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5147 }
5148
5149 @end
5150 /* }}} */
5151 /* Progress Controller {{{ */
5152 @interface ProgressController : CYBrowserController <
5153 ProgressDelegate
5154 > {
5155 _transient Database *database_;
5156 _H<CydiaProgressData> progress_;
5157 unsigned cancel_;
5158 }
5159
5160 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5161
5162 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5163
5164 - (void) setTitle:(NSString *)title;
5165 - (void) setCancellable:(bool)cancellable;
5166
5167 @end
5168
5169 @implementation ProgressController
5170
5171 - (void) dealloc {
5172 [database_ setProgressDelegate:nil];
5173 [progress_ setDelegate:nil];
5174 [super dealloc];
5175 }
5176
5177 - (void) updateCancel {
5178 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5179 initWithTitle:UCLocalize("CANCEL")
5180 style:UIBarButtonItemStylePlain
5181 target:self
5182 action:@selector(cancel)
5183 ] autorelease] : nil)];
5184 }
5185
5186 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5187 if ((self = [super init]) != nil) {
5188 database_ = database;
5189 delegate_ = delegate;
5190
5191 [database_ setProgressDelegate:self];
5192
5193 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5194 [progress_ setDelegate:self];
5195
5196 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5197
5198 [scroller_ setBackgroundColor:[UIColor blackColor]];
5199
5200 [[self navigationItem] setHidesBackButton:YES];
5201
5202 [self updateCancel];
5203 } return self;
5204 }
5205
5206 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5207 [super webView:view didClearWindowObject:window forFrame:frame];
5208 [window setValue:progress_ forKey:@"cydiaProgress"];
5209 }
5210
5211 - (void) updateProgress {
5212 [self dispatchEvent:@"CydiaProgressUpdate"];
5213 }
5214
5215 - (void) viewWillAppear:(BOOL)animated {
5216 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5217 [super viewWillAppear:animated];
5218 }
5219
5220 - (void) close {
5221 UpdateExternalStatus(0);
5222
5223 switch (Finish_) {
5224 case 0:
5225 break;
5226
5227 case 1:
5228 [delegate_ terminateWithSuccess];
5229 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5230 [delegate_ suspendWithAnimation:YES];
5231 else
5232 [delegate_ suspend];*/
5233 break;
5234
5235 case 2:
5236 _trace();
5237 goto reload;
5238
5239 case 3:
5240 _trace();
5241 goto reload;
5242
5243 reload:
5244 system("/usr/bin/sbreload");
5245 _trace();
5246 break;
5247
5248 case 4:
5249 _trace();
5250 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5251 SBReboot(SBSSpringBoardServerPort());
5252 else
5253 reboot2(RB_AUTOBOOT);
5254 break;
5255 }
5256
5257 [super close];
5258 }
5259
5260 - (void) setTitle:(NSString *)title {
5261 [progress_ setTitle:title];
5262 [self updateProgress];
5263 }
5264
5265 - (UIBarButtonItem *) rightButton {
5266 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5267 initWithTitle:UCLocalize("CLOSE")
5268 style:UIBarButtonItemStylePlain
5269 target:self
5270 action:@selector(close)
5271 ] autorelease];
5272 }
5273
5274 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5275 UpdateExternalStatus(1);
5276
5277 [progress_ setRunning:true];
5278 [self setTitle:title];
5279 // implicit updateProgress
5280
5281 SHA1SumValue notifyconf; {
5282 FileFd file;
5283 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5284 _error->Discard();
5285 else {
5286 MMap mmap(file, MMap::ReadOnly);
5287 SHA1Summation sha1;
5288 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5289 notifyconf = sha1.Result();
5290 }
5291 }
5292
5293 SHA1SumValue springlist; {
5294 FileFd file;
5295 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5296 _error->Discard();
5297 else {
5298 MMap mmap(file, MMap::ReadOnly);
5299 SHA1Summation sha1;
5300 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5301 springlist = sha1.Result();
5302 }
5303 }
5304
5305 if (invocation != nil) {
5306 [invocation yieldToSelector:@selector(invoke)];
5307 [self setTitle:@"COMPLETE"];
5308 }
5309
5310 if (Finish_ < 4) {
5311 FileFd file;
5312 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5313 _error->Discard();
5314 else {
5315 MMap mmap(file, MMap::ReadOnly);
5316 SHA1Summation sha1;
5317 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5318 if (!(notifyconf == sha1.Result()))
5319 Finish_ = 4;
5320 }
5321 }
5322
5323 if (Finish_ < 3) {
5324 FileFd file;
5325 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5326 _error->Discard();
5327 else {
5328 MMap mmap(file, MMap::ReadOnly);
5329 SHA1Summation sha1;
5330 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5331 if (!(springlist == sha1.Result()))
5332 Finish_ = 3;
5333 }
5334 }
5335
5336 if (Finish_ < 2) {
5337 if (RestartSubstrate_)
5338 Finish_ = 2;
5339 }
5340
5341 RestartSubstrate_ = false;
5342
5343 switch (Finish_) {
5344 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5345 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5346 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5347 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5348 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5349 }
5350
5351 _trace();
5352 system("su -c /usr/bin/uicache mobile");
5353 _trace();
5354
5355 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5356
5357 [progress_ setRunning:false];
5358 [self updateProgress];
5359
5360 [self applyRightButton];
5361 }
5362
5363 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5364 [progress_ addEvent:event];
5365 [self updateProgress];
5366 }
5367
5368 - (bool) isProgressCancelled {
5369 return cancel_ == 2;
5370 }
5371
5372 - (void) cancel {
5373 cancel_ = 2;
5374 [self updateCancel];
5375 }
5376
5377 - (void) setCancellable:(bool)cancellable {
5378 unsigned cancel(cancel_);
5379
5380 if (!cancellable)
5381 cancel_ = 0;
5382 else if (cancel_ == 0)
5383 cancel_ = 1;
5384
5385 if (cancel != cancel_)
5386 [self updateCancel];
5387 }
5388
5389 - (void) setProgressCancellable:(NSNumber *)cancellable {
5390 [self setCancellable:[cancellable boolValue]];
5391 }
5392
5393 - (void) setProgressPercent:(NSNumber *)percent {
5394 [progress_ setPercent:[percent floatValue]];
5395 [self updateProgress];
5396 }
5397
5398 - (void) setProgressStatus:(NSDictionary *)status {
5399 if (status == nil) {
5400 [progress_ setCurrent:0];
5401 [progress_ setTotal:0];
5402 [progress_ setSpeed:0];
5403 } else {
5404 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5405
5406 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5407 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5408 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5409 }
5410
5411 [self updateProgress];
5412 }
5413
5414 @end
5415 /* }}} */
5416
5417 /* Cell Content View {{{ */
5418 @protocol ContentDelegate
5419 - (void) drawContentRect:(CGRect)rect;
5420 @end
5421
5422 @interface ContentView : UIView {
5423 _transient id<ContentDelegate> delegate_;
5424 }
5425
5426 @end
5427
5428 @implementation ContentView
5429
5430 - (id) initWithFrame:(CGRect)frame {
5431 if ((self = [super initWithFrame:frame]) != nil) {
5432 [self setNeedsDisplayOnBoundsChange:YES];
5433 } return self;
5434 }
5435
5436 - (void) setDelegate:(id<ContentDelegate>)delegate {
5437 delegate_ = delegate;
5438 }
5439
5440 - (void) drawRect:(CGRect)rect {
5441 [super drawRect:rect];
5442 [delegate_ drawContentRect:rect];
5443 }
5444
5445 @end
5446 /* }}} */
5447 /* Cydia TableView Cell {{{ */
5448 @interface CYTableViewCell : UITableViewCell {
5449 ContentView *content_;
5450 bool highlighted_;
5451 }
5452
5453 @end
5454
5455 @implementation CYTableViewCell
5456
5457 - (void) dealloc {
5458 [content_ release];
5459 [super dealloc];
5460 }
5461
5462 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5463 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5464
5465 if (view == content_) {
5466 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5467 highlighted_ = highlighted;
5468 }
5469
5470 [super _updateHighlightColorsForView:view highlighted:highlighted];
5471 }
5472
5473 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5474 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5475 highlighted_ = selected;
5476
5477 [super setSelected:selected animated:animated];
5478 [content_ setNeedsDisplay];
5479 }
5480
5481 @end
5482 /* }}} */
5483
5484 /* Package Cell {{{ */
5485 @interface PackageCell : CYTableViewCell <
5486 ContentDelegate
5487 > {
5488 UIImage *icon_;
5489 NSString *name_;
5490 NSString *description_;
5491 bool commercial_;
5492 NSString *source_;
5493 UIImage *badge_;
5494 Package *package_;
5495 UIImage *placard_;
5496 }
5497
5498 - (PackageCell *) init;
5499 - (void) setPackage:(Package *)package;
5500
5501 - (void) drawContentRect:(CGRect)rect;
5502
5503 @end
5504
5505 @implementation PackageCell
5506
5507 - (void) clearPackage {
5508 if (icon_ != nil) {
5509 [icon_ release];
5510 icon_ = nil;
5511 }
5512
5513 if (name_ != nil) {
5514 [name_ release];
5515 name_ = nil;
5516 }
5517
5518 if (description_ != nil) {
5519 [description_ release];
5520 description_ = nil;
5521 }
5522
5523 if (source_ != nil) {
5524 [source_ release];
5525 source_ = nil;
5526 }
5527
5528 if (badge_ != nil) {
5529 [badge_ release];
5530 badge_ = nil;
5531 }
5532
5533 if (placard_ != nil) {
5534 [placard_ release];
5535 placard_ = nil;
5536 }
5537
5538 [package_ release];
5539 package_ = nil;
5540 }
5541
5542 - (void) dealloc {
5543 [self clearPackage];
5544 [super dealloc];
5545 }
5546
5547 - (PackageCell *) init {
5548 CGRect frame(CGRectMake(0, 0, 320, 74));
5549 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5550 UIView *content([self contentView]);
5551 CGRect bounds([content bounds]);
5552
5553 content_ = [[ContentView alloc] initWithFrame:bounds];
5554 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5555 [content addSubview:content_];
5556
5557 [content_ setDelegate:self];
5558 [content_ setOpaque:YES];
5559 } return self;
5560 }
5561
5562 - (NSString *) accessibilityLabel {
5563 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5564 }
5565
5566 - (void) setPackage:(Package *)package {
5567 [self clearPackage];
5568 [package parse];
5569
5570 Source *source = [package source];
5571
5572 icon_ = [[package icon] retain];
5573 name_ = [[package name] retain];
5574
5575 if (IsWildcat_)
5576 description_ = [package longDescription];
5577 if (description_ == nil)
5578 description_ = [package shortDescription];
5579 if (description_ != nil)
5580 description_ = [description_ retain];
5581
5582 commercial_ = [package isCommercial];
5583
5584 package_ = [package retain];
5585
5586 NSString *label = nil;
5587 bool trusted = false;
5588
5589 if (source != nil) {
5590 label = [source label];
5591 trusted = [source trusted];
5592 } else if ([[package id] isEqualToString:@"firmware"])
5593 label = UCLocalize("APPLE");
5594 else
5595 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5596
5597 NSString *from(label);
5598
5599 NSString *section = [package simpleSection];
5600 if (section != nil && ![section isEqualToString:label]) {
5601 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5602 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5603 }
5604
5605 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5606 source_ = [from retain];
5607
5608 if (NSString *purpose = [package primaryPurpose])
5609 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5610 badge_ = [badge_ retain];
5611
5612 UIColor *color;
5613 NSString *placard;
5614
5615 if (NSString *mode = [package_ mode]) {
5616 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5617 color = RemovingColor_;
5618 //placard = @"removing";
5619 } else {
5620 color = InstallingColor_;
5621 //placard = @"installing";
5622 }
5623
5624 // XXX: the removing/installing placards are not @2x
5625 placard = nil;
5626 } else {
5627 color = [UIColor whiteColor];
5628
5629 if ([package installed] != nil)
5630 placard = @"installed";
5631 else
5632 placard = nil;
5633 }
5634
5635 [content_ setBackgroundColor:color];
5636
5637 if (placard != nil)
5638 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5639 placard_ = [placard_ retain];
5640
5641 [self setNeedsDisplay];
5642 [content_ setNeedsDisplay];
5643 }
5644
5645 - (void) drawContentRect:(CGRect)rect {
5646 bool highlighted(highlighted_);
5647 float width([self bounds].size.width);
5648
5649 #if 0
5650 CGContextRef context(UIGraphicsGetCurrentContext());
5651 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5652 CGContextFillRect(context, rect);
5653 #endif
5654
5655 if (icon_ != nil) {
5656 CGRect rect;
5657 rect.size = [icon_ size];
5658
5659 rect.size.width /= 2;
5660 rect.size.height /= 2;
5661
5662 rect.origin.x = 25 - rect.size.width / 2;
5663 rect.origin.y = 25 - rect.size.height / 2;
5664
5665 [icon_ drawInRect:rect];
5666 }
5667
5668 if (badge_ != nil) {
5669 CGRect rect;
5670 rect.size = [badge_ size];
5671
5672 rect.size.width /= 2;
5673 rect.size.height /= 2;
5674
5675 rect.origin.x = 36 - rect.size.width / 2;
5676 rect.origin.y = 36 - rect.size.height / 2;
5677
5678 [badge_ drawInRect:rect];
5679 }
5680
5681 if (highlighted)
5682 UISetColor(White_);
5683
5684 if (!highlighted)
5685 UISetColor(commercial_ ? Purple_ : Black_);
5686 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5687 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5688
5689 if (!highlighted)
5690 UISetColor(commercial_ ? Purplish_ : Gray_);
5691 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5692
5693 if (placard_ != nil)
5694 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5695 }
5696
5697 @end
5698 /* }}} */
5699 /* Section Cell {{{ */
5700 @interface SectionCell : CYTableViewCell <
5701 ContentDelegate
5702 > {
5703 NSString *basic_;
5704 NSString *section_;
5705 NSString *name_;
5706 NSString *count_;
5707 UIImage *icon_;
5708 UISwitch *switch_;
5709 BOOL editing_;
5710 }
5711
5712 - (void) setSection:(Section *)section editing:(BOOL)editing;
5713
5714 @end
5715
5716 @implementation SectionCell
5717
5718 - (void) clearSection {
5719 if (basic_ != nil) {
5720 [basic_ release];
5721 basic_ = nil;
5722 }
5723
5724 if (section_ != nil) {
5725 [section_ release];
5726 section_ = nil;
5727 }
5728
5729 if (name_ != nil) {
5730 [name_ release];
5731 name_ = nil;
5732 }
5733
5734 if (count_ != nil) {
5735 [count_ release];
5736 count_ = nil;
5737 }
5738 }
5739
5740 - (void) dealloc {
5741 [self clearSection];
5742 [icon_ release];
5743 [switch_ release];
5744 [super dealloc];
5745 }
5746
5747 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5748 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5749 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5750 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5751 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5752
5753 UIView *content([self contentView]);
5754 CGRect bounds([content bounds]);
5755
5756 content_ = [[ContentView alloc] initWithFrame:bounds];
5757 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5758 [content addSubview:content_];
5759 [content_ setBackgroundColor:[UIColor whiteColor]];
5760
5761 [content_ setDelegate:self];
5762 } return self;
5763 }
5764
5765 - (void) onSwitch:(id)sender {
5766 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5767 if (metadata == nil) {
5768 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5769 [Sections_ setObject:metadata forKey:basic_];
5770 }
5771
5772 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5773 Changed_ = true;
5774 }
5775
5776 - (void) setSection:(Section *)section editing:(BOOL)editing {
5777 if (editing != editing_) {
5778 if (editing_)
5779 [switch_ removeFromSuperview];
5780 else
5781 [self addSubview:switch_];
5782 editing_ = editing;
5783 }
5784
5785 [self clearSection];
5786
5787 if (section == nil) {
5788 name_ = [UCLocalize("ALL_PACKAGES") retain];
5789 count_ = nil;
5790 } else {
5791 basic_ = [section name];
5792 if (basic_ != nil)
5793 basic_ = [basic_ retain];
5794
5795 section_ = [section localized];
5796 if (section_ != nil)
5797 section_ = [section_ retain];
5798
5799 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5800 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5801
5802 if (editing_)
5803 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5804 }
5805
5806 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5807 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5808
5809 [content_ setNeedsDisplay];
5810 }
5811
5812 - (void) setFrame:(CGRect)frame {
5813 [super setFrame:frame];
5814
5815 CGRect rect([switch_ frame]);
5816 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5817 }
5818
5819 - (NSString *) accessibilityLabel {
5820 return name_;
5821 }
5822
5823 - (void) drawContentRect:(CGRect)rect {
5824 bool highlighted(highlighted_ && !editing_);
5825
5826 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5827
5828 if (highlighted)
5829 UISetColor(White_);
5830
5831 float width(rect.size.width);
5832 if (editing_)
5833 width -= 87;
5834
5835 if (!highlighted)
5836 UISetColor(Black_);
5837 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5838
5839 CGSize size = [count_ sizeWithFont:Font14_];
5840
5841 UISetColor(White_);
5842 if (count_ != nil)
5843 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5844 }
5845
5846 @end
5847 /* }}} */
5848
5849 /* File Table {{{ */
5850 @interface FileTable : CYViewController <
5851 UITableViewDataSource,
5852 UITableViewDelegate
5853 > {
5854 _transient Database *database_;
5855 Package *package_;
5856 NSString *name_;
5857 NSMutableArray *files_;
5858 UITableView *list_;
5859 }
5860
5861 - (id) initWithDatabase:(Database *)database;
5862 - (void) setPackage:(Package *)package;
5863
5864 @end
5865
5866 @implementation FileTable
5867
5868 - (void) dealloc {
5869 [self releaseSubviews];
5870
5871 [package_ release];
5872 [name_ release];
5873 [files_ release];
5874
5875 [super dealloc];
5876 }
5877
5878 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5879 return files_ == nil ? 0 : [files_ count];
5880 }
5881
5882 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5883 return 24.0f;
5884 }*/
5885
5886 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5887 static NSString *reuseIdentifier = @"Cell";
5888
5889 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5890 if (cell == nil) {
5891 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5892 [cell setFont:[UIFont systemFontOfSize:16]];
5893 }
5894 [cell setText:[files_ objectAtIndex:indexPath.row]];
5895 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5896
5897 return cell;
5898 }
5899
5900 - (NSURL *) navigationURL {
5901 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5902 }
5903
5904 - (void) loadView {
5905 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5906
5907 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5908 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5909 [list_ setRowHeight:24.0f];
5910 [list_ setDataSource:self];
5911 [list_ setDelegate:self];
5912 [[self view] addSubview:list_];
5913 }
5914
5915 - (void) viewDidLoad {
5916 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5917 }
5918
5919 - (void) releaseSubviews {
5920 [list_ release];
5921 list_ = nil;
5922 }
5923
5924 - (id) initWithDatabase:(Database *)database {
5925 if ((self = [super init]) != nil) {
5926 database_ = database;
5927
5928 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5929 } return self;
5930 }
5931
5932 - (void) setPackage:(Package *)package {
5933 if (package_ != nil) {
5934 [package_ autorelease];
5935 package_ = nil;
5936 }
5937
5938 if (name_ != nil) {
5939 [name_ release];
5940 name_ = nil;
5941 }
5942
5943 [files_ removeAllObjects];
5944
5945 if (package != nil) {
5946 package_ = [package retain];
5947 name_ = [[package id] retain];
5948
5949 if (NSArray *files = [package files])
5950 [files_ addObjectsFromArray:files];
5951
5952 if ([files_ count] != 0) {
5953 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5954 [files_ removeObjectAtIndex:0];
5955 [files_ sortUsingSelector:@selector(compareByPath:)];
5956
5957 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5958 [stack addObject:@"/"];
5959
5960 for (int i(0), e([files_ count]); i != e; ++i) {
5961 NSString *file = [files_ objectAtIndex:i];
5962 while (![file hasPrefix:[stack lastObject]])
5963 [stack removeLastObject];
5964 NSString *directory = [stack lastObject];
5965 [stack addObject:[file stringByAppendingString:@"/"]];
5966 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5967 ([stack count] - 2) * 3, "",
5968 [file substringFromIndex:[directory length]]
5969 ]];
5970 }
5971 }
5972 }
5973
5974 [list_ reloadData];
5975 }
5976
5977 - (void) reloadData {
5978 [super reloadData];
5979
5980 [self setPackage:[database_ packageWithName:name_]];
5981 }
5982
5983 @end
5984 /* }}} */
5985 /* Package Controller {{{ */
5986 @interface CYPackageController : CYBrowserController <
5987 UIActionSheetDelegate
5988 > {
5989 _transient Database *database_;
5990 _H<Package> package_;
5991 _H<NSString> name_;
5992 bool commercial_;
5993 _H<NSMutableArray> buttons_;
5994 _H<UIBarButtonItem> button_;
5995 }
5996
5997 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5998
5999 @end
6000
6001 @implementation CYPackageController
6002
6003 - (NSURL *) navigationURL {
6004 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6005 }
6006
6007 /* XXX: this is not safe at all... localization of /fail/ */
6008 - (void) _clickButtonWithName:(NSString *)name {
6009 if ([name isEqualToString:UCLocalize("CLEAR")])
6010 [delegate_ clearPackage:package_];
6011 else if ([name isEqualToString:UCLocalize("INSTALL")])
6012 [delegate_ installPackage:package_];
6013 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6014 [delegate_ installPackage:package_];
6015 else if ([name isEqualToString:UCLocalize("REMOVE")])
6016 [delegate_ removePackage:package_];
6017 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6018 [delegate_ installPackage:package_];
6019 else _assert(false);
6020 }
6021
6022 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6023 NSString *context([sheet context]);
6024
6025 if ([context isEqualToString:@"modify"]) {
6026 if (button != [sheet cancelButtonIndex]) {
6027 NSString *buttonName = [buttons_ objectAtIndex:button];
6028 [self _clickButtonWithName:buttonName];
6029 }
6030
6031 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6032 }
6033 }
6034
6035 - (bool) _allowJavaScriptPanel {
6036 return commercial_;
6037 }
6038
6039 #if !AlwaysReload
6040 - (void) _customButtonClicked {
6041 int count([buttons_ count]);
6042 if (count == 0)
6043 return;
6044
6045 if (count == 1)
6046 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6047 else {
6048 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6049 [buttons addObjectsFromArray:buttons_];
6050
6051 UIActionSheet *sheet = [[[UIActionSheet alloc]
6052 initWithTitle:nil
6053 delegate:self
6054 cancelButtonTitle:nil
6055 destructiveButtonTitle:nil
6056 otherButtonTitles:nil
6057 ] autorelease];
6058
6059 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6060 if (!IsWildcat_) {
6061 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6062 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6063 }
6064 [sheet setContext:@"modify"];
6065
6066 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6067 }
6068 }
6069
6070 // We don't want to allow non-commercial packages to do custom things to the install button,
6071 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6072 - (void) customButtonClicked {
6073 if (commercial_)
6074 [super customButtonClicked];
6075 else
6076 [self _customButtonClicked];
6077 }
6078
6079 - (void) reloadButtonClicked {
6080 // Don't reload a commerical package by tapping the loading button,
6081 // but if it's not an Install button, we should forward it on.
6082 if (![package_ uninstalled])
6083 [self _customButtonClicked];
6084 }
6085
6086 - (void) applyLoadingTitle {
6087 // Don't show "Loading" as the title. Ever.
6088 }
6089
6090 - (UIBarButtonItem *) rightButton {
6091 return button_;
6092 }
6093 #endif
6094
6095 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6096 if ((self = [super init]) != nil) {
6097 database_ = database;
6098 buttons_ = [NSMutableArray arrayWithCapacity:4];
6099 name_ = [NSString stringWithString:name];
6100 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6101 } return self;
6102 }
6103
6104 - (void) reloadData {
6105 [super reloadData];
6106
6107 package_ = [database_ packageWithName:name_];
6108
6109 [buttons_ removeAllObjects];
6110
6111 if (package_ != nil) {
6112 [(Package *) package_ parse];
6113
6114 commercial_ = [package_ isCommercial];
6115
6116 if ([package_ mode] != nil)
6117 [buttons_ addObject:UCLocalize("CLEAR")];
6118 if ([package_ source] == nil);
6119 else if ([package_ upgradableAndEssential:NO])
6120 [buttons_ addObject:UCLocalize("UPGRADE")];
6121 else if ([package_ uninstalled])
6122 [buttons_ addObject:UCLocalize("INSTALL")];
6123 else
6124 [buttons_ addObject:UCLocalize("REINSTALL")];
6125 if (![package_ uninstalled])
6126 [buttons_ addObject:UCLocalize("REMOVE")];
6127 }
6128
6129 NSString *title;
6130 switch ([buttons_ count]) {
6131 case 0: title = nil; break;
6132 case 1: title = [buttons_ objectAtIndex:0]; break;
6133 default: title = UCLocalize("MODIFY"); break;
6134 }
6135
6136 button_ = [[[UIBarButtonItem alloc]
6137 initWithTitle:title
6138 style:UIBarButtonItemStylePlain
6139 target:self
6140 action:@selector(customButtonClicked)
6141 ] autorelease];
6142 }
6143
6144 - (bool) isLoading {
6145 return commercial_ ? [super isLoading] : false;
6146 }
6147
6148 @end
6149 /* }}} */
6150
6151 /* Package List Controller {{{ */
6152 @interface PackageListController : CYViewController <
6153 UITableViewDataSource,
6154 UITableViewDelegate
6155 > {
6156 _transient Database *database_;
6157 unsigned era_;
6158 NSMutableArray *packages_;
6159 NSMutableArray *sections_;
6160 UITableView *list_;
6161 NSMutableArray *index_;
6162 NSMutableDictionary *indices_;
6163 NSString *title_;
6164 }
6165
6166 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6167 - (void) setDelegate:(id)delegate;
6168 - (void) resetCursor;
6169
6170 @end
6171
6172 @implementation PackageListController
6173
6174 - (void) dealloc {
6175 [packages_ release];
6176 [sections_ release];
6177 [list_ release];
6178 [index_ release];
6179 [indices_ release];
6180 [title_ release];
6181
6182 [super dealloc];
6183 }
6184
6185 - (void) deselectWithAnimation:(BOOL)animated {
6186 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6187 }
6188
6189 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6190 CGRect base = [[self view] bounds];
6191 base.size.height -= bounds.size.height;
6192 base.origin = [list_ frame].origin;
6193
6194 [UIView beginAnimations:nil context:NULL];
6195 [UIView setAnimationBeginsFromCurrentState:YES];
6196 [UIView setAnimationCurve:curve];
6197 [UIView setAnimationDuration:duration];
6198 [list_ setFrame:base];
6199 [UIView commitAnimations];
6200 }
6201
6202 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6203 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6204 }
6205
6206 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6207 [self resizeForKeyboardBounds:bounds duration:0];
6208 }
6209
6210 - (void) keyboardWillShow:(NSNotification *)notification {
6211 CGRect bounds;
6212 CGPoint center;
6213 NSTimeInterval duration;
6214 UIViewAnimationCurve curve;
6215 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6216 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6217 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6218 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6219
6220 CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
6221 UIViewController *base = self;
6222 while ([base parentViewController] != nil)
6223 base = [base parentViewController];
6224 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6225 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6226
6227 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6228 }
6229
6230 - (void) keyboardWillHide:(NSNotification *)notification {
6231 NSTimeInterval duration;
6232 UIViewAnimationCurve curve;
6233 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6234 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6235
6236 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6237 }
6238
6239 - (void) viewWillAppear:(BOOL)animated {
6240 [super viewWillAppear:animated];
6241
6242 [self resizeForKeyboardBounds:CGRectZero];
6243 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6244 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6245 }
6246
6247 - (void) viewWillDisappear:(BOOL)animated {
6248 [super viewWillDisappear:animated];
6249
6250 [self resizeForKeyboardBounds:CGRectZero];
6251 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6252 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6253 }
6254
6255 - (void) viewDidAppear:(BOOL)animated {
6256 [super viewDidAppear:animated];
6257 [self deselectWithAnimation:animated];
6258 }
6259
6260 - (void) didSelectPackage:(Package *)package {
6261 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6262 [view setDelegate:delegate_];
6263 [[self navigationController] pushViewController:view animated:YES];
6264 }
6265
6266 #if TryIndexedCollation
6267 + (BOOL) hasIndexedCollation {
6268 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6269 }
6270 #endif
6271
6272 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6273 NSInteger count([sections_ count]);
6274 return count == 0 ? 1 : count;
6275 }
6276
6277 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6278 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6279 return nil;
6280 return [[sections_ objectAtIndex:section] name];
6281 }
6282
6283 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6284 if ([sections_ count] == 0)
6285 return 0;
6286 return [[sections_ objectAtIndex:section] count];
6287 }
6288
6289 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6290 @synchronized (database_) {
6291 if ([database_ era] != era_)
6292 return nil;
6293
6294 Section *section([sections_ objectAtIndex:[path section]]);
6295 NSInteger row([path row]);
6296 Package *package([packages_ objectAtIndex:([section row] + row)]);
6297 return [[package retain] autorelease];
6298 } }
6299
6300 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6301 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6302 if (cell == nil)
6303 cell = [[[PackageCell alloc] init] autorelease];
6304 [cell setPackage:[self packageAtIndexPath:path]];
6305 return cell;
6306 }
6307
6308 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6309 Package *package([self packageAtIndexPath:path]);
6310 package = [database_ packageWithName:[package id]];
6311 [self didSelectPackage:package];
6312 }
6313
6314 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6315 // XXX: is 20 the most optimal number here?
6316 return [packages_ count] > 20 ? index_ : nil;
6317 }
6318
6319 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6320 #if TryIndexedCollation
6321 if ([[self class] hasIndexedCollation]) {
6322 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6323 }
6324 #endif
6325
6326 return index;
6327 }
6328
6329 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6330 if ((self = [super init]) != nil) {
6331 database_ = database;
6332 title_ = [title copy];
6333 [[self navigationItem] setTitle:title_];
6334
6335 #if TryIndexedCollation
6336 if ([[self class] hasIndexedCollation])
6337 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6338 else
6339 #endif
6340 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6341
6342 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6343
6344 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6345 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6346
6347 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6348 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6349 [list_ setRowHeight:73];
6350 [[self view] addSubview:list_];
6351
6352 [list_ setDataSource:self];
6353 [list_ setDelegate:self];
6354 } return self;
6355 }
6356
6357 - (void) setDelegate:(id)delegate {
6358 delegate_ = delegate;
6359 }
6360
6361 - (bool) hasPackage:(Package *)package {
6362 return true;
6363 }
6364
6365 - (void) reloadData {
6366 [super reloadData];
6367
6368 era_ = [database_ era];
6369 NSArray *packages = [database_ packages];
6370
6371 [packages_ removeAllObjects];
6372 [sections_ removeAllObjects];
6373
6374 _profile(PackageTable$reloadData$Filter)
6375 for (Package *package in packages)
6376 if ([self hasPackage:package])
6377 [packages_ addObject:package];
6378 _end
6379
6380 [indices_ removeAllObjects];
6381
6382 Section *section = nil;
6383
6384 #if TryIndexedCollation
6385 if ([[self class] hasIndexedCollation]) {
6386 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6387 NSArray *titles = [collation sectionIndexTitles];
6388 int secidx = -1;
6389
6390 _profile(PackageTable$reloadData$Section)
6391 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6392 Package *package;
6393 int index;
6394
6395 _profile(PackageTable$reloadData$Section$Package)
6396 package = [packages_ objectAtIndex:offset];
6397 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6398 _end
6399
6400 while (secidx < index) {
6401 secidx += 1;
6402
6403 _profile(PackageTable$reloadData$Section$Allocate)
6404 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6405 _end
6406
6407 _profile(PackageTable$reloadData$Section$Add)
6408 [sections_ addObject:section];
6409 _end
6410 }
6411
6412 [section addToCount];
6413 }
6414 _end
6415 } else
6416 #endif
6417 {
6418 [index_ removeAllObjects];
6419
6420 _profile(PackageTable$reloadData$Section)
6421 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6422 Package *package;
6423 unichar index;
6424
6425 _profile(PackageTable$reloadData$Section$Package)
6426 package = [packages_ objectAtIndex:offset];
6427 index = [package index];
6428 _end
6429
6430 if (section == nil || [section index] != index) {
6431 _profile(PackageTable$reloadData$Section$Allocate)
6432 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6433 _end
6434
6435 [index_ addObject:[section name]];
6436 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6437
6438 _profile(PackageTable$reloadData$Section$Add)
6439 [sections_ addObject:section];
6440 _end
6441 }
6442
6443 [section addToCount];
6444 }
6445 _end
6446 }
6447
6448 _profile(PackageTable$reloadData$List)
6449 [list_ reloadData];
6450 _end
6451 }
6452
6453 - (void) resetCursor {
6454 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6455 }
6456
6457 @end
6458 /* }}} */
6459 /* Filtered Package List Controller {{{ */
6460 @interface FilteredPackageListController : PackageListController {
6461 SEL filter_;
6462 IMP imp_;
6463 id object_;
6464 }
6465
6466 - (void) setObject:(id)object;
6467 - (void) setObject:(id)object forFilter:(SEL)filter;
6468
6469 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6470
6471 @end
6472
6473 @implementation FilteredPackageListController
6474
6475 - (void) dealloc {
6476 if (object_ != nil)
6477 [object_ release];
6478 [super dealloc];
6479 }
6480
6481 - (void) setFilter:(SEL)filter {
6482 filter_ = filter;
6483
6484 /* XXX: this is an unsafe optimization of doomy hell */
6485 Method method(class_getInstanceMethod([Package class], filter));
6486 _assert(method != NULL);
6487 imp_ = method_getImplementation(method);
6488 _assert(imp_ != NULL);
6489 }
6490
6491 - (void) setObject:(id)object {
6492 if (object_ != nil)
6493 [object_ release];
6494 if (object == nil)
6495 object_ = nil;
6496 else
6497 object_ = [object retain];
6498 }
6499
6500 - (void) setObject:(id)object forFilter:(SEL)filter {
6501 [self setFilter:filter];
6502 [self setObject:object];
6503 }
6504
6505 - (bool) hasPackage:(Package *)package {
6506 _profile(FilteredPackageTable$hasPackage)
6507 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6508 _end
6509 }
6510
6511 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6512 if ((self = [super initWithDatabase:database title:title]) != nil) {
6513 [self setFilter:filter];
6514 [self setObject:object];
6515 } return self;
6516 }
6517
6518 @end
6519 /* }}} */
6520
6521 /* Home Controller {{{ */
6522 @interface HomeController : CYBrowserController {
6523 }
6524
6525 @end
6526
6527 @implementation HomeController
6528
6529 - (id) init {
6530 if ((self = [super init]) != nil) {
6531 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6532 } return self;
6533 }
6534
6535 - (NSURL *) navigationURL {
6536 return [NSURL URLWithString:@"cydia://home"];
6537 }
6538
6539 - (void) aboutButtonClicked {
6540 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6541
6542 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6543 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6544 [alert setCancelButtonIndex:0];
6545
6546 [alert setMessage:
6547 @"Copyright (C) 2008-2011\n"
6548 "Jay Freeman (saurik)\n"
6549 "saurik@saurik.com\n"
6550 "http://www.saurik.com/"
6551 ];
6552
6553 [alert show];
6554 }
6555
6556 - (void) viewDidLoad {
6557 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6558 initWithTitle:UCLocalize("ABOUT")
6559 style:UIBarButtonItemStylePlain
6560 target:self
6561 action:@selector(aboutButtonClicked)
6562 ] autorelease]];
6563 }
6564
6565 @end
6566 /* }}} */
6567 /* Manage Controller {{{ */
6568 @interface ManageController : CYBrowserController {
6569 }
6570
6571 - (void) queueStatusDidChange;
6572
6573 @end
6574
6575 @implementation ManageController
6576
6577 - (id) init {
6578 if ((self = [super init]) != nil) {
6579 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6580 } return self;
6581 }
6582
6583 - (NSURL *) navigationURL {
6584 return [NSURL URLWithString:@"cydia://manage"];
6585 }
6586
6587 - (void) viewDidLoad {
6588 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6589 initWithTitle:UCLocalize("SETTINGS")
6590 style:UIBarButtonItemStylePlain
6591 target:self
6592 action:@selector(settingsButtonClicked)
6593 ] autorelease]];
6594
6595 [self queueStatusDidChange];
6596 }
6597
6598 - (void) settingsButtonClicked {
6599 [delegate_ showSettings];
6600 }
6601
6602 #if !AlwaysReload
6603 - (void) queueButtonClicked {
6604 [delegate_ queue];
6605 }
6606
6607 - (void) applyLoadingTitle {
6608 // Disable "Loading" title.
6609 }
6610
6611 - (void) applyRightButton {
6612 // Disable right button.
6613 }
6614 #endif
6615
6616 - (void) queueStatusDidChange {
6617 #if !AlwaysReload
6618 if (!IsWildcat_ && Queuing_) {
6619 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6620 initWithTitle:UCLocalize("QUEUE")
6621 style:UIBarButtonItemStyleDone
6622 target:self
6623 action:@selector(queueButtonClicked)
6624 ] autorelease]];
6625 } else {
6626 [[self navigationItem] setRightBarButtonItem:nil];
6627 }
6628 #endif
6629 }
6630
6631 - (bool) isLoading {
6632 // Never show as loading.
6633 return false;
6634 }
6635
6636 @end
6637 /* }}} */
6638
6639 /* Refresh Bar {{{ */
6640 @interface RefreshBar : UINavigationBar {
6641 UIProgressIndicator *indicator_;
6642 UITextLabel *prompt_;
6643 UIProgressBar *progress_;
6644 UINavigationButton *cancel_;
6645 }
6646
6647 @end
6648
6649 @implementation RefreshBar
6650
6651 - (void) dealloc {
6652 [indicator_ release];
6653 [prompt_ release];
6654 [progress_ release];
6655 [cancel_ release];
6656 [super dealloc];
6657 }
6658
6659 - (void) positionViews {
6660 CGRect frame = [cancel_ frame];
6661 frame.size = [cancel_ sizeThatFits:frame.size];
6662 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6663 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6664 [cancel_ setFrame:frame];
6665
6666 CGSize prgsize = {75, 100};
6667 CGRect prgrect = {{
6668 [self frame].size.width - prgsize.width - 10,
6669 ([self frame].size.height - prgsize.height) / 2
6670 } , prgsize};
6671 [progress_ setFrame:prgrect];
6672
6673 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6674 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6675 CGRect indrect = {{indoffset, indoffset}, indsize};
6676 [indicator_ setFrame:indrect];
6677
6678 CGSize prmsize = {215, indsize.height + 4};
6679 CGRect prmrect = {{
6680 indoffset * 2 + indsize.width,
6681 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6682 }, prmsize};
6683 [prompt_ setFrame:prmrect];
6684 }
6685
6686 - (void) setFrame:(CGRect)frame {
6687 [super setFrame:frame];
6688 [self positionViews];
6689 }
6690
6691 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6692 if ((self = [super initWithFrame:frame]) != nil) {
6693 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6694
6695 [self setBarStyle:UIBarStyleBlack];
6696
6697 UIBarStyle barstyle([self _barStyle:NO]);
6698 bool ugly(barstyle == UIBarStyleDefault);
6699
6700 UIProgressIndicatorStyle style = ugly ?
6701 UIProgressIndicatorStyleMediumBrown :
6702 UIProgressIndicatorStyleMediumWhite;
6703
6704 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6705 [indicator_ setStyle:style];
6706 [indicator_ startAnimation];
6707 [self addSubview:indicator_];
6708
6709 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6710 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6711 [prompt_ setBackgroundColor:[UIColor clearColor]];
6712 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6713 [self addSubview:prompt_];
6714
6715 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6716 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6717 [progress_ setStyle:0];
6718 [self addSubview:progress_];
6719
6720 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6721 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6722 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6723 [cancel_ setBarStyle:barstyle];
6724
6725 [self positionViews];
6726 } return self;
6727 }
6728
6729 - (void) setCancellable:(bool)cancellable {
6730 if (cancellable)
6731 [self addSubview:cancel_];
6732 else
6733 [cancel_ removeFromSuperview];
6734 }
6735
6736 - (void) start {
6737 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6738 [progress_ setProgress:0];
6739 }
6740
6741 - (void) stop {
6742 [self setCancellable:NO];
6743 }
6744
6745 - (void) setPrompt:(NSString *)prompt {
6746 [prompt_ setText:prompt];
6747 }
6748
6749 - (void) setProgress:(float)progress {
6750 [progress_ setProgress:progress];
6751 }
6752
6753 @end
6754 /* }}} */
6755
6756 /* Cydia Navigation Controller Interface {{{ */
6757 @interface UINavigationController (Cydia)
6758
6759 - (NSArray *) navigationURLCollection;
6760 - (void) unloadData;
6761
6762 @end
6763 /* }}} */
6764
6765 /* Cydia Tab Bar Controller {{{ */
6766 @interface CYTabBarController : UITabBarController <
6767 UITabBarControllerDelegate,
6768 ProgressDelegate
6769 > {
6770 _transient Database *database_;
6771 RefreshBar *refreshbar_;
6772
6773 bool dropped_;
6774 bool updating_;
6775 // XXX: ok, "updatedelegate_"?...
6776 _transient NSObject<CydiaDelegate> *updatedelegate_;
6777
6778 id root_;
6779 UIViewController *remembered_;
6780 _transient UIViewController *transient_;
6781 }
6782
6783 - (NSArray *) navigationURLCollection;
6784 - (void) dropBar:(BOOL)animated;
6785 - (void) beginUpdate;
6786 - (void) raiseBar:(BOOL)animated;
6787 - (BOOL) updating;
6788 - (void) unloadData;
6789
6790 @end
6791
6792 @implementation CYTabBarController
6793
6794 - (void) setUnselectedViewController:(UIViewController *)transient {
6795 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6796 if (transient != nil) {
6797 if (transient_ == nil)
6798 remembered_ = [[controllers objectAtIndex:0] retain];
6799 transient_ = transient;
6800 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6801 [controllers replaceObjectAtIndex:0 withObject:transient_];
6802 [self setSelectedIndex:0];
6803 [self setViewControllers:controllers];
6804 [self concealTabBarSelection];
6805 } else if (remembered_ != nil) {
6806 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6807 transient_ = transient;
6808 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6809 [remembered_ release];
6810 remembered_ = nil;
6811 [self setViewControllers:controllers];
6812 [self revealTabBarSelection];
6813 }
6814 }
6815
6816 - (UIViewController *) unselectedViewController {
6817 return transient_;
6818 }
6819
6820 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6821 if ([self unselectedViewController])
6822 [self setUnselectedViewController:nil];
6823 }
6824
6825 - (NSArray *) navigationURLCollection {
6826 NSMutableArray *items([NSMutableArray array]);
6827
6828 // XXX: Should this deal with transient view controllers?
6829 for (id navigation in [self viewControllers]) {
6830 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6831 if (stack != nil)
6832 [items addObject:stack];
6833 }
6834
6835 return items;
6836 }
6837
6838 - (void) unloadData {
6839 UIViewController *selected([self selectedViewController]);
6840 for (UINavigationController *controller in [self viewControllers])
6841 [controller unloadData];
6842
6843 [selected reloadData];
6844
6845 if (UIViewController *unselected = [self unselectedViewController])
6846 [unselected reloadData];
6847
6848 [super unloadData];
6849 }
6850
6851 - (void) dealloc {
6852 [refreshbar_ release];
6853 [[NSNotificationCenter defaultCenter] removeObserver:self];
6854
6855 [super dealloc];
6856 }
6857
6858 - (id) initWithDatabase:(Database *)database {
6859 if ((self = [super init]) != nil) {
6860 database_ = database;
6861 [self setDelegate:self];
6862
6863 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6864 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6865
6866 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6867 } return self;
6868 }
6869
6870 - (void) setUpdate:(NSDate *)date {
6871 [self beginUpdate];
6872 }
6873
6874 - (void) beginUpdate {
6875 [refreshbar_ start];
6876 [self dropBar:YES];
6877
6878 [updatedelegate_ retainNetworkActivityIndicator];
6879 updating_ = true;
6880
6881 [NSThread
6882 detachNewThreadSelector:@selector(performUpdate)
6883 toTarget:self
6884 withObject:nil
6885 ];
6886 }
6887
6888 - (void) performUpdate { _pooled
6889 Status status;
6890 status.setDelegate(self);
6891 [database_ updateWithStatus:status];
6892
6893 [self
6894 performSelectorOnMainThread:@selector(completeUpdate)
6895 withObject:nil
6896 waitUntilDone:NO
6897 ];
6898 }
6899
6900 - (void) stopUpdateWithSelector:(SEL)selector {
6901 updating_ = false;
6902 [updatedelegate_ releaseNetworkActivityIndicator];
6903
6904 [self raiseBar:YES];
6905 [refreshbar_ stop];
6906
6907 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6908 }
6909
6910 - (void) completeUpdate {
6911 if (!updating_)
6912 return;
6913 [self stopUpdateWithSelector:@selector(reloadData)];
6914 }
6915
6916 - (void) cancelUpdate {
6917 [self stopUpdateWithSelector:@selector(updateData)];
6918 }
6919
6920 - (void) cancelPressed {
6921 [self cancelUpdate];
6922 }
6923
6924 - (BOOL) updating {
6925 return updating_;
6926 }
6927
6928 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6929 [refreshbar_ setPrompt:[event compoundMessage]];
6930 }
6931
6932 - (bool) isProgressCancelled {
6933 return !updating_;
6934 }
6935
6936 - (void) setProgressCancellable:(NSNumber *)cancellable {
6937 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6938 }
6939
6940 - (void) setProgressPercent:(NSNumber *)percent {
6941 [refreshbar_ setProgress:[percent floatValue]];
6942 }
6943
6944 - (void) setProgressStatus:(NSDictionary *)status {
6945 if (status != nil)
6946 [self setProgressPercent:[status objectForKey:@"Percent"]];
6947 }
6948
6949 - (void) setUpdateDelegate:(id)delegate {
6950 updatedelegate_ = delegate;
6951 }
6952
6953 - (CGFloat) statusBarHeight {
6954 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6955 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6956 } else {
6957 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6958 }
6959 }
6960
6961 - (UIView *) transitionView {
6962 if ([self respondsToSelector:@selector(_transitionView)])
6963 return [self _transitionView];
6964 else
6965 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6966 }
6967
6968 - (void) dropBar:(BOOL)animated {
6969 if (dropped_)
6970 return;
6971 dropped_ = true;
6972
6973 UIView *transition([self transitionView]);
6974 [[self view] addSubview:refreshbar_];
6975
6976 CGRect barframe([refreshbar_ frame]);
6977
6978 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6979 barframe.origin.y = [self statusBarHeight];
6980 else
6981 barframe.origin.y = 0;
6982
6983 [refreshbar_ setFrame:barframe];
6984
6985 if (animated)
6986 [UIView beginAnimations:nil context:NULL];
6987
6988 CGRect viewframe = [transition frame];
6989 viewframe.origin.y += barframe.size.height;
6990 viewframe.size.height -= barframe.size.height;
6991 [transition setFrame:viewframe];
6992
6993 if (animated)
6994 [UIView commitAnimations];
6995
6996 // Ensure bar has the proper width for our view, it might have changed
6997 barframe.size.width = viewframe.size.width;
6998 [refreshbar_ setFrame:barframe];
6999
7000 // XXX: fix Apple's layout bug
7001 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7002 }
7003
7004 - (void) raiseBar:(BOOL)animated {
7005 if (!dropped_)
7006 return;
7007 dropped_ = false;
7008
7009 UIView *transition([self transitionView]);
7010 [refreshbar_ removeFromSuperview];
7011
7012 CGRect barframe([refreshbar_ frame]);
7013
7014 if (animated)
7015 [UIView beginAnimations:nil context:NULL];
7016
7017 CGRect viewframe = [transition frame];
7018 viewframe.origin.y -= barframe.size.height;
7019 viewframe.size.height += barframe.size.height;
7020 [transition setFrame:viewframe];
7021
7022 if (animated)
7023 [UIView commitAnimations];
7024
7025 // XXX: fix Apple's layout bug
7026 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7027 }
7028
7029 #if 0
7030 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7031 // XXX: fix Apple's layout bug
7032 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7033 }
7034 #endif
7035
7036 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7037 bool dropped(dropped_);
7038
7039 if (dropped)
7040 [self raiseBar:NO];
7041
7042 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7043
7044 if (dropped)
7045 [self dropBar:NO];
7046
7047 // XXX: fix Apple's layout bug
7048 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7049 }
7050
7051 - (void) statusBarFrameChanged:(NSNotification *)notification {
7052 if (dropped_) {
7053 [self raiseBar:NO];
7054 [self dropBar:NO];
7055 }
7056 }
7057
7058 @end
7059 /* }}} */
7060
7061 /* Cydia Navigation Controller Implementation {{{ */
7062 @implementation UINavigationController (Cydia)
7063
7064 - (NSArray *) navigationURLCollection {
7065 NSMutableArray *stack([NSMutableArray array]);
7066
7067 for (CYViewController *controller in [self viewControllers]) {
7068 NSString *url = [[controller navigationURL] absoluteString];
7069 if (url != nil)
7070 [stack addObject:url];
7071 }
7072
7073 return stack;
7074 }
7075
7076 - (void) reloadData {
7077 [super reloadData];
7078
7079 if (UIViewController *visible = [self visibleViewController])
7080 [visible reloadData];
7081 }
7082
7083 - (void) unloadData {
7084 for (CYViewController *page in [self viewControllers])
7085 [page unloadData];
7086
7087 [super unloadData];
7088 }
7089
7090 @end
7091 /* }}} */
7092
7093 /* Cydia:// Protocol {{{ */
7094 @interface CydiaURLProtocol : NSURLProtocol {
7095 }
7096
7097 @end
7098
7099 @implementation CydiaURLProtocol
7100
7101 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7102 NSURL *url([request URL]);
7103 if (url == nil)
7104 return NO;
7105
7106 NSString *scheme([[url scheme] lowercaseString]);
7107 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7108 return YES;
7109 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7110 return YES;
7111
7112 return NO;
7113 }
7114
7115 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7116 return request;
7117 }
7118
7119 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7120 id<NSURLProtocolClient> client([self client]);
7121 if (icon == nil)
7122 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7123 else {
7124 NSData *data(UIImagePNGRepresentation(icon));
7125
7126 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7127 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7128 [client URLProtocol:self didLoadData:data];
7129 [client URLProtocolDidFinishLoading:self];
7130 }
7131 }
7132
7133 - (void) startLoading {
7134 id<NSURLProtocolClient> client([self client]);
7135 NSURLRequest *request([self request]);
7136
7137 NSURL *url([request URL]);
7138 NSString *href([url absoluteString]);
7139 NSString *scheme([[url scheme] lowercaseString]);
7140
7141 NSString *path;
7142
7143 if ([scheme isEqualToString:@"cydia"])
7144 path = [href substringFromIndex:8];
7145 else if ([scheme isEqualToString:@"about"])
7146 path = [href substringFromIndex:12];
7147 else _assert(false);
7148
7149 NSRange slash([path rangeOfString:@"/"]);
7150
7151 NSString *command;
7152 if (slash.location == NSNotFound) {
7153 command = path;
7154 path = nil;
7155 } else {
7156 command = [path substringToIndex:slash.location];
7157 path = [path substringFromIndex:(slash.location + 1)];
7158 }
7159
7160 Database *database([Database sharedInstance]);
7161
7162 if ([command isEqualToString:@"package-icon"]) {
7163 if (path == nil)
7164 goto fail;
7165 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7166 Package *package([database packageWithName:path]);
7167 if (package == nil)
7168 goto fail;
7169 UIImage *icon([package icon]);
7170 [self _returnPNGWithImage:icon forRequest:request];
7171 } else if ([command isEqualToString:@"source-icon"]) {
7172 if (path == nil)
7173 goto fail;
7174 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7175 NSString *source(Simplify(path));
7176 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7177 if (icon == nil)
7178 icon = [UIImage applicationImageNamed:@"unknown.png"];
7179 [self _returnPNGWithImage:icon forRequest:request];
7180 } else if ([command isEqualToString:@"uikit-image"]) {
7181 if (path == nil)
7182 goto fail;
7183 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7184 UIImage *icon(_UIImageWithName(path));
7185 [self _returnPNGWithImage:icon forRequest:request];
7186 } else if ([command isEqualToString:@"section-icon"]) {
7187 if (path == nil)
7188 goto fail;
7189 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7190 NSString *section(Simplify(path));
7191 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7192 if (icon == nil)
7193 icon = [UIImage applicationImageNamed:@"unknown.png"];
7194 [self _returnPNGWithImage:icon forRequest:request];
7195 } else fail: {
7196 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7197 }
7198 }
7199
7200 - (void) stopLoading {
7201 }
7202
7203 @end
7204 /* }}} */
7205
7206 /* Section Controller {{{ */
7207 @interface SectionController : FilteredPackageListController {
7208 _H<NSString> section_;
7209 }
7210
7211 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7212
7213 @end
7214
7215 @implementation SectionController
7216
7217 - (NSURL *) navigationURL {
7218 NSString *name = section_;
7219 if (name == nil)
7220 name = @"all";
7221
7222 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7223 }
7224
7225 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7226 NSString *title;
7227 if (name == nil)
7228 title = UCLocalize("ALL_PACKAGES");
7229 else if (![name isEqual:@""])
7230 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7231 else
7232 title = UCLocalize("NO_SECTION");
7233
7234 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7235 section_ = name;
7236 } return self;
7237 }
7238
7239 @end
7240 /* }}} */
7241 /* Sections Controller {{{ */
7242 @interface SectionsController : CYViewController <
7243 UITableViewDataSource,
7244 UITableViewDelegate
7245 > {
7246 _transient Database *database_;
7247 NSMutableArray *sections_;
7248 NSMutableArray *filtered_;
7249 UITableView *list_;
7250 }
7251
7252 - (id) initWithDatabase:(Database *)database;
7253 - (void) editButtonClicked;
7254
7255 @end
7256
7257 @implementation SectionsController
7258
7259 - (void) dealloc {
7260 [self releaseSubviews];
7261 [sections_ release];
7262 [filtered_ release];
7263
7264 [super dealloc];
7265 }
7266
7267 - (NSURL *) navigationURL {
7268 return [NSURL URLWithString:@"cydia://sections"];
7269 }
7270
7271 - (void) updateNavigationItem {
7272 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7273 if ([sections_ count] == 0) {
7274 [[self navigationItem] setRightBarButtonItem:nil];
7275 } else {
7276 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7277 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7278 target:self
7279 action:@selector(editButtonClicked)
7280 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7281 }
7282 }
7283
7284 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7285 [super setEditing:editing animated:animated];
7286
7287 if (editing)
7288 [list_ reloadData];
7289 else
7290 [delegate_ updateData];
7291
7292 [self updateNavigationItem];
7293 }
7294
7295 - (void) viewDidAppear:(BOOL)animated {
7296 [super viewDidAppear:animated];
7297 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7298 }
7299
7300 - (void) viewWillDisappear:(BOOL)animated {
7301 [super viewWillDisappear:animated];
7302 if ([self isEditing]) [self setEditing:NO];
7303 }
7304
7305 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7306 Section *section = nil;
7307 int index = [indexPath row];
7308 if (![self isEditing]) {
7309 index -= 1;
7310 if (index >= 0)
7311 section = [filtered_ objectAtIndex:index];
7312 } else {
7313 section = [sections_ objectAtIndex:index];
7314 }
7315 return section;
7316 }
7317
7318 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7319 if ([self isEditing])
7320 return [sections_ count];
7321 else
7322 return [filtered_ count] + 1;
7323 }
7324
7325 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7326 return 45.0f;
7327 }*/
7328
7329 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7330 static NSString *reuseIdentifier = @"SectionCell";
7331
7332 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7333 if (cell == nil)
7334 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7335
7336 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7337
7338 return cell;
7339 }
7340
7341 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7342 if ([self isEditing])
7343 return;
7344
7345 Section *section = [self sectionAtIndexPath:indexPath];
7346
7347 SectionController *controller = [[[SectionController alloc]
7348 initWithDatabase:database_
7349 section:[section name]
7350 ] autorelease];
7351 [controller setDelegate:delegate_];
7352
7353 [[self navigationController] pushViewController:controller animated:YES];
7354 }
7355
7356 - (void) loadView {
7357 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7358
7359 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7360 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7361 [list_ setRowHeight:45.0f];
7362 [list_ setDataSource:self];
7363 [list_ setDelegate:self];
7364 [[self view] addSubview:list_];
7365 }
7366
7367 - (void) viewDidLoad {
7368 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7369 }
7370
7371 - (void) releaseSubviews {
7372 [list_ release];
7373 list_ = nil;
7374 }
7375
7376 - (id) initWithDatabase:(Database *)database {
7377 if ((self = [super init]) != nil) {
7378 database_ = database;
7379
7380 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7381 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7382 } return self;
7383 }
7384
7385 - (void) reloadData {
7386 [super reloadData];
7387
7388 NSArray *packages = [database_ packages];
7389
7390 [sections_ removeAllObjects];
7391 [filtered_ removeAllObjects];
7392
7393 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7394
7395 _trace();
7396 for (Package *package in packages) {
7397 NSString *name([package section]);
7398 NSString *key(name == nil ? @"" : name);
7399
7400 Section *section;
7401
7402 _profile(SectionsView$reloadData$Section)
7403 section = [sections objectForKey:key];
7404 if (section == nil) {
7405 _profile(SectionsView$reloadData$Section$Allocate)
7406 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7407 [sections setObject:section forKey:key];
7408 _end
7409 }
7410 _end
7411
7412 [section addToCount];
7413
7414 _profile(SectionsView$reloadData$Filter)
7415 if (![package valid] || ![package visible])
7416 continue;
7417 _end
7418
7419 [section addToRow];
7420 }
7421 _trace();
7422
7423 [sections_ addObjectsFromArray:[sections allValues]];
7424
7425 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7426
7427 for (Section *section in sections_) {
7428 size_t count([section row]);
7429 if (count == 0)
7430 continue;
7431
7432 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7433 [section setCount:count];
7434 [filtered_ addObject:section];
7435 }
7436
7437 [self updateNavigationItem];
7438 [list_ reloadData];
7439 _trace();
7440 }
7441
7442 - (void) editButtonClicked {
7443 [self setEditing:![self isEditing] animated:YES];
7444 }
7445
7446 @end
7447 /* }}} */
7448
7449 /* Changes Controller {{{ */
7450 @interface ChangesController : CYViewController <
7451 UITableViewDataSource,
7452 UITableViewDelegate
7453 > {
7454 _transient Database *database_;
7455 unsigned era_;
7456 CFMutableArrayRef packages_;
7457 NSMutableArray *sections_;
7458 UITableView *list_;
7459 unsigned upgrades_;
7460 }
7461
7462 - (id) initWithDatabase:(Database *)database;
7463
7464 @end
7465
7466 @implementation ChangesController
7467
7468 - (void) dealloc {
7469 [self releaseSubviews];
7470 CFRelease(packages_);
7471 [sections_ release];
7472
7473 [super dealloc];
7474 }
7475
7476 - (NSURL *) navigationURL {
7477 return [NSURL URLWithString:@"cydia://changes"];
7478 }
7479
7480 - (void) viewDidAppear:(BOOL)animated {
7481 [super viewDidAppear:animated];
7482 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7483 }
7484
7485 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7486 NSInteger count([sections_ count]);
7487 return count == 0 ? 1 : count;
7488 }
7489
7490 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7491 if ([sections_ count] == 0)
7492 return nil;
7493 return [[sections_ objectAtIndex:section] name];
7494 }
7495
7496 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7497 if ([sections_ count] == 0)
7498 return 0;
7499 return [[sections_ objectAtIndex:section] count];
7500 }
7501
7502 - (Package *) packageAtIndex:(NSUInteger)index {
7503 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7504 }
7505
7506 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7507 @synchronized (database_) {
7508 if ([database_ era] != era_)
7509 return nil;
7510
7511 NSUInteger sectionIndex([path section]);
7512 if (sectionIndex >= [sections_ count])
7513 return nil;
7514 Section *section([sections_ objectAtIndex:sectionIndex]);
7515 NSInteger row([path row]);
7516 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7517 } }
7518
7519 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7520 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7521 if (cell == nil)
7522 cell = [[[PackageCell alloc] init] autorelease];
7523 [cell setPackage:[self packageAtIndexPath:path]];
7524 return cell;
7525 }
7526
7527 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7528 Package *package([self packageAtIndexPath:path]);
7529 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7530 [view setDelegate:delegate_];
7531 [[self navigationController] pushViewController:view animated:YES];
7532 return path;
7533 }
7534
7535 - (void) refreshButtonClicked {
7536 [delegate_ beginUpdate];
7537 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7538 }
7539
7540 - (void) upgradeButtonClicked {
7541 [delegate_ distUpgrade];
7542 }
7543
7544 - (void) loadView {
7545 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7546
7547 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7548 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7549 [list_ setRowHeight:73];
7550 [list_ setDataSource:self];
7551 [list_ setDelegate:self];
7552 [[self view] addSubview:list_];
7553 }
7554
7555 - (void) viewDidLoad {
7556 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7557 }
7558
7559 - (void) releaseSubviews {
7560 [list_ release];
7561 list_ = nil;
7562 }
7563
7564 - (id) initWithDatabase:(Database *)database {
7565 if ((self = [super init]) != nil) {
7566 database_ = database;
7567
7568 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7569 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7570 } return self;
7571 }
7572
7573 // this mostly works because reloadData (below) is @synchronized (database_)
7574 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7575 - (void) _reloadPackages:(NSArray *)packages {
7576 CFRelease(packages_);
7577 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7578
7579 _trace();
7580 _profile(ChangesController$_reloadPackages$Filter)
7581 for (Package *package in packages)
7582 if ([package upgradableAndEssential:YES] || [package visible])
7583 CFArrayAppendValue(packages_, package);
7584 _end
7585 _trace();
7586 _profile(ChangesController$_reloadPackages$radixSort)
7587 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7588 _end
7589 _trace();
7590 }
7591
7592 - (void) _reloadData {
7593 @synchronized (database_) {
7594 era_ = [database_ era];
7595 NSArray *packages = [database_ packages];
7596
7597 [sections_ removeAllObjects];
7598
7599 #if 1
7600 UIProgressHUD *hud([delegate_ addProgressHUD]);
7601 [hud setText:UCLocalize("LOADING")];
7602 //NSLog(@"HUD:%@::%@", delegate_, hud);
7603 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7604 [delegate_ removeProgressHUD:hud];
7605 #else
7606 [self _reloadPackages:packages];
7607 #endif
7608
7609 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7610 Section *ignored = nil;
7611 Section *section = nil;
7612 time_t last = 0;
7613
7614 upgrades_ = 0;
7615 bool unseens = false;
7616
7617 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7618
7619 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7620 Package *package = [self packageAtIndex:offset];
7621
7622 BOOL uae = [package upgradableAndEssential:YES];
7623
7624 if (!uae) {
7625 unseens = true;
7626 time_t seen([package seen]);
7627
7628 if (section == nil || last != seen) {
7629 last = seen;
7630
7631 NSString *name;
7632 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7633 [name autorelease];
7634
7635 _profile(ChangesController$reloadData$Allocate)
7636 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7637 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7638 [sections_ addObject:section];
7639 _end
7640 }
7641
7642 [section addToCount];
7643 } else if ([package ignored]) {
7644 if (ignored == nil) {
7645 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7646 }
7647 [ignored addToCount];
7648 } else {
7649 ++upgrades_;
7650 [upgradable addToCount];
7651 }
7652 }
7653 _trace();
7654
7655 CFRelease(formatter);
7656
7657 if (unseens) {
7658 Section *last = [sections_ lastObject];
7659 size_t count = [last count];
7660 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7661 [sections_ removeLastObject];
7662 }
7663
7664 if ([ignored count] != 0)
7665 [sections_ insertObject:ignored atIndex:0];
7666 if (upgrades_ != 0)
7667 [sections_ insertObject:upgradable atIndex:0];
7668
7669 [list_ reloadData];
7670
7671 if (upgrades_ > 0)
7672 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7673 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7674 style:UIBarButtonItemStylePlain
7675 target:self
7676 action:@selector(upgradeButtonClicked)
7677 ] autorelease]];
7678
7679 if (![delegate_ updating])
7680 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7681 initWithTitle:UCLocalize("REFRESH")
7682 style:UIBarButtonItemStylePlain
7683 target:self
7684 action:@selector(refreshButtonClicked)
7685 ] autorelease]];
7686
7687 PrintTimes();
7688 } }
7689
7690 - (void) reloadData {
7691 [super reloadData];
7692 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7693 }
7694
7695 @end
7696 /* }}} */
7697 /* Search Controller {{{ */
7698 @interface SearchController : FilteredPackageListController <
7699 UISearchBarDelegate
7700 > {
7701 _H<UISearchBar> search_;
7702 BOOL searchloaded_;
7703 }
7704
7705 - (id) initWithDatabase:(Database *)database;
7706 - (void) setSearchTerm:(NSString *)term;
7707 - (void) reloadData;
7708
7709 @end
7710
7711 @implementation SearchController
7712
7713 - (void) dealloc {
7714 [search_ setDelegate:nil];
7715 [super dealloc];
7716 }
7717
7718 - (NSURL *) navigationURL {
7719 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7720 return [NSURL URLWithString:@"cydia://search"];
7721 else
7722 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7723 }
7724
7725 - (void) setSearchTerm:(NSString *)searchTerm {
7726 [search_ setText:searchTerm];
7727 [self reloadData];
7728 }
7729
7730 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7731 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7732 [search_ resignFirstResponder];
7733 [self reloadData];
7734 }
7735
7736 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7737 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7738 [self reloadData];
7739 }
7740
7741 - (id) initWithDatabase:(Database *)database {
7742 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7743 search_ = [[[UISearchBar alloc] init] autorelease];
7744 [search_ setDelegate:self];
7745 } return self;
7746 }
7747
7748 - (void) viewDidAppear:(BOOL)animated {
7749 [super viewDidAppear:animated];
7750
7751 if (!searchloaded_) {
7752 searchloaded_ = YES;
7753 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7754 [search_ layoutSubviews];
7755 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7756
7757 UITextField *textField;
7758 if ([search_ respondsToSelector:@selector(searchField)])
7759 textField = [search_ searchField];
7760 else
7761 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7762
7763 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7764 [textField setEnablesReturnKeyAutomatically:NO];
7765 [[self navigationItem] setTitleView:textField];
7766 }
7767 }
7768
7769 - (void) reloadData {
7770 [self setObject:[search_ text]];
7771 [self resetCursor];
7772
7773 [super reloadData];
7774 }
7775
7776 - (void) didSelectPackage:(Package *)package {
7777 [search_ resignFirstResponder];
7778 [super didSelectPackage:package];
7779 }
7780
7781 @end
7782 /* }}} */
7783 /* Package Settings Controller {{{ */
7784 @interface PackageSettingsController : CYViewController <
7785 UITableViewDataSource,
7786 UITableViewDelegate
7787 > {
7788 _transient Database *database_;
7789 NSString *name_;
7790 Package *package_;
7791 UITableView *table_;
7792 UISwitch *subscribedSwitch_;
7793 UISwitch *ignoredSwitch_;
7794 UITableViewCell *subscribedCell_;
7795 UITableViewCell *ignoredCell_;
7796 }
7797
7798 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7799
7800 @end
7801
7802 @implementation PackageSettingsController
7803
7804 - (void) dealloc {
7805 [self releaseSubviews];
7806 [name_ release];
7807 [package_ release];
7808
7809 [super dealloc];
7810 }
7811
7812 - (NSURL *) navigationURL {
7813 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7814 }
7815
7816 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7817 if (package_ == nil)
7818 return 0;
7819
7820 if ([package_ installed] == nil)
7821 return 1;
7822 else
7823 return 2;
7824 }
7825
7826 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7827 if (package_ == nil)
7828 return 0;
7829
7830 // both sections contain just one item right now.
7831 return 1;
7832 }
7833
7834 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7835 return nil;
7836 }
7837
7838 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7839 if (section == 0)
7840 return UCLocalize("SHOW_ALL_CHANGES_EX");
7841 else
7842 return UCLocalize("IGNORE_UPGRADES_EX");
7843 }
7844
7845 - (void) onSubscribed:(id)control {
7846 bool value([control isOn]);
7847 if (package_ == nil)
7848 return;
7849 if ([package_ setSubscribed:value])
7850 [delegate_ updateData];
7851 }
7852
7853 - (void) _updateIgnored {
7854 const char *package([name_ UTF8String]);
7855 bool on([ignoredSwitch_ isOn]);
7856
7857 pid_t pid(ExecFork());
7858 if (pid == 0) {
7859 FILE *dpkg(popen("dpkg --set-selections", "w"));
7860 fwrite(package, strlen(package), 1, dpkg);
7861
7862 if (on)
7863 fwrite(" hold\n", 6, 1, dpkg);
7864 else
7865 fwrite(" install\n", 9, 1, dpkg);
7866
7867 pclose(dpkg);
7868
7869 exit(0);
7870 _assert(false);
7871 }
7872
7873 _forever {
7874 int status;
7875 int result(waitpid(pid, &status, 0));
7876
7877 if (result != -1) {
7878 _assert(result == pid);
7879 break;
7880 }
7881 }
7882 }
7883
7884 - (void) onIgnored:(id)control {
7885 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7886 [invocation setTarget:self];
7887 [invocation setSelector:@selector(_updateIgnored)];
7888
7889 [delegate_ reloadDataWithInvocation:invocation];
7890 }
7891
7892 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7893 if (package_ == nil)
7894 return nil;
7895
7896 switch ([indexPath section]) {
7897 case 0: return subscribedCell_;
7898 case 1: return ignoredCell_;
7899
7900 _nodefault
7901 }
7902
7903 return nil;
7904 }
7905
7906 - (void) loadView {
7907 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7908
7909 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7910 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7911 [table_ setDataSource:self];
7912 [table_ setDelegate:self];
7913 [[self view] addSubview:table_];
7914
7915 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7916 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7917 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7918
7919 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7920 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7921 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7922
7923 subscribedCell_ = [[UITableViewCell alloc] init];
7924 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7925 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7926 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7927
7928 ignoredCell_ = [[UITableViewCell alloc] init];
7929 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7930 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7931 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7932 }
7933
7934 - (void) viewDidLoad {
7935 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7936 }
7937
7938 - (void) releaseSubviews {
7939 [ignoredCell_ release];
7940 ignoredCell_ = nil;
7941
7942 [subscribedCell_ release];
7943 subscribedCell_ = nil;
7944
7945 [table_ release];
7946 table_ = nil;
7947
7948 [ignoredSwitch_ release];
7949 ignoredSwitch_ = nil;
7950
7951 [subscribedSwitch_ release];
7952 subscribedSwitch_ = nil;
7953 }
7954
7955 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7956 if ((self = [super init]) != nil) {
7957 database_ = database;
7958 name_ = [package retain];
7959 } return self;
7960 }
7961
7962 - (void) reloadData {
7963 [super reloadData];
7964
7965 if (package_ != nil)
7966 [package_ autorelease];
7967 package_ = [database_ packageWithName:name_];
7968
7969 if (package_ != nil) {
7970 package_ = [package_ retain];
7971 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7972 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7973 } // XXX: what now, G?
7974
7975 [table_ reloadData];
7976 }
7977
7978 @end
7979 /* }}} */
7980
7981 /* Installed Controller {{{ */
7982 @interface InstalledController : FilteredPackageListController {
7983 BOOL expert_;
7984 }
7985
7986 - (id) initWithDatabase:(Database *)database;
7987
7988 - (void) updateRoleButton;
7989 - (void) queueStatusDidChange;
7990
7991 @end
7992
7993 @implementation InstalledController
7994
7995 - (void) dealloc {
7996 [super dealloc];
7997 }
7998
7999 - (NSURL *) navigationURL {
8000 return [NSURL URLWithString:@"cydia://installed"];
8001 }
8002
8003 - (id) initWithDatabase:(Database *)database {
8004 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8005 [self updateRoleButton];
8006 [self queueStatusDidChange];
8007 } return self;
8008 }
8009
8010 #if !AlwaysReload
8011 - (void) queueButtonClicked {
8012 [delegate_ queue];
8013 }
8014 #endif
8015
8016 - (void) queueStatusDidChange {
8017 #if !AlwaysReload
8018 if (IsWildcat_) {
8019 if (Queuing_) {
8020 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8021 initWithTitle:UCLocalize("QUEUE")
8022 style:UIBarButtonItemStyleDone
8023 target:self
8024 action:@selector(queueButtonClicked)
8025 ] autorelease]];
8026 } else {
8027 [[self navigationItem] setLeftBarButtonItem:nil];
8028 }
8029 }
8030 #endif
8031 }
8032
8033 - (void) updateRoleButton {
8034 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8035 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8036 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8037 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8038 target:self
8039 action:@selector(roleButtonClicked)
8040 ] autorelease]];
8041 }
8042
8043 - (void) roleButtonClicked {
8044 [self setObject:[NSNumber numberWithBool:expert_]];
8045 [self reloadData];
8046 expert_ = !expert_;
8047
8048 [self updateRoleButton];
8049 }
8050
8051 @end
8052 /* }}} */
8053
8054 /* Source Cell {{{ */
8055 @interface SourceCell : CYTableViewCell <
8056 ContentDelegate
8057 > {
8058 UIImage *icon_;
8059 NSString *origin_;
8060 NSString *label_;
8061 }
8062
8063 - (void) setSource:(Source *)source;
8064
8065 @end
8066
8067 @implementation SourceCell
8068
8069 - (void) clearSource {
8070 [icon_ release];
8071 [origin_ release];
8072 [label_ release];
8073
8074 icon_ = nil;
8075 origin_ = nil;
8076 label_ = nil;
8077 }
8078
8079 - (void) setSource:(Source *)source {
8080 [self clearSource];
8081
8082 if (icon_ == nil)
8083 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8084 if (icon_ == nil)
8085 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8086 icon_ = [icon_ retain];
8087
8088 origin_ = [[source name] retain];
8089 label_ = [[source uri] retain];
8090
8091 [content_ setNeedsDisplay];
8092 }
8093
8094 - (void) dealloc {
8095 [self clearSource];
8096 [super dealloc];
8097 }
8098
8099 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8100 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8101 UIView *content([self contentView]);
8102 CGRect bounds([content bounds]);
8103
8104 content_ = [[ContentView alloc] initWithFrame:bounds];
8105 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8106 [content_ setBackgroundColor:[UIColor whiteColor]];
8107 [content addSubview:content_];
8108
8109 [content_ setDelegate:self];
8110 [content_ setOpaque:YES];
8111 } return self;
8112 }
8113
8114 - (NSString *) accessibilityLabel {
8115 return label_;
8116 }
8117
8118 - (void) drawContentRect:(CGRect)rect {
8119 bool highlighted(highlighted_);
8120 float width(rect.size.width);
8121
8122 if (icon_ != nil)
8123 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8124
8125 if (highlighted)
8126 UISetColor(White_);
8127
8128 if (!highlighted)
8129 UISetColor(Black_);
8130 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8131
8132 if (!highlighted)
8133 UISetColor(Blue_);
8134 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8135 }
8136
8137 @end
8138 /* }}} */
8139 /* Source Controller {{{ */
8140 @interface SourceController : FilteredPackageListController {
8141 _transient Source *source_;
8142 NSString *key_;
8143 }
8144
8145 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8146
8147 @end
8148
8149 @implementation SourceController
8150
8151 - (NSURL *) navigationURL {
8152 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8153 }
8154
8155 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8156 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8157 source_ = source;
8158 key_ = [[source key] retain];
8159 } return self;
8160 }
8161
8162 - (void) reloadData {
8163 source_ = [database_ sourceWithKey:key_];
8164 [key_ release];
8165 key_ = [[source_ key] retain];
8166 [self setObject:source_];
8167
8168 [[self navigationItem] setTitle:[source_ label]];
8169
8170 [super reloadData];
8171 }
8172
8173 @end
8174 /* }}} */
8175 /* Sources Controller {{{ */
8176 @interface SourcesController : CYViewController <
8177 UITableViewDataSource,
8178 UITableViewDelegate
8179 > {
8180 _transient Database *database_;
8181 UITableView *list_;
8182 NSMutableArray *sources_;
8183 int offset_;
8184
8185 NSString *href_;
8186 UIProgressHUD *hud_;
8187 NSError *error_;
8188
8189 //NSURLConnection *installer_;
8190 NSURLConnection *trivial_;
8191 NSURLConnection *trivial_bz2_;
8192 NSURLConnection *trivial_gz_;
8193 //NSURLConnection *automatic_;
8194
8195 BOOL cydia_;
8196 }
8197
8198 - (id) initWithDatabase:(Database *)database;
8199 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8200
8201 @end
8202
8203 @implementation SourcesController
8204
8205 - (void) _releaseConnection:(NSURLConnection *)connection {
8206 if (connection != nil) {
8207 [connection cancel];
8208 //[connection setDelegate:nil];
8209 [connection release];
8210 }
8211 }
8212
8213 - (void) dealloc {
8214 [self releaseSubviews];
8215
8216 [href_ release];
8217 [hud_ release];
8218 [error_ release];
8219
8220 //[self _releaseConnection:installer_];
8221 [self _releaseConnection:trivial_];
8222 [self _releaseConnection:trivial_gz_];
8223 [self _releaseConnection:trivial_bz2_];
8224 //[self _releaseConnection:automatic_];
8225
8226 [sources_ release];
8227 [super dealloc];
8228 }
8229
8230 - (NSURL *) navigationURL {
8231 return [NSURL URLWithString:@"cydia://sources"];
8232 }
8233
8234 - (void) viewDidAppear:(BOOL)animated {
8235 [super viewDidAppear:animated];
8236 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8237 }
8238
8239 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8240 return offset_ == 0 ? 1 : 2;
8241 }
8242
8243 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8244 switch (section + (offset_ == 0 ? 1 : 0)) {
8245 case 0: return UCLocalize("ENTERED_BY_USER");
8246 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8247
8248 _nodefault
8249 }
8250 }
8251
8252 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8253 int count = [sources_ count];
8254 switch (section) {
8255 case 0: return (offset_ == 0 ? count : offset_);
8256 case 1: return count - offset_;
8257
8258 _nodefault
8259 }
8260 }
8261
8262 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8263 unsigned idx = 0;
8264 switch (indexPath.section) {
8265 case 0: idx = indexPath.row; break;
8266 case 1: idx = indexPath.row + offset_; break;
8267
8268 _nodefault
8269 }
8270 return [sources_ objectAtIndex:idx];
8271 }
8272
8273 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8274 static NSString *cellIdentifier = @"SourceCell";
8275
8276 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8277 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8278 [cell setSource:[self sourceAtIndexPath:indexPath]];
8279 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8280
8281 return cell;
8282 }
8283
8284 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8285 Source *source = [self sourceAtIndexPath:indexPath];
8286
8287 SourceController *controller = [[[SourceController alloc]
8288 initWithDatabase:database_
8289 source:source
8290 ] autorelease];
8291
8292 [controller setDelegate:delegate_];
8293
8294 [[self navigationController] pushViewController:controller animated:YES];
8295 }
8296
8297 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8298 Source *source = [self sourceAtIndexPath:indexPath];
8299 return [source record] != nil;
8300 }
8301
8302 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8303 Source *source = [self sourceAtIndexPath:indexPath];
8304 [Sources_ removeObjectForKey:[source key]];
8305 [delegate_ syncData];
8306 }
8307
8308 - (void) complete {
8309 [delegate_ addTrivialSource:href_];
8310 [delegate_ syncData];
8311 }
8312
8313 - (NSString *) getWarning {
8314 NSString *href(href_);
8315 NSRange colon([href rangeOfString:@"://"]);
8316 if (colon.location != NSNotFound)
8317 href = [href substringFromIndex:(colon.location + 3)];
8318 href = [href stringByAddingPercentEscapes];
8319 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8320 href = [href stringByCachingURLWithCurrentCDN];
8321
8322 NSURL *url([NSURL URLWithString:href]);
8323
8324 NSStringEncoding encoding;
8325 NSError *error(nil);
8326
8327 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8328 return [warning length] == 0 ? nil : warning;
8329 return nil;
8330 }
8331
8332 - (void) _endConnection:(NSURLConnection *)connection {
8333 // XXX: the memory management in this method is horribly awkward
8334
8335 NSURLConnection **field = NULL;
8336 if (connection == trivial_)
8337 field = &trivial_;
8338 else if (connection == trivial_bz2_)
8339 field = &trivial_bz2_;
8340 else if (connection == trivial_gz_)
8341 field = &trivial_gz_;
8342 _assert(field != NULL);
8343 [connection release];
8344 *field = nil;
8345
8346 if (
8347 trivial_ == nil &&
8348 trivial_bz2_ == nil &&
8349 trivial_gz_ == nil
8350 ) {
8351 bool defer(false);
8352
8353 if (cydia_) {
8354 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8355 defer = true;
8356
8357 UIAlertView *alert = [[[UIAlertView alloc]
8358 initWithTitle:UCLocalize("SOURCE_WARNING")
8359 message:warning
8360 delegate:self
8361 cancelButtonTitle:UCLocalize("CANCEL")
8362 otherButtonTitles:
8363 UCLocalize("ADD_ANYWAY"),
8364 nil
8365 ] autorelease];
8366
8367 [alert setContext:@"warning"];
8368 [alert setNumberOfRows:1];
8369 [alert show];
8370 } else
8371 [self complete];
8372 } else if (error_ != nil) {
8373 UIAlertView *alert = [[[UIAlertView alloc]
8374 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8375 message:[error_ localizedDescription]
8376 delegate:self
8377 cancelButtonTitle:UCLocalize("OK")
8378 otherButtonTitles:nil
8379 ] autorelease];
8380
8381 [alert setContext:@"urlerror"];
8382 [alert show];
8383 } else {
8384 UIAlertView *alert = [[[UIAlertView alloc]
8385 initWithTitle:UCLocalize("NOT_REPOSITORY")
8386 message:UCLocalize("NOT_REPOSITORY_EX")
8387 delegate:self
8388 cancelButtonTitle:UCLocalize("OK")
8389 otherButtonTitles:nil
8390 ] autorelease];
8391
8392 [alert setContext:@"trivial"];
8393 [alert show];
8394 }
8395
8396 [delegate_ releaseNetworkActivityIndicator];
8397
8398 [delegate_ removeProgressHUD:hud_];
8399 [hud_ autorelease];
8400 hud_ = nil;
8401
8402 if (!defer) {
8403 [href_ release];
8404 href_ = nil;
8405 }
8406
8407 if (error_ != nil) {
8408 [error_ release];
8409 error_ = nil;
8410 }
8411 }
8412 }
8413
8414 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8415 switch ([response statusCode]) {
8416 case 200:
8417 cydia_ = YES;
8418 }
8419 }
8420
8421 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8422 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8423 if (error_ != nil)
8424 error_ = [error retain];
8425 [self _endConnection:connection];
8426 }
8427
8428 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8429 [self _endConnection:connection];
8430 }
8431
8432 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8433 NSMutableURLRequest *request = [NSMutableURLRequest
8434 requestWithURL:[NSURL URLWithString:href]
8435 cachePolicy:NSURLRequestUseProtocolCachePolicy
8436 timeoutInterval:120.0
8437 ];
8438
8439 [request setHTTPMethod:method];
8440
8441 if (Machine_ != NULL)
8442 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8443 if (UniqueID_ != nil)
8444 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8445
8446 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8447 }
8448
8449 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8450 NSString *context([alert context]);
8451
8452 if ([context isEqualToString:@"source"]) {
8453 switch (button) {
8454 case 1: {
8455 NSString *href = [[alert textField] text];
8456
8457 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8458
8459 if (![href hasSuffix:@"/"])
8460 href_ = [href stringByAppendingString:@"/"];
8461 else
8462 href_ = href;
8463 href_ = [href_ retain];
8464
8465 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8466 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8467 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8468 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8469
8470 cydia_ = false;
8471
8472 // XXX: this is stupid
8473 hud_ = [[delegate_ addProgressHUD] retain];
8474 [hud_ setText:UCLocalize("VERIFYING_URL")];
8475 [delegate_ retainNetworkActivityIndicator];
8476 } break;
8477
8478 case 0:
8479 break;
8480
8481 _nodefault
8482 }
8483
8484 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8485 } else if ([context isEqualToString:@"trivial"])
8486 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8487 else if ([context isEqualToString:@"urlerror"])
8488 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8489 else if ([context isEqualToString:@"warning"]) {
8490 switch (button) {
8491 case 1:
8492 [self complete];
8493 break;
8494
8495 case 0:
8496 break;
8497
8498 _nodefault
8499 }
8500
8501 [href_ release];
8502 href_ = nil;
8503
8504 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8505 }
8506 }
8507
8508 - (void) loadView {
8509 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8510
8511 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8512 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8513 [list_ setRowHeight:56];
8514 [list_ setDataSource:self];
8515 [list_ setDelegate:self];
8516 [[self view] addSubview:list_];
8517 }
8518
8519 - (void) viewDidLoad {
8520 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8521 [self updateButtonsForEditingStatus:NO animated:NO];
8522 }
8523
8524 - (void) releaseSubviews {
8525 [list_ release];
8526 list_ = nil;
8527 }
8528
8529 - (id) initWithDatabase:(Database *)database {
8530 if ((self = [super init]) != nil) {
8531 database_ = database;
8532 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8533 } return self;
8534 }
8535
8536 - (void) reloadData {
8537 [super reloadData];
8538
8539 pkgSourceList list;
8540 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8541 return;
8542
8543 [sources_ removeAllObjects];
8544 [sources_ addObjectsFromArray:[database_ sources]];
8545 _trace();
8546 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8547 _trace();
8548
8549 int count([sources_ count]);
8550 offset_ = 0;
8551 for (int i = 0; i != count; i++) {
8552 if ([[sources_ objectAtIndex:i] record] == nil)
8553 break;
8554 offset_++;
8555 }
8556
8557 [list_ setEditing:NO];
8558 [self updateButtonsForEditingStatus:NO animated:NO];
8559 [list_ reloadData];
8560 }
8561
8562 - (void) showAddSourcePrompt {
8563 UIAlertView *alert = [[[UIAlertView alloc]
8564 initWithTitle:UCLocalize("ENTER_APT_URL")
8565 message:nil
8566 delegate:self
8567 cancelButtonTitle:UCLocalize("CANCEL")
8568 otherButtonTitles:
8569 UCLocalize("ADD_SOURCE"),
8570 nil
8571 ] autorelease];
8572
8573 [alert setContext:@"source"];
8574 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8575
8576 [alert setNumberOfRows:1];
8577 [alert addTextFieldWithValue:@"http://" label:@""];
8578
8579 UITextInputTraits *traits = [[alert textField] textInputTraits];
8580 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8581 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8582 [traits setKeyboardType:UIKeyboardTypeURL];
8583 // XXX: UIReturnKeyDone
8584 [traits setReturnKeyType:UIReturnKeyNext];
8585
8586 [alert show];
8587 }
8588
8589 - (void) addButtonClicked {
8590 [self showAddSourcePrompt];
8591 }
8592
8593 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8594 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8595 initWithTitle:UCLocalize("ADD")
8596 style:UIBarButtonItemStylePlain
8597 target:self
8598 action:@selector(addButtonClicked)
8599 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8600
8601 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8602 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8603 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8604 target:self
8605 action:@selector(editButtonClicked)
8606 ] autorelease] animated:animated];
8607
8608 if (IsWildcat_ && !editing)
8609 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8610 initWithTitle:UCLocalize("SETTINGS")
8611 style:UIBarButtonItemStylePlain
8612 target:self
8613 action:@selector(settingsButtonClicked)
8614 ] autorelease]];
8615 }
8616
8617 - (void) settingsButtonClicked {
8618 [delegate_ showSettings];
8619 }
8620
8621 - (void) editButtonClicked {
8622 [list_ setEditing:![list_ isEditing] animated:YES];
8623
8624 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8625 }
8626
8627 @end
8628 /* }}} */
8629
8630 /* Settings Controller {{{ */
8631 @interface SettingsController : CYViewController <
8632 UITableViewDataSource,
8633 UITableViewDelegate
8634 > {
8635 _transient Database *database_;
8636 // XXX: ok, "roledelegate_"?...
8637 _transient id roledelegate_;
8638 UITableView *table_;
8639 UISegmentedControl *segment_;
8640 UIView *container_;
8641 }
8642
8643 - (void) showDoneButton;
8644 - (void) resizeSegmentedControl;
8645
8646 @end
8647
8648 @implementation SettingsController
8649
8650 - (void) dealloc {
8651 [self releaseSubviews];
8652
8653 [super dealloc];
8654 }
8655
8656 - (void) loadView {
8657 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8658
8659 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8660 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8661 [table_ setDelegate:self];
8662 [table_ setDataSource:self];
8663 [[self view] addSubview:table_];
8664
8665 NSArray *items = [NSArray arrayWithObjects:
8666 UCLocalize("USER"),
8667 UCLocalize("HACKER"),
8668 UCLocalize("DEVELOPER"),
8669 nil];
8670 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8671 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8672 [container_ addSubview:segment_];
8673 }
8674
8675 - (void) viewDidLoad {
8676 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8677
8678 int index = -1;
8679 if ([Role_ isEqualToString:@"User"]) index = 0;
8680 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8681 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8682 if (index != -1) {
8683 [segment_ setSelectedSegmentIndex:index];
8684 [self showDoneButton];
8685 }
8686
8687 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8688 [self resizeSegmentedControl];
8689 }
8690
8691 - (void) releaseSubviews {
8692 [table_ release];
8693 table_ = nil;
8694
8695 [segment_ release];
8696 segment_ = nil;
8697
8698 [container_ release];
8699 container_ = nil;
8700 }
8701
8702 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8703 if ((self = [super init]) != nil) {
8704 database_ = database;
8705 roledelegate_ = delegate;
8706 } return self;
8707 }
8708
8709 - (void) resizeSegmentedControl {
8710 CGFloat width = [[self view] frame].size.width;
8711 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8712 }
8713
8714 - (void) viewWillAppear:(BOOL)animated {
8715 [super viewWillAppear:animated];
8716
8717 [self resizeSegmentedControl];
8718 }
8719
8720 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8721 [self resizeSegmentedControl];
8722 }
8723
8724 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8725 [self resizeSegmentedControl];
8726 }
8727
8728 - (void) save {
8729 NSString *role(nil);
8730
8731 switch ([segment_ selectedSegmentIndex]) {
8732 case 0: role = @"User"; break;
8733 case 1: role = @"Hacker"; break;
8734 case 2: role = @"Developer"; break;
8735
8736 _nodefault
8737 }
8738
8739 if (![role isEqualToString:Role_]) {
8740 bool rolling(Role_ == nil);
8741 Role_ = role;
8742
8743 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8744 Role_, @"Role",
8745 nil];
8746
8747 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8748 Changed_ = true;
8749
8750 if (rolling)
8751 [roledelegate_ loadData];
8752 else
8753 [roledelegate_ updateData];
8754 }
8755 }
8756
8757 - (void) segmentChanged:(UISegmentedControl *)control {
8758 [self showDoneButton];
8759 }
8760
8761 - (void) saveAndClose {
8762 [self save];
8763
8764 [[self navigationItem] setRightBarButtonItem:nil];
8765 [[self navigationController] dismissModalViewControllerAnimated:YES];
8766 }
8767
8768 - (void) doneButtonClicked {
8769 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8770 [spinner startAnimating];
8771 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8772 [[self navigationItem] setRightBarButtonItem:spinItem];
8773
8774 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8775 }
8776
8777 - (void) showDoneButton {
8778 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8779 initWithTitle:UCLocalize("DONE")
8780 style:UIBarButtonItemStyleDone
8781 target:self
8782 action:@selector(doneButtonClicked)
8783 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8784 }
8785
8786 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8787 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8788 return 6;
8789 }
8790
8791 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8792 return 0; // :(
8793 }
8794
8795 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8796 return nil; // This method is required by the protocol.
8797 }
8798
8799 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8800 if (section == 1)
8801 return UCLocalize("ROLE_EX");
8802 if (section == 4)
8803 return [NSString stringWithFormat:
8804 @"%@: %@\n%@: %@\n%@: %@",
8805 UCLocalize("USER"), UCLocalize("USER_EX"),
8806 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8807 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8808 ];
8809 else return nil;
8810 }
8811
8812 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8813 return section == 3 ? 44.0f : 0;
8814 }
8815
8816 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8817 return section == 3 ? container_ : nil;
8818 }
8819
8820 - (void) reloadData {
8821 [super reloadData];
8822
8823 [table_ reloadData];
8824 }
8825
8826 @end
8827 /* }}} */
8828 /* Stash Controller {{{ */
8829 @interface StashController : CYViewController {
8830 UIActivityIndicatorView *spinner_;
8831 UILabel *status_;
8832 UILabel *caption_;
8833 }
8834
8835 @end
8836
8837 @implementation StashController
8838
8839 - (void) dealloc {
8840 [self releaseSubviews];
8841
8842 [super dealloc];
8843 }
8844
8845 - (void) loadView {
8846 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8847 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8848
8849 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8850 CGRect spinrect = [spinner_ frame];
8851 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8852 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8853 [spinner_ setFrame:spinrect];
8854 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8855 [[self view] addSubview:spinner_];
8856 [spinner_ startAnimating];
8857
8858 CGRect captrect;
8859 captrect.size.width = [[self view] frame].size.width;
8860 captrect.size.height = 40.0f;
8861 captrect.origin.x = 0;
8862 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8863 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8864 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8865 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8866 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8867 [caption_ setTextColor:[UIColor whiteColor]];
8868 [caption_ setBackgroundColor:[UIColor clearColor]];
8869 [caption_ setShadowColor:[UIColor blackColor]];
8870 [caption_ setTextAlignment:UITextAlignmentCenter];
8871 [[self view] addSubview:caption_];
8872
8873 CGRect statusrect;
8874 statusrect.size.width = [[self view] frame].size.width;
8875 statusrect.size.height = 30.0f;
8876 statusrect.origin.x = 0;
8877 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8878 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8879 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8880 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8881 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8882 [status_ setTextColor:[UIColor whiteColor]];
8883 [status_ setBackgroundColor:[UIColor clearColor]];
8884 [status_ setShadowColor:[UIColor blackColor]];
8885 [status_ setTextAlignment:UITextAlignmentCenter];
8886 [[self view] addSubview:status_];
8887 }
8888
8889 - (void) releaseSubviews {
8890 [spinner_ release];
8891 spinner_ = nil;
8892
8893 [status_ release];
8894 status_ = nil;
8895
8896 [caption_ release];
8897 caption_ = nil;
8898 }
8899
8900 @end
8901 /* }}} */
8902
8903 @interface Cydia : UIApplication <
8904 ConfirmationControllerDelegate,
8905 DatabaseDelegate,
8906 CydiaDelegate,
8907 UINavigationControllerDelegate,
8908 UITabBarControllerDelegate
8909 > {
8910 // XXX: evaluate all fields for _transient
8911
8912 UIWindow *window_;
8913 CYTabBarController *tabbar_;
8914 CYEmulatedLoadingController *emulated_;
8915
8916 NSMutableArray *essential_;
8917 NSMutableArray *broken_;
8918
8919 Database *database_;
8920
8921 NSURL *starturl_;
8922
8923 unsigned locked_;
8924 unsigned activity_;
8925
8926 StashController *stash_;
8927
8928 bool loaded_;
8929 }
8930
8931 - (void) loadData;
8932
8933 @end
8934
8935 @implementation Cydia
8936
8937 - (void) beginUpdate {
8938 [tabbar_ beginUpdate];
8939 }
8940
8941 - (BOOL) updating {
8942 return [tabbar_ updating];
8943 }
8944
8945 - (void) _loaded {
8946 if ([broken_ count] != 0) {
8947 int count = [broken_ count];
8948
8949 UIAlertView *alert = [[[UIAlertView alloc]
8950 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8951 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8952 delegate:self
8953 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8954 otherButtonTitles:
8955 UCLocalize("TEMPORARY_IGNORE"),
8956 nil
8957 ] autorelease];
8958
8959 [alert setContext:@"fixhalf"];
8960 [alert setNumberOfRows:2];
8961 [alert show];
8962 } else if (!Ignored_ && [essential_ count] != 0) {
8963 int count = [essential_ count];
8964
8965 UIAlertView *alert = [[[UIAlertView alloc]
8966 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8967 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8968 delegate:self
8969 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8970 otherButtonTitles:
8971 UCLocalize("UPGRADE_ESSENTIAL"),
8972 UCLocalize("COMPLETE_UPGRADE"),
8973 nil
8974 ] autorelease];
8975
8976 [alert setContext:@"upgrade"];
8977 [alert show];
8978 }
8979 }
8980
8981 - (void) _saveConfig {
8982 _trace();
8983 MetaFile_.Sync();
8984 _trace();
8985
8986 if (Changed_) {
8987 NSString *error(nil);
8988
8989 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8990 _trace();
8991 NSError *error(nil);
8992 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8993 NSLog(@"failure to save metadata data: %@", error);
8994 _trace();
8995
8996 Changed_ = false;
8997 } else {
8998 NSLog(@"failure to serialize metadata: %@", error);
8999 }
9000 }
9001 }
9002
9003 // Navigation controller for the queuing badge.
9004 - (UINavigationController *) queueNavigationController {
9005 NSArray *controllers = [tabbar_ viewControllers];
9006 return [controllers objectAtIndex:3];
9007 }
9008
9009 - (void) unloadData {
9010 [tabbar_ unloadData];
9011 }
9012
9013 - (void) _updateData {
9014 [self _saveConfig];
9015
9016 [self unloadData];
9017
9018 UINavigationController *navigation = [self queueNavigationController];
9019
9020 id queuedelegate = nil;
9021 if ([[navigation viewControllers] count] > 0)
9022 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9023
9024 [queuedelegate queueStatusDidChange];
9025 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9026 }
9027
9028 - (void) _refreshIfPossible:(NSDate *)update {
9029 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9030
9031 bool recently = false;
9032 if (update != nil) {
9033 NSTimeInterval interval([update timeIntervalSinceNow]);
9034 if (interval <= 0 && interval > -(15*60))
9035 recently = true;
9036 }
9037
9038 // Don't automatic refresh if:
9039 // - We already refreshed recently.
9040 // - We already auto-refreshed this launch.
9041 // - Auto-refresh is disabled.
9042 if (recently || loaded_ || ManualRefresh) {
9043 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9044
9045 // If we are cancelling, we need to make sure it knows it's already loaded.
9046 loaded_ = true;
9047 return;
9048 } else {
9049 // We are going to load, so remember that.
9050 loaded_ = true;
9051 }
9052
9053 SCNetworkReachabilityFlags flags; {
9054 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9055 SCNetworkReachabilityGetFlags(reachability, &flags);
9056 CFRelease(reachability);
9057 }
9058
9059 // XXX: this elaborate mess is what Apple is using to determine this? :(
9060 // XXX: do we care if the user has to intervene? maybe that's ok?
9061 bool reachable(
9062 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9063 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9064 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9065 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9066 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9067 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9068 )
9069 );
9070
9071 // If we can reach the server, auto-refresh!
9072 if (reachable)
9073 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9074
9075 [pool release];
9076 }
9077
9078 - (void) refreshIfPossible {
9079 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9080 }
9081
9082 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9083 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9084 [hud setText:UCLocalize("RELOADING_DATA")];
9085
9086 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9087
9088 if (hud != nil)
9089 [self removeProgressHUD:hud];
9090
9091 size_t changes(0);
9092
9093 [essential_ removeAllObjects];
9094 [broken_ removeAllObjects];
9095
9096 NSArray *packages([database_ packages]);
9097 for (Package *package in packages) {
9098 if ([package half])
9099 [broken_ addObject:package];
9100 if ([package upgradableAndEssential:NO]) {
9101 if ([package essential])
9102 [essential_ addObject:package];
9103 ++changes;
9104 }
9105 }
9106
9107 NSLog(@"changes:#%u", changes);
9108
9109 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9110 if (changes != 0) {
9111 _trace();
9112 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9113 [changesItem setBadgeValue:badge];
9114 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9115 [self setApplicationIconBadgeNumber:changes];
9116 } else {
9117 _trace();
9118 [changesItem setBadgeValue:nil];
9119 [changesItem setAnimatedBadge:NO];
9120 [self setApplicationIconBadgeNumber:0];
9121 }
9122
9123 [self _updateData];
9124
9125 [self refreshIfPossible];
9126 }
9127
9128 - (void) updateData {
9129 [self _updateData];
9130 }
9131
9132 - (void) update_ {
9133 [database_ update];
9134 }
9135
9136 - (void) complete {
9137 @synchronized (self) {
9138 [self _reloadDataWithInvocation:nil];
9139 }
9140 }
9141
9142 - (void) disemulate {
9143 if (emulated_ == nil)
9144 return;
9145
9146 [window_ addSubview:[tabbar_ view]];
9147 [[emulated_ view] removeFromSuperview];
9148 [emulated_ release];
9149 emulated_ = nil;
9150 [window_ setUserInteractionEnabled:YES];
9151 }
9152
9153 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9154 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9155 if (IsWildcat_)
9156 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9157
9158 UIViewController *parent;
9159 if (emulated_ == nil)
9160 parent = tabbar_;
9161 else if (!force)
9162 parent = emulated_;
9163 else {
9164 [self disemulate];
9165 parent = tabbar_;
9166 }
9167
9168 [parent presentModalViewController:navigation animated:YES];
9169 }
9170
9171 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9172 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9173
9174 if (navigation != nil)
9175 [navigation pushViewController:progress animated:YES];
9176 else
9177 [self presentModalViewController:progress force:YES];
9178
9179 [progress invoke:invocation withTitle:title];
9180 return progress;
9181 }
9182
9183 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9184 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9185 }
9186
9187 - (void) repairWithInvocation:(NSInvocation *)invocation {
9188 _trace();
9189 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9190 _trace();
9191 }
9192
9193 - (void) repairWithSelector:(SEL)selector {
9194 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9195 }
9196
9197 - (void) syncData {
9198 [self _saveConfig];
9199
9200 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9201 _assert(file != NULL);
9202
9203 for (NSString *key in [Sources_ allKeys]) {
9204 NSDictionary *source([Sources_ objectForKey:key]);
9205
9206 fprintf(file, "%s %s %s\n",
9207 [[source objectForKey:@"Type"] UTF8String],
9208 [[source objectForKey:@"URI"] UTF8String],
9209 [[source objectForKey:@"Distribution"] UTF8String]
9210 );
9211 }
9212
9213 fclose(file);
9214
9215 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9216
9217 [self complete];
9218 }
9219
9220 - (void) addTrivialSource:(NSString *)href {
9221 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9222 @"deb", @"Type",
9223 href, @"URI",
9224 @"./", @"Distribution",
9225 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9226
9227 Changed_ = true;
9228 }
9229
9230 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9231 @synchronized (self) {
9232 [self _reloadDataWithInvocation:invocation];
9233 }
9234 }
9235
9236 - (void) reloadData {
9237 [self reloadDataWithInvocation:nil];
9238 }
9239
9240 - (void) resolve {
9241 pkgProblemResolver *resolver = [database_ resolver];
9242
9243 resolver->InstallProtect();
9244 if (!resolver->Resolve(true))
9245 _error->Discard();
9246 }
9247
9248 - (bool) perform {
9249 // XXX: this is a really crappy way of doing this.
9250 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9251 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9252 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9253 if ([tabbar_ updating])
9254 [tabbar_ cancelUpdate];
9255
9256 if (![database_ prepare])
9257 return false;
9258
9259 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9260 [page setDelegate:self];
9261 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9262
9263 if (IsWildcat_)
9264 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9265 [tabbar_ presentModalViewController:confirm_ animated:YES];
9266
9267 return true;
9268 }
9269
9270 - (void) queue {
9271 @synchronized (self) {
9272 [self perform];
9273 }
9274 }
9275
9276 - (void) clearPackage:(Package *)package {
9277 @synchronized (self) {
9278 [package clear];
9279 [self resolve];
9280 [self perform];
9281 }
9282 }
9283
9284 - (void) installPackages:(NSArray *)packages {
9285 @synchronized (self) {
9286 for (Package *package in packages)
9287 [package install];
9288 [self resolve];
9289 [self perform];
9290 }
9291 }
9292
9293 - (void) installPackage:(Package *)package {
9294 @synchronized (self) {
9295 [package install];
9296 [self resolve];
9297 [self perform];
9298 }
9299 }
9300
9301 - (void) removePackage:(Package *)package {
9302 @synchronized (self) {
9303 [package remove];
9304 [self resolve];
9305 [self perform];
9306 }
9307 }
9308
9309 - (void) distUpgrade {
9310 @synchronized (self) {
9311 if (![database_ upgrade])
9312 return;
9313 [self perform];
9314 }
9315 }
9316
9317 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9318 Queuing_ = false;
9319 ++locked_;
9320 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9321 --locked_;
9322 [self complete];
9323 }
9324
9325 - (void) showSettings {
9326 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9327 }
9328
9329 - (void) retainNetworkActivityIndicator {
9330 if (activity_++ == 0)
9331 [self setNetworkActivityIndicatorVisible:YES];
9332
9333 #if TraceLogging
9334 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9335 #endif
9336 }
9337
9338 - (void) releaseNetworkActivityIndicator {
9339 if (--activity_ == 0)
9340 [self setNetworkActivityIndicatorVisible:NO];
9341
9342 #if TraceLogging
9343 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9344 #endif
9345
9346 }
9347
9348 - (void) cancelAndClear:(bool)clear {
9349 @synchronized (self) {
9350 if (clear) {
9351 [database_ clear];
9352 Queuing_ = false;
9353 } else {
9354 Queuing_ = true;
9355 }
9356
9357 [self _updateData];
9358 }
9359 }
9360
9361 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9362 NSString *context([alert context]);
9363
9364 if ([context isEqualToString:@"conffile"]) {
9365 FILE *input = [database_ input];
9366 if (button == [alert cancelButtonIndex])
9367 fprintf(input, "N\n");
9368 else if (button == [alert firstOtherButtonIndex])
9369 fprintf(input, "Y\n");
9370 fflush(input);
9371
9372 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9373 } else if ([context isEqualToString:@"fixhalf"]) {
9374 if (button == [alert cancelButtonIndex]) {
9375 @synchronized (self) {
9376 for (Package *broken in broken_) {
9377 [broken remove];
9378
9379 NSString *id = [broken id];
9380 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9381 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9382 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9383 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9384 }
9385
9386 [self resolve];
9387 [self perform];
9388 }
9389 } else if (button == [alert firstOtherButtonIndex]) {
9390 [broken_ removeAllObjects];
9391 [self _loaded];
9392 }
9393
9394 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9395 } else if ([context isEqualToString:@"upgrade"]) {
9396 if (button == [alert firstOtherButtonIndex]) {
9397 @synchronized (self) {
9398 for (Package *essential in essential_)
9399 [essential install];
9400
9401 [self resolve];
9402 [self perform];
9403 }
9404 } else if (button == [alert firstOtherButtonIndex] + 1) {
9405 [self distUpgrade];
9406 } else if (button == [alert cancelButtonIndex]) {
9407 Ignored_ = YES;
9408 }
9409
9410 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9411 }
9412 }
9413
9414 - (void) system:(NSString *)command { _pooled
9415 _trace();
9416 system([command UTF8String]);
9417 _trace();
9418 }
9419
9420 - (void) applicationWillSuspend {
9421 [database_ clean];
9422 [super applicationWillSuspend];
9423 }
9424
9425 - (BOOL) isSafeToSuspend {
9426 if (locked_ != 0) {
9427 #if !ForRelease
9428 NSLog(@"isSafeToSuspend: locked_ != 0");
9429 #endif
9430 return false;
9431 }
9432
9433 // Use external process status API internally.
9434 // This is probably a really bad idea.
9435 // XXX: what is the point of this? does this solve anything at all?
9436 uint64_t status = 0;
9437 int notify_token;
9438 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9439 notify_get_state(notify_token, &status);
9440 notify_cancel(notify_token);
9441 }
9442
9443 if (status != 0) {
9444 #if !ForRelease
9445 NSLog(@"isSafeToSuspend: status != 0");
9446 #endif
9447 return false;
9448 }
9449
9450 #if !ForRelease
9451 NSLog(@"isSafeToSuspend: -> true");
9452 #endif
9453 return true;
9454 }
9455
9456 - (void) applicationSuspend:(__GSEvent *)event {
9457 if ([self isSafeToSuspend])
9458 [super applicationSuspend:event];
9459 }
9460
9461 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9462 if ([self isSafeToSuspend])
9463 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9464 }
9465
9466 - (void) _setSuspended:(BOOL)value {
9467 if ([self isSafeToSuspend])
9468 [super _setSuspended:value];
9469 }
9470
9471 - (UIProgressHUD *) addProgressHUD {
9472 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9473 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9474
9475 [window_ setUserInteractionEnabled:NO];
9476
9477 UIViewController *target(tabbar_);
9478 if (UIViewController *modal = [target modalViewController])
9479 target = modal;
9480
9481 UIView *view([target view]);
9482 [view addSubview:hud];
9483
9484 [hud show:YES];
9485
9486 ++locked_;
9487 return hud;
9488 }
9489
9490 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9491 --locked_;
9492 [hud show:NO];
9493 [hud removeFromSuperview];
9494 [window_ setUserInteractionEnabled:YES];
9495 }
9496
9497 - (CYViewController *) pageForPackage:(NSString *)name {
9498 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9499 }
9500
9501 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9502 NSString *scheme([[url scheme] lowercaseString]);
9503 if ([[url absoluteString] length] <= [scheme length] + 3)
9504 return nil;
9505 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9506 NSArray *components([path pathComponents]);
9507
9508 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9509 return [self pageForPackage:[components objectAtIndex:1]];
9510
9511 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9512 return nil;
9513
9514 NSString *base([components objectAtIndex:0]);
9515
9516 CYViewController *controller = nil;
9517
9518 if ([base isEqualToString:@"url"]) {
9519 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9520 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9521 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9522 } else if (!external && [components count] == 1) {
9523 if ([base isEqualToString:@"manage"]) {
9524 controller = [[[ManageController alloc] init] autorelease];
9525 }
9526
9527 if ([base isEqualToString:@"sources"]) {
9528 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9529 }
9530
9531 if ([base isEqualToString:@"home"]) {
9532 controller = [[[HomeController alloc] init] autorelease];
9533 }
9534
9535 if ([base isEqualToString:@"sections"]) {
9536 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9537 }
9538
9539 if ([base isEqualToString:@"search"]) {
9540 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9541 }
9542
9543 if ([base isEqualToString:@"changes"]) {
9544 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9545 }
9546
9547 if ([base isEqualToString:@"installed"]) {
9548 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9549 }
9550 } else if ([components count] == 2) {
9551 NSString *argument = [components objectAtIndex:1];
9552
9553 if ([base isEqualToString:@"package"]) {
9554 controller = [self pageForPackage:argument];
9555 }
9556
9557 if (!external && [base isEqualToString:@"search"]) {
9558 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9559 [(SearchController *)controller setSearchTerm:argument];
9560 }
9561
9562 if (!external && [base isEqualToString:@"sections"]) {
9563 if ([argument isEqualToString:@"all"])
9564 argument = nil;
9565 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9566 }
9567
9568 if (!external && [base isEqualToString:@"sources"]) {
9569 if ([argument isEqualToString:@"add"]) {
9570 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9571 [(SourcesController *)controller showAddSourcePrompt];
9572 } else {
9573 Source *source = [database_ sourceWithKey:argument];
9574 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9575 }
9576 }
9577
9578 if (!external && [base isEqualToString:@"launch"]) {
9579 [self launchApplicationWithIdentifier:argument suspended:NO];
9580 return nil;
9581 }
9582 } else if (!external && [components count] == 3) {
9583 NSString *arg1 = [components objectAtIndex:1];
9584 NSString *arg2 = [components objectAtIndex:2];
9585
9586 if ([base isEqualToString:@"package"]) {
9587 if ([arg2 isEqualToString:@"settings"]) {
9588 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9589 } else if ([arg2 isEqualToString:@"files"]) {
9590 if (Package *package = [database_ packageWithName:arg1]) {
9591 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9592 [(FileTable *)controller setPackage:package];
9593 }
9594 }
9595 }
9596 }
9597
9598 [controller setDelegate:self];
9599 return controller;
9600 }
9601
9602 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9603 CYViewController *page([self pageForURL:url forExternal:external]);
9604
9605 if (page != nil) {
9606 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9607 [nav setViewControllers:[NSArray arrayWithObject:page]];
9608 [tabbar_ setUnselectedViewController:nav];
9609 }
9610
9611 return page != nil;
9612 }
9613
9614 - (void) applicationOpenURL:(NSURL *)url {
9615 [super applicationOpenURL:url];
9616
9617 if (!loaded_) starturl_ = [url retain];
9618 else [self openCydiaURL:url forExternal:YES];
9619 }
9620
9621 - (void) applicationWillResignActive:(UIApplication *)application {
9622 // Stop refreshing if you get a phone call or lock the device.
9623 if ([tabbar_ updating])
9624 [tabbar_ cancelUpdate];
9625
9626 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9627 [super applicationWillResignActive:application];
9628 }
9629
9630 - (void) applicationWillTerminate:(UIApplication *)application {
9631 Changed_ = true;
9632 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9633 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9634 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9635
9636 [self _saveConfig];
9637 }
9638
9639 - (void) setConfigurationData:(NSString *)data {
9640 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9641
9642 if (!conffile_r(data)) {
9643 lprintf("E:invalid conffile\n");
9644 return;
9645 }
9646
9647 NSString *ofile = conffile_r[1];
9648 //NSString *nfile = conffile_r[2];
9649
9650 UIAlertView *alert = [[[UIAlertView alloc]
9651 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9652 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9653 delegate:self
9654 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9655 otherButtonTitles:
9656 UCLocalize("ACCEPT_NEW_COPY"),
9657 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9658 nil
9659 ] autorelease];
9660
9661 [alert setContext:@"conffile"];
9662 [alert setNumberOfRows:2];
9663 [alert show];
9664 }
9665
9666 - (void) addStashController {
9667 ++locked_;
9668 stash_ = [[StashController alloc] init];
9669 [window_ addSubview:[stash_ view]];
9670 }
9671
9672 - (void) removeStashController {
9673 [[stash_ view] removeFromSuperview];
9674 [stash_ release];
9675 --locked_;
9676 }
9677
9678 - (void) stash {
9679 [self setIdleTimerDisabled:YES];
9680
9681 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9682 UpdateExternalStatus(1);
9683 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9684 UpdateExternalStatus(0);
9685
9686 [self removeStashController];
9687
9688 if (ExecFork() == 0) {
9689 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9690 perror("launchctl stop");
9691 }
9692 }
9693
9694 - (void) setupViewControllers {
9695 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9696
9697 NSMutableArray *items([NSMutableArray arrayWithObjects:
9698 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9699 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9700 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9701 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9702 nil]);
9703
9704 if (IsWildcat_) {
9705 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9706 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9707 } else {
9708 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9709 }
9710
9711 NSMutableArray *controllers([NSMutableArray array]);
9712 for (UITabBarItem *item in items) {
9713 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9714 [controller setTabBarItem:item];
9715 [controllers addObject:controller];
9716 }
9717 [tabbar_ setViewControllers:controllers];
9718
9719 [tabbar_ setUpdateDelegate:self];
9720 }
9721
9722 - (void) applicationDidFinishLaunching:(id)unused {
9723 _trace();
9724 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9725 [self setApplicationSupportsShakeToEdit:NO];
9726
9727 @synchronized (HostConfig_) {
9728 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9729 }
9730
9731 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9732 initWithMemoryCapacity:524288
9733 diskCapacity:10485760
9734 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9735 ] autorelease]];
9736
9737 [CYBrowserController _initialize];
9738
9739 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9740
9741 Font12_ = [[UIFont systemFontOfSize:12] retain];
9742 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9743 Font14_ = [[UIFont systemFontOfSize:14] retain];
9744 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9745 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9746
9747 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9748 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9749
9750 // XXX: I really need this thing... like, seriously... I'm sorry
9751 [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9752
9753 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9754 [window_ orderFront:self];
9755 [window_ makeKey:self];
9756 [window_ setHidden:NO];
9757
9758 if (
9759 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9760 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9761 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9762 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9763 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9764 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9765 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9766 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9767 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9768 false
9769 ) {
9770 [self addStashController];
9771 // XXX: this would be much cleaner as a yieldToSelector:
9772 // that way the removeStashController could happen right here inline
9773 // we also could no longer require the useless stash_ field anymore
9774 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9775 return;
9776 }
9777
9778 database_ = [Database sharedInstance];
9779 [database_ setDelegate:self];
9780
9781 [window_ setUserInteractionEnabled:NO];
9782 [self setupViewControllers];
9783
9784 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9785 [window_ addSubview:[emulated_ view]];
9786
9787 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9788 _trace();
9789 }
9790
9791 - (NSArray *) defaultStartPages {
9792 NSMutableArray *standard = [NSMutableArray array];
9793 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9794 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9795 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9796 if (!IsWildcat_) {
9797 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9798 } else {
9799 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9800 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9801 }
9802 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9803 return standard;
9804 }
9805
9806 - (void) loadData {
9807 _trace();
9808 if (Role_ == nil) {
9809 [window_ setUserInteractionEnabled:YES];
9810 [self showSettings];
9811 return;
9812 } else {
9813 if ([emulated_ modalViewController] != nil)
9814 [emulated_ dismissModalViewControllerAnimated:YES];
9815 [window_ setUserInteractionEnabled:NO];
9816 }
9817
9818 [self reloadData];
9819 PrintTimes();
9820
9821 [self disemulate];
9822
9823 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9824 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9825 int standardIndex = 0;
9826 NSArray *standard = [self defaultStartPages];
9827
9828 BOOL valid = YES;
9829
9830 if (saved == nil)
9831 valid = NO;
9832
9833 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9834 if (valid && closed != nil) {
9835 NSTimeInterval interval([closed timeIntervalSinceNow]);
9836 // XXX: Is 15 minutes the optimal time here?
9837 if (interval > 0 && interval <= -(15*60))
9838 valid = NO;
9839 }
9840
9841 if (valid && [saved count] != [standard count])
9842 valid = NO;
9843
9844 if (valid) {
9845 for (unsigned int i = 0; i < [standard count]; i++) {
9846 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9847 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9848 // but it's good enough for now.
9849 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9850 valid = NO;
9851 break;
9852 }
9853 }
9854 }
9855
9856 NSArray *items = nil;
9857 if (valid) {
9858 [tabbar_ setSelectedIndex:savedIndex];
9859 items = saved;
9860 } else {
9861 [tabbar_ setSelectedIndex:standardIndex];
9862 items = standard;
9863 }
9864
9865 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9866 NSArray *stack = [items objectAtIndex:tab];
9867 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9868 NSMutableArray *current = [NSMutableArray array];
9869
9870 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9871 NSString *addr = [stack objectAtIndex:nav];
9872 NSURL *url = [NSURL URLWithString:addr];
9873 CYViewController *page = [self pageForURL:url forExternal:NO];
9874 if (page != nil)
9875 [current addObject:page];
9876 }
9877
9878 [navigation setViewControllers:current];
9879 }
9880
9881 // (Try to) show the startup URL.
9882 if (starturl_ != nil) {
9883 [self openCydiaURL:starturl_ forExternal:NO];
9884 [starturl_ release];
9885 starturl_ = nil;
9886 }
9887 }
9888
9889 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9890 if (item != nil && IsWildcat_) {
9891 [sheet showFromBarButtonItem:item animated:YES];
9892 } else {
9893 [sheet showInView:window_];
9894 }
9895 }
9896
9897 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9898 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9899 [progress setTitle:task];
9900 [progress addProgressEvent:event];
9901 }
9902
9903 - (void) addProgressEventForTask:(NSArray *)data {
9904 CydiaProgressEvent *event([data objectAtIndex:0]);
9905 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9906 [self addProgressEvent:event forTask:task];
9907 }
9908
9909 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9910 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9911 }
9912
9913 @end
9914
9915 /*IMP alloc_;
9916 id Alloc_(id self, SEL selector) {
9917 id object = alloc_(self, selector);
9918 lprintf("[%s]A-%p\n", self->isa->name, object);
9919 return object;
9920 }*/
9921
9922 /*IMP dealloc_;
9923 id Dealloc_(id self, SEL selector) {
9924 id object = dealloc_(self, selector);
9925 lprintf("[%s]D-%p\n", self->isa->name, object);
9926 return object;
9927 }*/
9928
9929 Class $WebDefaultUIKitDelegate;
9930
9931 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9932 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9933 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9934 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9935 }
9936
9937 static NSSet *MobilizedFiles_;
9938
9939 static NSURL *MobilizeURL(NSURL *url) {
9940 NSString *path([url path]);
9941 if ([path hasPrefix:@"/var/root/"]) {
9942 NSString *file([path substringFromIndex:10]);
9943 if ([MobilizedFiles_ containsObject:file])
9944 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9945 }
9946
9947 return url;
9948 }
9949
9950 Class $CFXPreferencesPropertyListSource;
9951 @class CFXPreferencesPropertyListSource;
9952
9953 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9954 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9955 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9956 url = MobilizeURL(url);
9957 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9958 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9959 url = old;
9960 [pool release];
9961 return value;
9962 }
9963
9964 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9965 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9966 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9967 url = MobilizeURL(url);
9968 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9969 //NSLog(@"%@ %@", [url absoluteString], value);
9970 url = old;
9971 [pool release];
9972 return value;
9973 }
9974
9975 Class $NSURLConnection;
9976
9977 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9978 NSMutableURLRequest *copy([request mutableCopy]);
9979
9980 NSURL *url([copy URL]);
9981 NSString *host([url host]);
9982 NSString *scheme([[url scheme] lowercaseString]);
9983
9984 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9985
9986 @synchronized (HostConfig_) {
9987 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9988 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9989 [copy setHTTPShouldUsePipelining:YES];
9990 }
9991
9992 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9993 } return self;
9994 }
9995
9996 int main(int argc, char *argv[]) { _pooled
9997 _trace();
9998
9999 UpdateExternalStatus(0);
10000
10001 if (Class $UIDevice = objc_getClass("UIDevice")) {
10002 UIDevice *device([$UIDevice currentDevice]);
10003 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10004 } else
10005 IsWildcat_ = false;
10006
10007 UIScreen *screen([UIScreen mainScreen]);
10008 if ([screen respondsToSelector:@selector(scale)])
10009 ScreenScale_ = [screen scale];
10010 else
10011 ScreenScale_ = 1;
10012
10013 UIDevice *device([UIDevice currentDevice]);
10014 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10015 Idiom_ = @"iphone";
10016 else {
10017 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10018 if (idiom == UIUserInterfaceIdiomPhone)
10019 Idiom_ = @"iphone";
10020 else if (idiom == UIUserInterfaceIdiomPad)
10021 Idiom_ = @"ipad";
10022 else
10023 NSLog(@"unknown UIUserInterfaceIdiom!");
10024 }
10025
10026 SessionData_ = [[NSMutableDictionary alloc] initWithCapacity:4];
10027
10028 HostConfig_ = [[NSObject alloc] init];
10029 @synchronized (HostConfig_) {
10030 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10031 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10032 }
10033
10034 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
10035
10036 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10037
10038 MobilizedFiles_ = [NSMutableSet setWithObjects:
10039 @"Library/Preferences/com.apple.Accessibility.plist",
10040 @"Library/Preferences/com.apple.preferences.sounds.plist",
10041 nil];
10042
10043 /* Library Hacks {{{ */
10044 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10045
10046 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10047
10048 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10049 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10050 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10051 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10052 }
10053
10054 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10055 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10056 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10057 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10058 }
10059
10060 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10061 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10062 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10063 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10064 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10065 }
10066
10067 $NSURLConnection = objc_getClass("NSURLConnection");
10068 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10069 if (NSURLConnection$init$ != NULL) {
10070 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10071 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10072 }
10073 /* }}} */
10074 /* Set Locale {{{ */
10075 Locale_ = CFLocaleCopyCurrent();
10076 Languages_ = [NSLocale preferredLanguages];
10077
10078 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10079 //NSLog(@"%@", [Languages_ description]);
10080
10081 const char *lang;
10082 if (Locale_ != NULL)
10083 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10084 else if (Languages_ != nil && [Languages_ count] != 0)
10085 lang = [[Languages_ objectAtIndex:0] UTF8String];
10086 else
10087 // XXX: consider just setting to C and then falling through?
10088 lang = NULL;
10089
10090 if (lang != NULL) {
10091 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10092 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10093 }
10094
10095 NSLog(@"Setting Language: %s", lang);
10096
10097 if (lang != NULL) {
10098 setenv("LANG", lang, true);
10099 std::setlocale(LC_ALL, lang);
10100 }
10101 /* }}} */
10102
10103 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10104
10105 /* Parse Arguments {{{ */
10106 bool substrate(false);
10107
10108 if (argc != 0) {
10109 char **args(argv);
10110 int arge(1);
10111
10112 for (int argi(1); argi != argc; ++argi)
10113 if (strcmp(argv[argi], "--") == 0) {
10114 arge = argi;
10115 argv[argi] = argv[0];
10116 argv += argi;
10117 argc -= argi;
10118 break;
10119 }
10120
10121 for (int argi(1); argi != arge; ++argi)
10122 if (strcmp(args[argi], "--substrate") == 0)
10123 substrate = true;
10124 else
10125 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10126 }
10127 /* }}} */
10128
10129 App_ = [[NSBundle mainBundle] bundlePath];
10130 Advanced_ = YES;
10131
10132 setuid(0);
10133 setgid(0);
10134
10135 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10136 alloc_ = alloc->method_imp;
10137 alloc->method_imp = (IMP) &Alloc_;*/
10138
10139 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10140 dealloc_ = dealloc->method_imp;
10141 dealloc->method_imp = (IMP) &Dealloc_;*/
10142
10143 /* System Information {{{ */
10144 size_t size;
10145
10146 int maxproc;
10147 size = sizeof(maxproc);
10148 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10149 perror("sysctlbyname(\"kern.maxproc\", ?)");
10150 else if (maxproc < 64) {
10151 maxproc = 64;
10152 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10153 perror("sysctlbyname(\"kern.maxproc\", #)");
10154 }
10155
10156 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10157 char *osversion = new char[size];
10158 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10159 perror("sysctlbyname(\"kern.osversion\", ?)");
10160 else
10161 System_ = [NSString stringWithUTF8String:osversion];
10162
10163 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10164 char *machine = new char[size];
10165 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10166 perror("sysctlbyname(\"hw.machine\", ?)");
10167 else
10168 Machine_ = machine;
10169
10170 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10171 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10172 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10173 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10174 CFRelease(serial);
10175 }
10176
10177 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10178 NSData *data((NSData *) ecid);
10179 size_t length([data length]);
10180 uint8_t bytes[length];
10181 [data getBytes:bytes];
10182 char string[length * 2 + 1];
10183 for (size_t i(0); i != length; ++i)
10184 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10185 ChipID_ = [NSString stringWithUTF8String:string];
10186 CFRelease(ecid);
10187 }
10188
10189 IOObjectRelease(service);
10190 }
10191 }
10192
10193 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10194
10195 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10196 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10197 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10198
10199 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10200 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10201 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10202
10203 if (mcc != NULL && mnc != NULL)
10204 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10205
10206 if (mnc != NULL)
10207 CFRelease(mnc);
10208 if (mcc != NULL)
10209 CFRelease(mcc);
10210
10211 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10212 Build_ = [system objectForKey:@"ProductBuildVersion"];
10213 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10214 Product_ = [info objectForKey:@"SafariProductVersion"];
10215 Safari_ = [info objectForKey:@"CFBundleVersion"];
10216 }
10217 /* }}} */
10218 /* Load Database {{{ */
10219 _trace();
10220 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10221 _trace();
10222 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10223
10224 if (Metadata_ == NULL)
10225 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10226 else {
10227 Settings_ = [Metadata_ objectForKey:@"Settings"];
10228
10229 Packages_ = [Metadata_ objectForKey:@"Packages"];
10230 Sections_ = [Metadata_ objectForKey:@"Sections"];
10231 Sources_ = [Metadata_ objectForKey:@"Sources"];
10232
10233 Token_ = [Metadata_ objectForKey:@"Token"];
10234 }
10235
10236 if (Settings_ != nil)
10237 Role_ = [Settings_ objectForKey:@"Role"];
10238
10239 if (Sections_ == nil) {
10240 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10241 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10242 }
10243
10244 if (Sources_ == nil) {
10245 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10246 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10247 }
10248 /* }}} */
10249
10250 _trace();
10251 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10252 _trace();
10253
10254 if (Packages_ != nil) {
10255 bool fail(false);
10256 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10257 _trace();
10258
10259 if (!fail) {
10260 [Metadata_ removeObjectForKey:@"Packages"];
10261 Packages_ = nil;
10262 Changed_ = true;
10263 }
10264 }
10265
10266 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10267
10268 #define MobileSubstrate_(name) \
10269 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10270 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10271 if (handle == NULL) \
10272 NSLog(@"%s", dlerror()); \
10273 }
10274
10275 MobileSubstrate_(Activator)
10276 MobileSubstrate_(libstatusbar)
10277 MobileSubstrate_(SimulatedKeyEvents)
10278 MobileSubstrate_(WinterBoard)
10279
10280 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10281 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10282
10283 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10284
10285 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10286 unlink("/tmp/.cydia.fw");
10287 goto firmware;
10288 } else if (access("/User", F_OK) != 0 || version < 4) {
10289 firmware:
10290 _trace();
10291 system("/usr/libexec/cydia/firmware.sh");
10292 _trace();
10293 }
10294
10295 _assert([[NSFileManager defaultManager]
10296 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10297 withIntermediateDirectories:YES
10298 attributes:nil
10299 error:NULL
10300 ]);
10301
10302 if (access("/tmp/cydia.chk", F_OK) == 0) {
10303 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10304 _assert(errno == ENOENT);
10305 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10306 _assert(errno == ENOENT);
10307 }
10308
10309 /* APT Initialization {{{ */
10310 _assert(pkgInitConfig(*_config));
10311 _assert(pkgInitSystem(*_config, _system));
10312
10313 if (lang != NULL)
10314 _config->Set("APT::Acquire::Translation", lang);
10315
10316 // XXX: this timeout might be important :(
10317 //_config->Set("Acquire::http::Timeout", 15);
10318
10319 _config->Set("Acquire::http::MaxParallel", 3);
10320 /* }}} */
10321 /* Color Choices {{{ */
10322 space_ = CGColorSpaceCreateDeviceRGB();
10323
10324 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10325 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10326 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10327 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10328 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10329 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10330 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10331 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10332 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10333
10334 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10335 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10336 /* }}}*/
10337 /* UIKit Configuration {{{ */
10338 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10339 if ($GSFontSetUseLegacyFontMetrics != NULL)
10340 $GSFontSetUseLegacyFontMetrics(YES);
10341
10342 // XXX: I have a feeling this was important
10343 //UIKeyboardDisableAutomaticAppearance();
10344 /* }}} */
10345
10346 Colon_ = UCLocalize("COLON_DELIMITED");
10347 Elision_ = UCLocalize("ELISION");
10348 Error_ = UCLocalize("ERROR");
10349 Warning_ = UCLocalize("WARNING");
10350
10351 _trace();
10352 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10353
10354 CGColorSpaceRelease(space_);
10355 CFRelease(Locale_);
10356
10357 return value;
10358 }