]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Expose languages and locales to JavaScript.
[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 #if !ForRelease
4027 NSLog(@"div: %@", diverted);
4028 #endif
4029 url = [NSURL URLWithString:diverted];
4030 goto divert;
4031 }
4032
4033 return url;
4034 }
4035
4036 - (NSString *) key {
4037 return key_;
4038 }
4039
4040 - (NSUInteger) hash {
4041 return [key_ hash];
4042 }
4043
4044 - (BOOL) isEqual:(Diversion *)object {
4045 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4046 }
4047
4048 @end
4049
4050 @interface CydiaObject : NSObject {
4051 id indirect_;
4052 _transient id delegate_;
4053 }
4054
4055 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4056
4057 @end
4058
4059 @interface CYBrowserController : BrowserController {
4060 CydiaObject *cydia_;
4061 }
4062
4063 + (void) addDiversion:(Diversion *)diversion;
4064
4065 @end
4066
4067 /* Web Scripting {{{ */
4068 @implementation CydiaObject
4069
4070 - (void) dealloc {
4071 [indirect_ release];
4072 [super dealloc];
4073 }
4074
4075 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4076 if ((self = [super init]) != nil) {
4077 indirect_ = [indirect retain];
4078 } return self;
4079 }
4080
4081 - (void) setDelegate:(id)delegate {
4082 delegate_ = delegate;
4083 }
4084
4085 + (NSArray *) _attributeKeys {
4086 return [NSArray arrayWithObjects:
4087 @"device",
4088 @"ecid",
4089 @"firmware",
4090 @"hostname",
4091 @"idiom",
4092 @"model",
4093 @"plmn",
4094 @"role",
4095 @"serial",
4096 @"token",
4097 @"version",
4098 nil];
4099 }
4100
4101 - (NSArray *) attributeKeys {
4102 return [[self class] _attributeKeys];
4103 }
4104
4105 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4106 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4107 }
4108
4109 - (NSString *) version {
4110 return @ Cydia_;
4111 }
4112
4113 - (NSString *) device {
4114 return [[UIDevice currentDevice] uniqueIdentifier];
4115 }
4116
4117 - (NSString *) firmware {
4118 return [[UIDevice currentDevice] systemVersion];
4119 }
4120
4121 - (NSString *) hostname {
4122 return [[UIDevice currentDevice] name];
4123 }
4124
4125 - (NSString *) idiom {
4126 return (id) Idiom_ ?: [NSNull null];
4127 }
4128
4129 - (NSString *) plmn {
4130 return (id) PLMN_ ?: [NSNull null];
4131 }
4132
4133 - (NSString *) ecid {
4134 return (id) ChipID_ ?: [NSNull null];
4135 }
4136
4137 - (NSString *) serial {
4138 return SerialNumber_;
4139 }
4140
4141 - (NSString *) role {
4142 return (id) Role_ ?: [NSNull null];
4143 }
4144
4145 - (NSString *) model {
4146 return [NSString stringWithUTF8String:Machine_];
4147 }
4148
4149 - (NSString *) token {
4150 return (id) Token_ ?: [NSNull null];
4151 }
4152
4153 + (NSString *) webScriptNameForSelector:(SEL)selector {
4154 if (false);
4155 else if (selector == @selector(addBridgedHost:))
4156 return @"addBridgedHost";
4157 else if (selector == @selector(addPipelinedHost:scheme:))
4158 return @"addPipelinedHost";
4159 else if (selector == @selector(addTrivialSource:))
4160 return @"addTrivialSource";
4161 else if (selector == @selector(close))
4162 return @"close";
4163 else if (selector == @selector(divert::))
4164 return @"divert";
4165 else if (selector == @selector(du:))
4166 return @"du";
4167 else if (selector == @selector(stringWithFormat:arguments:))
4168 return @"format";
4169 else if (selector == @selector(getAllSources))
4170 return @"getAllSourcs";
4171 else if (selector == @selector(getKernelNumber:))
4172 return @"getKernelNumber";
4173 else if (selector == @selector(getKernelString:))
4174 return @"getKernelString";
4175 else if (selector == @selector(getInstalledPackages))
4176 return @"getInstalledPackages";
4177 else if (selector == @selector(getLocaleIdentifier))
4178 return @"getLocaleIdentifier";
4179 else if (selector == @selector(getPreferredLanguages))
4180 return @"getPreferredLanguages";
4181 else if (selector == @selector(getPackageById:))
4182 return @"getPackageById";
4183 else if (selector == @selector(getSessionValue:))
4184 return @"getSessionValue";
4185 else if (selector == @selector(installPackages:))
4186 return @"installPackages";
4187 else if (selector == @selector(localizedStringForKey:value:table:))
4188 return @"localize";
4189 else if (selector == @selector(popViewController:))
4190 return @"popViewController";
4191 else if (selector == @selector(refreshSources))
4192 return @"refreshSources";
4193 else if (selector == @selector(removeButton))
4194 return @"removeButton";
4195 else if (selector == @selector(setSessionValue::))
4196 return @"setSessionValue";
4197 else if (selector == @selector(substitutePackageNames:))
4198 return @"substitutePackageNames";
4199 else if (selector == @selector(scrollToBottom:))
4200 return @"scrollToBottom";
4201 else if (selector == @selector(setAllowsNavigationAction:))
4202 return @"setAllowsNavigationAction";
4203 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4204 return @"setButtonImage";
4205 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4206 return @"setButtonTitle";
4207 else if (selector == @selector(setHidesBackButton:))
4208 return @"setHidesBackButton";
4209 else if (selector == @selector(setHidesNavigationBar:))
4210 return @"setHidesNavigationBar";
4211 else if (selector == @selector(setNavigationBarStyle:))
4212 return @"setNavigationBarStyle";
4213 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4214 return @"setNavigationBarTintColor";
4215 else if (selector == @selector(setToken:))
4216 return @"setToken";
4217 else if (selector == @selector(setViewportWidth:))
4218 return @"setViewportWidth";
4219 else if (selector == @selector(statfs:))
4220 return @"statfs";
4221 else if (selector == @selector(supports:))
4222 return @"supports";
4223 else
4224 return nil;
4225 }
4226
4227 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4228 return [self webScriptNameForSelector:selector] == nil;
4229 }
4230
4231 - (BOOL) supports:(NSString *)feature {
4232 return [feature isEqualToString:@"window.open"];
4233 }
4234
4235 - (void) divert:(NSString *)from :(NSString *)to {
4236 [CYBrowserController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4237 }
4238
4239 - (NSNumber *) getKernelNumber:(NSString *)name {
4240 const char *string([name UTF8String]);
4241
4242 size_t size;
4243 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4244 return (id) [NSNull null];
4245
4246 if (size != sizeof(int))
4247 return (id) [NSNull null];
4248
4249 int value;
4250 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4251 return (id) [NSNull null];
4252
4253 return [NSNumber numberWithInt:value];
4254 }
4255
4256 - (NSString *) getKernelString:(NSString *)name {
4257 const char *string([name UTF8String]);
4258
4259 size_t size;
4260 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4261 return (id) [NSNull null];
4262
4263 char value[size + 1];
4264 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4265 return (id) [NSNull null];
4266
4267 // XXX: just in case you request something ludicrous
4268 value[size] = '\0';
4269
4270 return [NSString stringWithCString:value];
4271 }
4272
4273 - (id) getSessionValue:(NSString *)key {
4274 @synchronized (SessionData_) {
4275 return [SessionData_ objectForKey:key];
4276 } }
4277
4278 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4279 @synchronized (SessionData_) {
4280 if (value == (id) [WebUndefined undefined])
4281 [SessionData_ removeObjectForKey:key];
4282 else
4283 [SessionData_ setObject:value forKey:key];
4284 } }
4285
4286 - (void) addBridgedHost:(NSString *)host {
4287 @synchronized (HostConfig_) {
4288 [BridgedHosts_ addObject:host];
4289 } }
4290
4291 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4292 @synchronized (HostConfig_) {
4293 if (scheme != (id) [WebUndefined undefined])
4294 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4295
4296 [PipelinedHosts_ addObject:host];
4297 } }
4298
4299 - (void) popViewController:(NSNumber *)value {
4300 if (value == (id) [WebUndefined undefined])
4301 value = [NSNumber numberWithBool:YES];
4302 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4303 }
4304
4305 - (void) addTrivialSource:(NSString *)href {
4306 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4307 }
4308
4309 - (void) refreshSources {
4310 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4311 }
4312
4313 - (NSArray *) getAllSources {
4314 return [[Database sharedInstance] sources];
4315 }
4316
4317 - (NSArray *) getInstalledPackages {
4318 Database *database([Database sharedInstance]);
4319 @synchronized (database) {
4320 NSArray *packages([database packages]);
4321 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4322 for (Package *package in packages)
4323 if (![package uninstalled])
4324 [installed addObject:package];
4325 return installed;
4326 } }
4327
4328 - (Package *) getPackageById:(NSString *)id {
4329 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4330 [package parse];
4331 return package;
4332 } else
4333 return (Package *) [NSNull null];
4334 }
4335
4336 - (NSString *) getLocaleIdentifier {
4337 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4338 }
4339
4340 - (NSArray *) getPreferredLanguages {
4341 return Languages_;
4342 }
4343
4344 - (NSArray *) statfs:(NSString *)path {
4345 struct statfs stat;
4346
4347 if (path == nil || statfs([path UTF8String], &stat) == -1)
4348 return nil;
4349
4350 return [NSArray arrayWithObjects:
4351 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4352 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4353 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4354 nil];
4355 }
4356
4357 - (NSNumber *) du:(NSString *)path {
4358 NSNumber *value(nil);
4359
4360 int fds[2];
4361 _assert(pipe(fds) != -1);
4362
4363 pid_t pid(ExecFork());
4364 if (pid == 0) {
4365 _assert(dup2(fds[1], 1) != -1);
4366 _assert(close(fds[0]) != -1);
4367 _assert(close(fds[1]) != -1);
4368 /* XXX: this should probably not use du */
4369 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4370 exit(1);
4371 _assert(false);
4372 }
4373
4374 _assert(close(fds[1]) != -1);
4375
4376 if (FILE *du = fdopen(fds[0], "r")) {
4377 char line[1024];
4378 while (fgets(line, sizeof(line), du) != NULL) {
4379 size_t length(strlen(line));
4380 while (length != 0 && line[length - 1] == '\n')
4381 line[--length] = '\0';
4382 if (char *tab = strchr(line, '\t')) {
4383 *tab = '\0';
4384 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4385 }
4386 }
4387
4388 fclose(du);
4389 } else _assert(close(fds[0]));
4390
4391 int status;
4392 wait:
4393 if (waitpid(pid, &status, 0) == -1)
4394 if (errno == EINTR)
4395 goto wait;
4396 else _assert(false);
4397
4398 return value;
4399 }
4400
4401 - (void) close {
4402 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4403 }
4404
4405 - (void) installPackages:(NSArray *)packages {
4406 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4407 }
4408
4409 - (NSString *) substitutePackageNames:(NSString *)message {
4410 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4411 for (size_t i(0), e([words count]); i != e; ++i) {
4412 NSString *word([words objectAtIndex:i]);
4413 if (Package *package = [[Database sharedInstance] packageWithName:word])
4414 [words replaceObjectAtIndex:i withObject:[package name]];
4415 }
4416
4417 return [words componentsJoinedByString:@" "];
4418 }
4419
4420 - (void) removeButton {
4421 [indirect_ removeButton];
4422 }
4423
4424 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4425 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4426 }
4427
4428 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4429 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4430 }
4431
4432 - (void) setAllowsNavigationAction:(NSString *)value {
4433 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4434 }
4435
4436 - (void) setHidesBackButton:(NSString *)value {
4437 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4438 }
4439
4440 - (void) setHidesNavigationBar:(NSString *)value {
4441 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4442 }
4443
4444 - (void) setNavigationBarStyle:(NSString *)value {
4445 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4446 }
4447
4448 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4449 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4450 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4451 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4452 }
4453
4454 - (void) _setToken:(NSString *)token {
4455 Token_ = token;
4456
4457 if (token == nil)
4458 [Metadata_ removeObjectForKey:@"Token"];
4459 else
4460 [Metadata_ setObject:Token_ forKey:@"Token"];
4461
4462 Changed_ = true;
4463 }
4464
4465 - (void) setToken:(NSString *)token {
4466 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4467 }
4468
4469 - (void) scrollToBottom:(NSNumber *)animated {
4470 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4471 }
4472
4473 - (void) setViewportWidth:(float)width {
4474 [indirect_ setViewportWidthOnMainThread:width];
4475 }
4476
4477 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4478 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4479 unsigned count([arguments count]);
4480 id values[count];
4481 for (unsigned i(0); i != count; ++i)
4482 values[i] = [arguments objectAtIndex:i];
4483 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4484 }
4485
4486 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4487 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4488 value = nil;
4489 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4490 table = nil;
4491 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4492 }
4493
4494 @end
4495 /* }}} */
4496
4497 /* @ Loading... Indicator {{{ */
4498 @interface CYLoadingIndicator : UIView {
4499 _H<UIActivityIndicatorView> spinner_;
4500 _H<UILabel> label_;
4501 _H<UIView> container_;
4502 }
4503
4504 @property (readonly, nonatomic) UILabel *label;
4505 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4506
4507 @end
4508
4509 @implementation CYLoadingIndicator
4510
4511 - (id) initWithFrame:(CGRect)frame {
4512 if ((self = [super initWithFrame:frame]) != nil) {
4513 container_ = [[[UIView alloc] init] autorelease];
4514 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4515
4516 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4517 [spinner_ startAnimating];
4518 [container_ addSubview:spinner_];
4519
4520 label_ = [[[UILabel alloc] init] autorelease];
4521 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4522 [label_ setBackgroundColor:[UIColor clearColor]];
4523 [label_ setTextColor:[UIColor blackColor]];
4524 [label_ setShadowColor:[UIColor whiteColor]];
4525 [label_ setShadowOffset:CGSizeMake(0, 1)];
4526 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4527 [container_ addSubview:label_];
4528
4529 CGSize viewsize = frame.size;
4530 CGSize spinnersize = [spinner_ bounds].size;
4531 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4532 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4533
4534 CGRect containrect = {
4535 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4536 CGSizeMake(bothwidth, spinnersize.height)
4537 };
4538 CGRect textrect = {
4539 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4540 textsize
4541 };
4542 CGRect spinrect = {
4543 CGPointZero,
4544 spinnersize
4545 };
4546
4547 [container_ setFrame:containrect];
4548 [spinner_ setFrame:spinrect];
4549 [label_ setFrame:textrect];
4550 [self addSubview:container_];
4551 } return self;
4552 }
4553
4554 - (UILabel *) label {
4555 return label_;
4556 }
4557
4558 - (UIActivityIndicatorView *) activityIndicatorView {
4559 return spinner_;
4560 }
4561
4562 @end
4563 /* }}} */
4564 /* Emulated Loading Controller {{{ */
4565 @interface CYEmulatedLoadingController : CYViewController {
4566 _transient Database *database_;
4567 _H<CYLoadingIndicator> indicator_;
4568 _H<UITabBar> tabbar_;
4569 _H<UINavigationBar> navbar_;
4570 }
4571
4572 @end
4573
4574 @implementation CYEmulatedLoadingController
4575
4576 - (id) initWithDatabase:(Database *)database {
4577 if ((self = [super init]) != nil) {
4578 database_ = database;
4579 } return self;
4580 }
4581
4582 - (void) loadView {
4583 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4584
4585 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4586 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4587 [[self view] addSubview:table];
4588
4589 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4590 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4591 [[self view] addSubview:indicator_];
4592
4593 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4594 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4595 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4596 [[self view] addSubview:tabbar_];
4597
4598 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4599 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4600 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4601 [[self view] addSubview:navbar_];
4602 }
4603
4604 - (void) releaseSubviews {
4605 indicator_ = nil;
4606 tabbar_ = nil;
4607 navbar_ = nil;
4608 }
4609
4610 @end
4611 /* }}} */
4612
4613 /* Cydia Browser Controller {{{ */
4614 @implementation CYBrowserController
4615
4616 - (void) dealloc {
4617 [cydia_ release];
4618 [super dealloc];
4619 }
4620
4621 - (NSURL *) navigationURL {
4622 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4623 }
4624
4625 + (void) initialize {
4626 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4627 }
4628
4629 + (void) addDiversion:(Diversion *)diversion {
4630 [Diversions_ addObject:diversion];
4631 }
4632
4633 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4634 [super webView:view didClearWindowObject:window forFrame:frame];
4635
4636 WebDataSource *source([frame dataSource]);
4637 NSURLResponse *response([source response]);
4638 NSURL *url([response URL]);
4639 NSString *scheme([[url scheme] lowercaseString]);
4640
4641 bool bridged(false);
4642
4643 @synchronized (HostConfig_) {
4644 if ([scheme isEqualToString:@"file"])
4645 bridged = true;
4646 else if ([scheme isEqualToString:@"https"])
4647 if ([BridgedHosts_ containsObject:[url host]])
4648 bridged = true;
4649 }
4650
4651 if (bridged)
4652 [window setValue:cydia_ forKey:@"cydia"];
4653 }
4654
4655 - (NSURL *) URLWithURL:(NSURL *)url {
4656 return [Diversion divertURL:url];
4657 }
4658
4659 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4660 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4661
4662 if (System_ != NULL)
4663 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4664 if (Machine_ != NULL)
4665 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4666 if (Token_ != nil)
4667 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4668
4669 return copy;
4670 }
4671
4672 - (void) setDelegate:(id)delegate {
4673 [super setDelegate:delegate];
4674 [cydia_ setDelegate:delegate];
4675 }
4676
4677 - (id) init {
4678 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4679 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4680
4681 WebView *webview([[webview_ _documentView] webView]);
4682
4683 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4684
4685 if (Safari_ != nil)
4686 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4687 if (Build_ != nil)
4688 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4689 if (Product_ != nil)
4690 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4691
4692 [webview setApplicationNameForUserAgent:application];
4693 } return self;
4694 }
4695
4696 @end
4697 /* }}} */
4698
4699 // CydiaScript {{{
4700 @interface NSObject (CydiaScript)
4701 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4702 @end
4703
4704 @implementation NSObject (CydiaScript)
4705
4706 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4707 return self;
4708 }
4709
4710 @end
4711
4712 @implementation NSArray (CydiaScript)
4713
4714 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4715 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4716 for (size_t i(0), e([self count]); i != e; ++i)
4717 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4718 return object;
4719 }
4720
4721 @end
4722
4723 @implementation NSDictionary (CydiaScript)
4724
4725 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4726 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4727 for (id i in self)
4728 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4729 return object;
4730 }
4731
4732 @end
4733 // }}}
4734
4735 /* Confirmation Controller {{{ */
4736 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4737 if (!iterator.end())
4738 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4739 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4740 continue;
4741 pkgCache::PkgIterator package(dep.TargetPkg());
4742 if (package.end())
4743 continue;
4744 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4745 return true;
4746 }
4747
4748 return false;
4749 }
4750
4751 @protocol ConfirmationControllerDelegate
4752 - (void) cancelAndClear:(bool)clear;
4753 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4754 - (void) queue;
4755 @end
4756
4757 @interface ConfirmationController : CYBrowserController {
4758 _transient Database *database_;
4759
4760 UIAlertView *essential_;
4761
4762 NSDictionary *changes_;
4763 NSMutableArray *issues_;
4764 NSDictionary *sizes_;
4765
4766 BOOL substrate_;
4767 }
4768
4769 - (id) initWithDatabase:(Database *)database;
4770
4771 @end
4772
4773 @implementation ConfirmationController
4774
4775 - (void) dealloc {
4776 [changes_ release];
4777 [issues_ release];
4778 [sizes_ release];
4779
4780 if (essential_ != nil)
4781 [essential_ release];
4782
4783 [super dealloc];
4784 }
4785
4786 - (void) complete {
4787 if (substrate_)
4788 RestartSubstrate_ = true;
4789 [delegate_ confirmWithNavigationController:[self navigationController]];
4790 }
4791
4792 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4793 NSString *context([alert context]);
4794
4795 if ([context isEqualToString:@"remove"]) {
4796 if (button == [alert cancelButtonIndex])
4797 [self dismissModalViewControllerAnimated:YES];
4798 else if (button == [alert firstOtherButtonIndex]) {
4799 [self complete];
4800 }
4801
4802 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4803 } else if ([context isEqualToString:@"unable"]) {
4804 [self dismissModalViewControllerAnimated:YES];
4805 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4806 } else {
4807 [super alertView:alert clickedButtonAtIndex:button];
4808 }
4809 }
4810
4811 - (void) _doContinue {
4812 [self dismissModalViewControllerAnimated:YES];
4813 [delegate_ cancelAndClear:NO];
4814 }
4815
4816 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4817 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4818 return nil;
4819 }
4820
4821 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4822 [super webView:view didClearWindowObject:window forFrame:frame];
4823
4824 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4825 changes_, @"changes",
4826 issues_, @"issues",
4827 sizes_, @"sizes",
4828 self, @"queue",
4829 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4830 }
4831
4832 - (id) initWithDatabase:(Database *)database {
4833 if ((self = [super init]) != nil) {
4834 database_ = database;
4835
4836 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4837 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4838 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4839 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4840 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4841
4842 bool remove(false);
4843
4844 pkgCacheFile &cache([database_ cache]);
4845 NSArray *packages([database_ packages]);
4846 pkgDepCache::Policy *policy([database_ policy]);
4847
4848 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4849
4850 for (Package *package in packages) {
4851 pkgCache::PkgIterator iterator([package iterator]);
4852 NSString *name([package id]);
4853
4854 if ([package broken]) {
4855 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4856
4857 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4858 name, @"package",
4859 reasons, @"reasons",
4860 nil]];
4861
4862 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4863 if (ver.end())
4864 continue;
4865
4866 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4867 pkgCache::DepIterator start;
4868 pkgCache::DepIterator end;
4869 dep.GlobOr(start, end); // ++dep
4870
4871 if (!cache->IsImportantDep(end))
4872 continue;
4873 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4874 continue;
4875
4876 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4877
4878 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4879 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4880 clauses, @"clauses",
4881 nil]];
4882
4883 _forever {
4884 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4885
4886 pkgCache::PkgIterator target(start.TargetPkg());
4887 if (target->ProvidesList != 0)
4888 reason = @"missing";
4889 else {
4890 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4891 if (!ver.end()) {
4892 reason = @"installed";
4893 installed = [NSString stringWithUTF8String:ver.VerStr()];
4894 } else if (!cache[target].CandidateVerIter(cache).end())
4895 reason = @"uninstalled";
4896 else if (target->ProvidesList == 0)
4897 reason = @"uninstallable";
4898 else
4899 reason = @"virtual";
4900 }
4901
4902 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4903 [NSString stringWithUTF8String:start.CompType()], @"operator",
4904 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4905 nil]);
4906
4907 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4908 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4909 version, @"version",
4910 reason, @"reason",
4911 installed, @"installed",
4912 nil]];
4913
4914 // yes, seriously. (wtf?)
4915 if (start == end)
4916 break;
4917 ++start;
4918 }
4919 }
4920 }
4921
4922 pkgDepCache::StateCache &state(cache[iterator]);
4923
4924 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4925
4926 if (state.NewInstall())
4927 [installs addObject:name];
4928 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4929 [reinstalls addObject:name];
4930 else if (state.Upgrade())
4931 [upgrades addObject:name];
4932 else if (state.Downgrade())
4933 [downgrades addObject:name];
4934 else if (!state.Delete())
4935 continue;
4936 else if (special_r(name))
4937 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4938 [NSNull null], @"package",
4939 [NSArray arrayWithObjects:
4940 [NSDictionary dictionaryWithObjectsAndKeys:
4941 @"Conflicts", @"relationship",
4942 [NSArray arrayWithObjects:
4943 [NSDictionary dictionaryWithObjectsAndKeys:
4944 name, @"package",
4945 [NSNull null], @"version",
4946 @"installed", @"reason",
4947 nil],
4948 nil], @"clauses",
4949 nil],
4950 nil], @"reasons",
4951 nil]];
4952 else {
4953 if ([package essential])
4954 remove = true;
4955 [removes addObject:name];
4956 }
4957
4958 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4959 substrate_ |= DepSubstrate(iterator.CurrentVer());
4960 }
4961
4962 if (!remove)
4963 essential_ = nil;
4964 else if (Advanced_) {
4965 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4966
4967 essential_ = [[UIAlertView alloc]
4968 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4969 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4970 delegate:self
4971 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4972 otherButtonTitles:
4973 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4974 nil
4975 ];
4976
4977 [essential_ setContext:@"remove"];
4978 } else {
4979 essential_ = [[UIAlertView alloc]
4980 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4981 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4982 delegate:self
4983 cancelButtonTitle:UCLocalize("OKAY")
4984 otherButtonTitles:nil
4985 ];
4986
4987 [essential_ setContext:@"unable"];
4988 }
4989
4990 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4991 installs, @"installs",
4992 reinstalls, @"reinstalls",
4993 upgrades, @"upgrades",
4994 downgrades, @"downgrades",
4995 removes, @"removes",
4996 nil];
4997
4998 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4999 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5000 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5001 nil];
5002
5003 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5004
5005 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
5006 initWithTitle:UCLocalize("CANCEL")
5007 style:UIBarButtonItemStylePlain
5008 target:self
5009 action:@selector(cancelButtonClicked)
5010 ] autorelease]];
5011 } return self;
5012 }
5013
5014 #if !AlwaysReload
5015 - (void) applyRightButton {
5016 if ([issues_ count] == 0 && ![self isLoading])
5017 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5018 initWithTitle:UCLocalize("CONFIRM")
5019 style:UIBarButtonItemStyleDone
5020 target:self
5021 action:@selector(confirmButtonClicked)
5022 ] autorelease]];
5023 else
5024 [[self navigationItem] setRightBarButtonItem:nil];
5025 }
5026 #endif
5027
5028 - (void) cancelButtonClicked {
5029 [self dismissModalViewControllerAnimated:YES];
5030 [delegate_ cancelAndClear:YES];
5031 }
5032
5033 #if !AlwaysReload
5034 - (void) confirmButtonClicked {
5035 if (essential_ != nil)
5036 [essential_ show];
5037 else
5038 [self complete];
5039 }
5040 #endif
5041
5042 @end
5043 /* }}} */
5044
5045 /* Progress Data {{{ */
5046 @interface CydiaProgressData : NSObject {
5047 _transient id delegate_;
5048
5049 bool running_;
5050 float percent_;
5051
5052 float current_;
5053 float total_;
5054 float speed_;
5055
5056 _H<NSMutableArray> events_;
5057 _H<NSString> title_;
5058
5059 _H<NSString> status_;
5060 _H<NSString> finish_;
5061 }
5062
5063 @end
5064
5065 @implementation CydiaProgressData
5066
5067 + (NSArray *) _attributeKeys {
5068 return [NSArray arrayWithObjects:
5069 @"current",
5070 @"events",
5071 @"finish",
5072 @"percent",
5073 @"running",
5074 @"speed",
5075 @"title",
5076 @"total",
5077 nil];
5078 }
5079
5080 - (NSArray *) attributeKeys {
5081 return [[self class] _attributeKeys];
5082 }
5083
5084 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5085 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5086 }
5087
5088 - (id) init {
5089 if ((self = [super init]) != nil) {
5090 events_ = [NSMutableArray arrayWithCapacity:32];
5091 } return self;
5092 }
5093
5094 - (void) setDelegate:(id)delegate {
5095 delegate_ = delegate;
5096 }
5097
5098 - (void) setPercent:(float)value {
5099 percent_ = value;
5100 }
5101
5102 - (NSNumber *) percent {
5103 return [NSNumber numberWithFloat:percent_];
5104 }
5105
5106 - (void) setCurrent:(float)value {
5107 current_ = value;
5108 }
5109
5110 - (NSNumber *) current {
5111 return [NSNumber numberWithFloat:current_];
5112 }
5113
5114 - (void) setTotal:(float)value {
5115 total_ = value;
5116 }
5117
5118 - (NSNumber *) total {
5119 return [NSNumber numberWithFloat:total_];
5120 }
5121
5122 - (void) setSpeed:(float)value {
5123 speed_ = value;
5124 }
5125
5126 - (NSNumber *) speed {
5127 return [NSNumber numberWithFloat:speed_];
5128 }
5129
5130 - (NSArray *) events {
5131 return events_;
5132 }
5133
5134 - (void) removeAllEvents {
5135 [events_ removeAllObjects];
5136 }
5137
5138 - (void) addEvent:(CydiaProgressEvent *)event {
5139 [events_ addObject:event];
5140 }
5141
5142 - (void) setTitle:(NSString *)text {
5143 title_ = text;
5144 }
5145
5146 - (NSString *) title {
5147 return title_;
5148 }
5149
5150 - (void) setFinish:(NSString *)text {
5151 finish_ = text;
5152 }
5153
5154 - (NSString *) finish {
5155 return (id) finish_ ?: [NSNull null];
5156 }
5157
5158 - (void) setRunning:(bool)running {
5159 running_ = running;
5160 }
5161
5162 - (NSNumber *) running {
5163 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5164 }
5165
5166 @end
5167 /* }}} */
5168 /* Progress Controller {{{ */
5169 @interface ProgressController : CYBrowserController <
5170 ProgressDelegate
5171 > {
5172 _transient Database *database_;
5173 _H<CydiaProgressData> progress_;
5174 unsigned cancel_;
5175 }
5176
5177 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5178
5179 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5180
5181 - (void) setTitle:(NSString *)title;
5182 - (void) setCancellable:(bool)cancellable;
5183
5184 @end
5185
5186 @implementation ProgressController
5187
5188 - (void) dealloc {
5189 [database_ setProgressDelegate:nil];
5190 [progress_ setDelegate:nil];
5191 [super dealloc];
5192 }
5193
5194 - (void) updateCancel {
5195 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5196 initWithTitle:UCLocalize("CANCEL")
5197 style:UIBarButtonItemStylePlain
5198 target:self
5199 action:@selector(cancel)
5200 ] autorelease] : nil)];
5201 }
5202
5203 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5204 if ((self = [super init]) != nil) {
5205 database_ = database;
5206 delegate_ = delegate;
5207
5208 [database_ setProgressDelegate:self];
5209
5210 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5211 [progress_ setDelegate:self];
5212
5213 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5214
5215 [scroller_ setBackgroundColor:[UIColor blackColor]];
5216
5217 [[self navigationItem] setHidesBackButton:YES];
5218
5219 [self updateCancel];
5220 } return self;
5221 }
5222
5223 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5224 [super webView:view didClearWindowObject:window forFrame:frame];
5225 [window setValue:progress_ forKey:@"cydiaProgress"];
5226 }
5227
5228 - (void) updateProgress {
5229 [self dispatchEvent:@"CydiaProgressUpdate"];
5230 }
5231
5232 - (void) viewWillAppear:(BOOL)animated {
5233 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5234 [super viewWillAppear:animated];
5235 }
5236
5237 - (void) close {
5238 UpdateExternalStatus(0);
5239
5240 switch (Finish_) {
5241 case 0:
5242 break;
5243
5244 case 1:
5245 [delegate_ terminateWithSuccess];
5246 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5247 [delegate_ suspendWithAnimation:YES];
5248 else
5249 [delegate_ suspend];*/
5250 break;
5251
5252 case 2:
5253 _trace();
5254 goto reload;
5255
5256 case 3:
5257 _trace();
5258 goto reload;
5259
5260 reload:
5261 system("/usr/bin/sbreload");
5262 _trace();
5263 break;
5264
5265 case 4:
5266 _trace();
5267 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5268 SBReboot(SBSSpringBoardServerPort());
5269 else
5270 reboot2(RB_AUTOBOOT);
5271 break;
5272 }
5273
5274 [super close];
5275 }
5276
5277 - (void) setTitle:(NSString *)title {
5278 [progress_ setTitle:title];
5279 [self updateProgress];
5280 }
5281
5282 - (UIBarButtonItem *) rightButton {
5283 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5284 initWithTitle:UCLocalize("CLOSE")
5285 style:UIBarButtonItemStylePlain
5286 target:self
5287 action:@selector(close)
5288 ] autorelease];
5289 }
5290
5291 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5292 UpdateExternalStatus(1);
5293
5294 [progress_ setRunning:true];
5295 [self setTitle:title];
5296 // implicit updateProgress
5297
5298 SHA1SumValue notifyconf; {
5299 FileFd file;
5300 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5301 _error->Discard();
5302 else {
5303 MMap mmap(file, MMap::ReadOnly);
5304 SHA1Summation sha1;
5305 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5306 notifyconf = sha1.Result();
5307 }
5308 }
5309
5310 SHA1SumValue springlist; {
5311 FileFd file;
5312 if (!file.Open(SpringBoard_, 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 springlist = sha1.Result();
5319 }
5320 }
5321
5322 if (invocation != nil) {
5323 [invocation yieldToSelector:@selector(invoke)];
5324 [self setTitle:@"COMPLETE"];
5325 }
5326
5327 if (Finish_ < 4) {
5328 FileFd file;
5329 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5330 _error->Discard();
5331 else {
5332 MMap mmap(file, MMap::ReadOnly);
5333 SHA1Summation sha1;
5334 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5335 if (!(notifyconf == sha1.Result()))
5336 Finish_ = 4;
5337 }
5338 }
5339
5340 if (Finish_ < 3) {
5341 FileFd file;
5342 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5343 _error->Discard();
5344 else {
5345 MMap mmap(file, MMap::ReadOnly);
5346 SHA1Summation sha1;
5347 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5348 if (!(springlist == sha1.Result()))
5349 Finish_ = 3;
5350 }
5351 }
5352
5353 if (Finish_ < 2) {
5354 if (RestartSubstrate_)
5355 Finish_ = 2;
5356 }
5357
5358 RestartSubstrate_ = false;
5359
5360 switch (Finish_) {
5361 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5362 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5363 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5364 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5365 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5366 }
5367
5368 _trace();
5369 system("su -c /usr/bin/uicache mobile");
5370 _trace();
5371
5372 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5373
5374 [progress_ setRunning:false];
5375 [self updateProgress];
5376
5377 [self applyRightButton];
5378 }
5379
5380 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5381 [progress_ addEvent:event];
5382 [self updateProgress];
5383 }
5384
5385 - (bool) isProgressCancelled {
5386 return cancel_ == 2;
5387 }
5388
5389 - (void) cancel {
5390 cancel_ = 2;
5391 [self updateCancel];
5392 }
5393
5394 - (void) setCancellable:(bool)cancellable {
5395 unsigned cancel(cancel_);
5396
5397 if (!cancellable)
5398 cancel_ = 0;
5399 else if (cancel_ == 0)
5400 cancel_ = 1;
5401
5402 if (cancel != cancel_)
5403 [self updateCancel];
5404 }
5405
5406 - (void) setProgressCancellable:(NSNumber *)cancellable {
5407 [self setCancellable:[cancellable boolValue]];
5408 }
5409
5410 - (void) setProgressPercent:(NSNumber *)percent {
5411 [progress_ setPercent:[percent floatValue]];
5412 [self updateProgress];
5413 }
5414
5415 - (void) setProgressStatus:(NSDictionary *)status {
5416 if (status == nil) {
5417 [progress_ setCurrent:0];
5418 [progress_ setTotal:0];
5419 [progress_ setSpeed:0];
5420 } else {
5421 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5422
5423 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5424 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5425 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5426 }
5427
5428 [self updateProgress];
5429 }
5430
5431 @end
5432 /* }}} */
5433
5434 /* Cell Content View {{{ */
5435 @protocol ContentDelegate
5436 - (void) drawContentRect:(CGRect)rect;
5437 @end
5438
5439 @interface ContentView : UIView {
5440 _transient id<ContentDelegate> delegate_;
5441 }
5442
5443 @end
5444
5445 @implementation ContentView
5446
5447 - (id) initWithFrame:(CGRect)frame {
5448 if ((self = [super initWithFrame:frame]) != nil) {
5449 [self setNeedsDisplayOnBoundsChange:YES];
5450 } return self;
5451 }
5452
5453 - (void) setDelegate:(id<ContentDelegate>)delegate {
5454 delegate_ = delegate;
5455 }
5456
5457 - (void) drawRect:(CGRect)rect {
5458 [super drawRect:rect];
5459 [delegate_ drawContentRect:rect];
5460 }
5461
5462 @end
5463 /* }}} */
5464 /* Cydia TableView Cell {{{ */
5465 @interface CYTableViewCell : UITableViewCell {
5466 ContentView *content_;
5467 bool highlighted_;
5468 }
5469
5470 @end
5471
5472 @implementation CYTableViewCell
5473
5474 - (void) dealloc {
5475 [content_ release];
5476 [super dealloc];
5477 }
5478
5479 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5480 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5481
5482 if (view == content_) {
5483 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5484 highlighted_ = highlighted;
5485 }
5486
5487 [super _updateHighlightColorsForView:view highlighted:highlighted];
5488 }
5489
5490 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5491 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5492 highlighted_ = selected;
5493
5494 [super setSelected:selected animated:animated];
5495 [content_ setNeedsDisplay];
5496 }
5497
5498 @end
5499 /* }}} */
5500
5501 /* Package Cell {{{ */
5502 @interface PackageCell : CYTableViewCell <
5503 ContentDelegate
5504 > {
5505 UIImage *icon_;
5506 NSString *name_;
5507 NSString *description_;
5508 bool commercial_;
5509 NSString *source_;
5510 UIImage *badge_;
5511 Package *package_;
5512 UIImage *placard_;
5513 }
5514
5515 - (PackageCell *) init;
5516 - (void) setPackage:(Package *)package;
5517
5518 - (void) drawContentRect:(CGRect)rect;
5519
5520 @end
5521
5522 @implementation PackageCell
5523
5524 - (void) clearPackage {
5525 if (icon_ != nil) {
5526 [icon_ release];
5527 icon_ = nil;
5528 }
5529
5530 if (name_ != nil) {
5531 [name_ release];
5532 name_ = nil;
5533 }
5534
5535 if (description_ != nil) {
5536 [description_ release];
5537 description_ = nil;
5538 }
5539
5540 if (source_ != nil) {
5541 [source_ release];
5542 source_ = nil;
5543 }
5544
5545 if (badge_ != nil) {
5546 [badge_ release];
5547 badge_ = nil;
5548 }
5549
5550 if (placard_ != nil) {
5551 [placard_ release];
5552 placard_ = nil;
5553 }
5554
5555 [package_ release];
5556 package_ = nil;
5557 }
5558
5559 - (void) dealloc {
5560 [self clearPackage];
5561 [super dealloc];
5562 }
5563
5564 - (PackageCell *) init {
5565 CGRect frame(CGRectMake(0, 0, 320, 74));
5566 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5567 UIView *content([self contentView]);
5568 CGRect bounds([content bounds]);
5569
5570 content_ = [[ContentView alloc] initWithFrame:bounds];
5571 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5572 [content addSubview:content_];
5573
5574 [content_ setDelegate:self];
5575 [content_ setOpaque:YES];
5576 } return self;
5577 }
5578
5579 - (NSString *) accessibilityLabel {
5580 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5581 }
5582
5583 - (void) setPackage:(Package *)package {
5584 [self clearPackage];
5585 [package parse];
5586
5587 Source *source = [package source];
5588
5589 icon_ = [[package icon] retain];
5590 name_ = [[package name] retain];
5591
5592 if (IsWildcat_)
5593 description_ = [package longDescription];
5594 if (description_ == nil)
5595 description_ = [package shortDescription];
5596 if (description_ != nil)
5597 description_ = [description_ retain];
5598
5599 commercial_ = [package isCommercial];
5600
5601 package_ = [package retain];
5602
5603 NSString *label = nil;
5604 bool trusted = false;
5605
5606 if (source != nil) {
5607 label = [source label];
5608 trusted = [source trusted];
5609 } else if ([[package id] isEqualToString:@"firmware"])
5610 label = UCLocalize("APPLE");
5611 else
5612 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5613
5614 NSString *from(label);
5615
5616 NSString *section = [package simpleSection];
5617 if (section != nil && ![section isEqualToString:label]) {
5618 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5619 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5620 }
5621
5622 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5623 source_ = [from retain];
5624
5625 if (NSString *purpose = [package primaryPurpose])
5626 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5627 badge_ = [badge_ retain];
5628
5629 UIColor *color;
5630 NSString *placard;
5631
5632 if (NSString *mode = [package_ mode]) {
5633 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5634 color = RemovingColor_;
5635 //placard = @"removing";
5636 } else {
5637 color = InstallingColor_;
5638 //placard = @"installing";
5639 }
5640
5641 // XXX: the removing/installing placards are not @2x
5642 placard = nil;
5643 } else {
5644 color = [UIColor whiteColor];
5645
5646 if ([package installed] != nil)
5647 placard = @"installed";
5648 else
5649 placard = nil;
5650 }
5651
5652 [content_ setBackgroundColor:color];
5653
5654 if (placard != nil)
5655 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5656 placard_ = [placard_ retain];
5657
5658 [self setNeedsDisplay];
5659 [content_ setNeedsDisplay];
5660 }
5661
5662 - (void) drawContentRect:(CGRect)rect {
5663 bool highlighted(highlighted_);
5664 float width([self bounds].size.width);
5665
5666 #if 0
5667 CGContextRef context(UIGraphicsGetCurrentContext());
5668 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5669 CGContextFillRect(context, rect);
5670 #endif
5671
5672 if (icon_ != nil) {
5673 CGRect rect;
5674 rect.size = [icon_ size];
5675
5676 rect.size.width /= 2;
5677 rect.size.height /= 2;
5678
5679 rect.origin.x = 25 - rect.size.width / 2;
5680 rect.origin.y = 25 - rect.size.height / 2;
5681
5682 [icon_ drawInRect:rect];
5683 }
5684
5685 if (badge_ != nil) {
5686 CGRect rect;
5687 rect.size = [badge_ size];
5688
5689 rect.size.width /= 2;
5690 rect.size.height /= 2;
5691
5692 rect.origin.x = 36 - rect.size.width / 2;
5693 rect.origin.y = 36 - rect.size.height / 2;
5694
5695 [badge_ drawInRect:rect];
5696 }
5697
5698 if (highlighted)
5699 UISetColor(White_);
5700
5701 if (!highlighted)
5702 UISetColor(commercial_ ? Purple_ : Black_);
5703 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5704 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5705
5706 if (!highlighted)
5707 UISetColor(commercial_ ? Purplish_ : Gray_);
5708 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5709
5710 if (placard_ != nil)
5711 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5712 }
5713
5714 @end
5715 /* }}} */
5716 /* Section Cell {{{ */
5717 @interface SectionCell : CYTableViewCell <
5718 ContentDelegate
5719 > {
5720 NSString *basic_;
5721 NSString *section_;
5722 NSString *name_;
5723 NSString *count_;
5724 UIImage *icon_;
5725 UISwitch *switch_;
5726 BOOL editing_;
5727 }
5728
5729 - (void) setSection:(Section *)section editing:(BOOL)editing;
5730
5731 @end
5732
5733 @implementation SectionCell
5734
5735 - (void) clearSection {
5736 if (basic_ != nil) {
5737 [basic_ release];
5738 basic_ = nil;
5739 }
5740
5741 if (section_ != nil) {
5742 [section_ release];
5743 section_ = nil;
5744 }
5745
5746 if (name_ != nil) {
5747 [name_ release];
5748 name_ = nil;
5749 }
5750
5751 if (count_ != nil) {
5752 [count_ release];
5753 count_ = nil;
5754 }
5755 }
5756
5757 - (void) dealloc {
5758 [self clearSection];
5759 [icon_ release];
5760 [switch_ release];
5761 [super dealloc];
5762 }
5763
5764 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5765 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5766 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5767 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5768 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5769
5770 UIView *content([self contentView]);
5771 CGRect bounds([content bounds]);
5772
5773 content_ = [[ContentView alloc] initWithFrame:bounds];
5774 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5775 [content addSubview:content_];
5776 [content_ setBackgroundColor:[UIColor whiteColor]];
5777
5778 [content_ setDelegate:self];
5779 } return self;
5780 }
5781
5782 - (void) onSwitch:(id)sender {
5783 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5784 if (metadata == nil) {
5785 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5786 [Sections_ setObject:metadata forKey:basic_];
5787 }
5788
5789 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5790 Changed_ = true;
5791 }
5792
5793 - (void) setSection:(Section *)section editing:(BOOL)editing {
5794 if (editing != editing_) {
5795 if (editing_)
5796 [switch_ removeFromSuperview];
5797 else
5798 [self addSubview:switch_];
5799 editing_ = editing;
5800 }
5801
5802 [self clearSection];
5803
5804 if (section == nil) {
5805 name_ = [UCLocalize("ALL_PACKAGES") retain];
5806 count_ = nil;
5807 } else {
5808 basic_ = [section name];
5809 if (basic_ != nil)
5810 basic_ = [basic_ retain];
5811
5812 section_ = [section localized];
5813 if (section_ != nil)
5814 section_ = [section_ retain];
5815
5816 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5817 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5818
5819 if (editing_)
5820 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5821 }
5822
5823 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5824 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5825
5826 [content_ setNeedsDisplay];
5827 }
5828
5829 - (void) setFrame:(CGRect)frame {
5830 [super setFrame:frame];
5831
5832 CGRect rect([switch_ frame]);
5833 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5834 }
5835
5836 - (NSString *) accessibilityLabel {
5837 return name_;
5838 }
5839
5840 - (void) drawContentRect:(CGRect)rect {
5841 bool highlighted(highlighted_ && !editing_);
5842
5843 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5844
5845 if (highlighted)
5846 UISetColor(White_);
5847
5848 float width(rect.size.width);
5849 if (editing_)
5850 width -= 87;
5851
5852 if (!highlighted)
5853 UISetColor(Black_);
5854 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5855
5856 CGSize size = [count_ sizeWithFont:Font14_];
5857
5858 UISetColor(White_);
5859 if (count_ != nil)
5860 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5861 }
5862
5863 @end
5864 /* }}} */
5865
5866 /* File Table {{{ */
5867 @interface FileTable : CYViewController <
5868 UITableViewDataSource,
5869 UITableViewDelegate
5870 > {
5871 _transient Database *database_;
5872 Package *package_;
5873 NSString *name_;
5874 NSMutableArray *files_;
5875 UITableView *list_;
5876 }
5877
5878 - (id) initWithDatabase:(Database *)database;
5879 - (void) setPackage:(Package *)package;
5880
5881 @end
5882
5883 @implementation FileTable
5884
5885 - (void) dealloc {
5886 [self releaseSubviews];
5887
5888 [package_ release];
5889 [name_ release];
5890 [files_ release];
5891
5892 [super dealloc];
5893 }
5894
5895 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5896 return files_ == nil ? 0 : [files_ count];
5897 }
5898
5899 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5900 return 24.0f;
5901 }*/
5902
5903 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5904 static NSString *reuseIdentifier = @"Cell";
5905
5906 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5907 if (cell == nil) {
5908 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5909 [cell setFont:[UIFont systemFontOfSize:16]];
5910 }
5911 [cell setText:[files_ objectAtIndex:indexPath.row]];
5912 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5913
5914 return cell;
5915 }
5916
5917 - (NSURL *) navigationURL {
5918 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5919 }
5920
5921 - (void) loadView {
5922 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5923
5924 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5925 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5926 [list_ setRowHeight:24.0f];
5927 [list_ setDataSource:self];
5928 [list_ setDelegate:self];
5929 [[self view] addSubview:list_];
5930 }
5931
5932 - (void) viewDidLoad {
5933 [super viewDidLoad];
5934
5935 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5936 }
5937
5938 - (void) releaseSubviews {
5939 [list_ release];
5940 list_ = nil;
5941 }
5942
5943 - (id) initWithDatabase:(Database *)database {
5944 if ((self = [super init]) != nil) {
5945 database_ = database;
5946
5947 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5948 } return self;
5949 }
5950
5951 - (void) setPackage:(Package *)package {
5952 if (package_ != nil) {
5953 [package_ autorelease];
5954 package_ = nil;
5955 }
5956
5957 if (name_ != nil) {
5958 [name_ release];
5959 name_ = nil;
5960 }
5961
5962 [files_ removeAllObjects];
5963
5964 if (package != nil) {
5965 package_ = [package retain];
5966 name_ = [[package id] retain];
5967
5968 if (NSArray *files = [package files])
5969 [files_ addObjectsFromArray:files];
5970
5971 if ([files_ count] != 0) {
5972 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5973 [files_ removeObjectAtIndex:0];
5974 [files_ sortUsingSelector:@selector(compareByPath:)];
5975
5976 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5977 [stack addObject:@"/"];
5978
5979 for (int i(0), e([files_ count]); i != e; ++i) {
5980 NSString *file = [files_ objectAtIndex:i];
5981 while (![file hasPrefix:[stack lastObject]])
5982 [stack removeLastObject];
5983 NSString *directory = [stack lastObject];
5984 [stack addObject:[file stringByAppendingString:@"/"]];
5985 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5986 ([stack count] - 2) * 3, "",
5987 [file substringFromIndex:[directory length]]
5988 ]];
5989 }
5990 }
5991 }
5992
5993 [list_ reloadData];
5994 }
5995
5996 - (void) reloadData {
5997 [super reloadData];
5998
5999 [self setPackage:[database_ packageWithName:name_]];
6000 }
6001
6002 @end
6003 /* }}} */
6004 /* Package Controller {{{ */
6005 @interface CYPackageController : CYBrowserController <
6006 UIActionSheetDelegate
6007 > {
6008 _transient Database *database_;
6009 _H<Package> package_;
6010 _H<NSString> name_;
6011 bool commercial_;
6012 _H<NSMutableArray> buttons_;
6013 _H<UIBarButtonItem> button_;
6014 }
6015
6016 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
6017
6018 @end
6019
6020 @implementation CYPackageController
6021
6022 - (NSURL *) navigationURL {
6023 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6024 }
6025
6026 /* XXX: this is not safe at all... localization of /fail/ */
6027 - (void) _clickButtonWithName:(NSString *)name {
6028 if ([name isEqualToString:UCLocalize("CLEAR")])
6029 [delegate_ clearPackage:package_];
6030 else if ([name isEqualToString:UCLocalize("INSTALL")])
6031 [delegate_ installPackage:package_];
6032 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6033 [delegate_ installPackage:package_];
6034 else if ([name isEqualToString:UCLocalize("REMOVE")])
6035 [delegate_ removePackage:package_];
6036 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6037 [delegate_ installPackage:package_];
6038 else _assert(false);
6039 }
6040
6041 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6042 NSString *context([sheet context]);
6043
6044 if ([context isEqualToString:@"modify"]) {
6045 if (button != [sheet cancelButtonIndex]) {
6046 NSString *buttonName = [buttons_ objectAtIndex:button];
6047 [self _clickButtonWithName:buttonName];
6048 }
6049
6050 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6051 }
6052 }
6053
6054 - (bool) _allowJavaScriptPanel {
6055 return commercial_;
6056 }
6057
6058 #if !AlwaysReload
6059 - (void) _customButtonClicked {
6060 int count([buttons_ count]);
6061 if (count == 0)
6062 return;
6063
6064 if (count == 1)
6065 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6066 else {
6067 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6068 [buttons addObjectsFromArray:buttons_];
6069
6070 UIActionSheet *sheet = [[[UIActionSheet alloc]
6071 initWithTitle:nil
6072 delegate:self
6073 cancelButtonTitle:nil
6074 destructiveButtonTitle:nil
6075 otherButtonTitles:nil
6076 ] autorelease];
6077
6078 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6079 if (!IsWildcat_) {
6080 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6081 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6082 }
6083 [sheet setContext:@"modify"];
6084
6085 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6086 }
6087 }
6088
6089 // We don't want to allow non-commercial packages to do custom things to the install button,
6090 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6091 - (void) customButtonClicked {
6092 if (commercial_)
6093 [super customButtonClicked];
6094 else
6095 [self _customButtonClicked];
6096 }
6097
6098 - (void) reloadButtonClicked {
6099 // Don't reload a commerical package by tapping the loading button,
6100 // but if it's not an Install button, we should forward it on.
6101 if (![package_ uninstalled])
6102 [self _customButtonClicked];
6103 }
6104
6105 - (void) applyLoadingTitle {
6106 // Don't show "Loading" as the title. Ever.
6107 }
6108
6109 - (UIBarButtonItem *) rightButton {
6110 return button_;
6111 }
6112 #endif
6113
6114 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6115 if ((self = [super init]) != nil) {
6116 database_ = database;
6117 buttons_ = [NSMutableArray arrayWithCapacity:4];
6118 name_ = [NSString stringWithString:name];
6119 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6120 } return self;
6121 }
6122
6123 - (void) reloadData {
6124 [super reloadData];
6125
6126 package_ = [database_ packageWithName:name_];
6127
6128 [buttons_ removeAllObjects];
6129
6130 if (package_ != nil) {
6131 [(Package *) package_ parse];
6132
6133 commercial_ = [package_ isCommercial];
6134
6135 if ([package_ mode] != nil)
6136 [buttons_ addObject:UCLocalize("CLEAR")];
6137 if ([package_ source] == nil);
6138 else if ([package_ upgradableAndEssential:NO])
6139 [buttons_ addObject:UCLocalize("UPGRADE")];
6140 else if ([package_ uninstalled])
6141 [buttons_ addObject:UCLocalize("INSTALL")];
6142 else
6143 [buttons_ addObject:UCLocalize("REINSTALL")];
6144 if (![package_ uninstalled])
6145 [buttons_ addObject:UCLocalize("REMOVE")];
6146 }
6147
6148 NSString *title;
6149 switch ([buttons_ count]) {
6150 case 0: title = nil; break;
6151 case 1: title = [buttons_ objectAtIndex:0]; break;
6152 default: title = UCLocalize("MODIFY"); break;
6153 }
6154
6155 button_ = [[[UIBarButtonItem alloc]
6156 initWithTitle:title
6157 style:UIBarButtonItemStylePlain
6158 target:self
6159 action:@selector(customButtonClicked)
6160 ] autorelease];
6161 }
6162
6163 - (bool) isLoading {
6164 return commercial_ ? [super isLoading] : false;
6165 }
6166
6167 @end
6168 /* }}} */
6169
6170 /* Package List Controller {{{ */
6171 @interface PackageListController : CYViewController <
6172 UITableViewDataSource,
6173 UITableViewDelegate
6174 > {
6175 _transient Database *database_;
6176 unsigned era_;
6177 NSMutableArray *packages_;
6178 NSMutableArray *sections_;
6179 UITableView *list_;
6180 NSMutableArray *index_;
6181 NSMutableDictionary *indices_;
6182 NSString *title_;
6183 }
6184
6185 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6186 - (void) setDelegate:(id)delegate;
6187 - (void) resetCursor;
6188
6189 @end
6190
6191 @implementation PackageListController
6192
6193 - (void) dealloc {
6194 [packages_ release];
6195 [sections_ release];
6196 [list_ release];
6197 [index_ release];
6198 [indices_ release];
6199 [title_ release];
6200
6201 [super dealloc];
6202 }
6203
6204 - (void) deselectWithAnimation:(BOOL)animated {
6205 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6206 }
6207
6208 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6209 CGRect base = [[self view] bounds];
6210 base.size.height -= bounds.size.height;
6211 base.origin = [list_ frame].origin;
6212
6213 [UIView beginAnimations:nil context:NULL];
6214 [UIView setAnimationBeginsFromCurrentState:YES];
6215 [UIView setAnimationCurve:curve];
6216 [UIView setAnimationDuration:duration];
6217 [list_ setFrame:base];
6218 [UIView commitAnimations];
6219 }
6220
6221 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6222 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6223 }
6224
6225 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6226 [self resizeForKeyboardBounds:bounds duration:0];
6227 }
6228
6229 - (void) keyboardWillShow:(NSNotification *)notification {
6230 CGRect bounds;
6231 CGPoint center;
6232 NSTimeInterval duration;
6233 UIViewAnimationCurve curve;
6234 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6235 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
6236 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6237 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6238
6239 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);
6240 UIViewController *base = self;
6241 while ([base parentViewController] != nil)
6242 base = [base parentViewController];
6243 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6244 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6245
6246 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6247 }
6248
6249 - (void) keyboardWillHide:(NSNotification *)notification {
6250 NSTimeInterval duration;
6251 UIViewAnimationCurve curve;
6252 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6253 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6254
6255 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6256 }
6257
6258 - (void) viewWillAppear:(BOOL)animated {
6259 [super viewWillAppear:animated];
6260
6261 [self resizeForKeyboardBounds:CGRectZero];
6262 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6263 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6264 }
6265
6266 - (void) viewWillDisappear:(BOOL)animated {
6267 [super viewWillDisappear:animated];
6268
6269 [self resizeForKeyboardBounds:CGRectZero];
6270 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6271 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6272 }
6273
6274 - (void) viewDidAppear:(BOOL)animated {
6275 [super viewDidAppear:animated];
6276 [self deselectWithAnimation:animated];
6277 }
6278
6279 - (void) didSelectPackage:(Package *)package {
6280 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6281 [view setDelegate:delegate_];
6282 [[self navigationController] pushViewController:view animated:YES];
6283 }
6284
6285 #if TryIndexedCollation
6286 + (BOOL) hasIndexedCollation {
6287 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6288 }
6289 #endif
6290
6291 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6292 NSInteger count([sections_ count]);
6293 return count == 0 ? 1 : count;
6294 }
6295
6296 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6297 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6298 return nil;
6299 return [[sections_ objectAtIndex:section] name];
6300 }
6301
6302 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6303 if ([sections_ count] == 0)
6304 return 0;
6305 return [[sections_ objectAtIndex:section] count];
6306 }
6307
6308 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6309 @synchronized (database_) {
6310 if ([database_ era] != era_)
6311 return nil;
6312
6313 Section *section([sections_ objectAtIndex:[path section]]);
6314 NSInteger row([path row]);
6315 Package *package([packages_ objectAtIndex:([section row] + row)]);
6316 return [[package retain] autorelease];
6317 } }
6318
6319 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6320 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6321 if (cell == nil)
6322 cell = [[[PackageCell alloc] init] autorelease];
6323 [cell setPackage:[self packageAtIndexPath:path]];
6324 return cell;
6325 }
6326
6327 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6328 Package *package([self packageAtIndexPath:path]);
6329 package = [database_ packageWithName:[package id]];
6330 [self didSelectPackage:package];
6331 }
6332
6333 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6334 // XXX: is 20 the most optimal number here?
6335 return [packages_ count] > 20 ? index_ : nil;
6336 }
6337
6338 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6339 #if TryIndexedCollation
6340 if ([[self class] hasIndexedCollation]) {
6341 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6342 }
6343 #endif
6344
6345 return index;
6346 }
6347
6348 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6349 if ((self = [super init]) != nil) {
6350 database_ = database;
6351 title_ = [title copy];
6352 [[self navigationItem] setTitle:title_];
6353
6354 #if TryIndexedCollation
6355 if ([[self class] hasIndexedCollation])
6356 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6357 else
6358 #endif
6359 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6360
6361 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6362
6363 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6364 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6365
6366 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6367 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6368 [list_ setRowHeight:73];
6369 [[self view] addSubview:list_];
6370
6371 [list_ setDataSource:self];
6372 [list_ setDelegate:self];
6373 } return self;
6374 }
6375
6376 - (void) setDelegate:(id)delegate {
6377 delegate_ = delegate;
6378 }
6379
6380 - (bool) hasPackage:(Package *)package {
6381 return true;
6382 }
6383
6384 - (void) reloadData {
6385 [super reloadData];
6386
6387 era_ = [database_ era];
6388 NSArray *packages = [database_ packages];
6389
6390 [packages_ removeAllObjects];
6391 [sections_ removeAllObjects];
6392
6393 _profile(PackageTable$reloadData$Filter)
6394 for (Package *package in packages)
6395 if ([self hasPackage:package])
6396 [packages_ addObject:package];
6397 _end
6398
6399 [indices_ removeAllObjects];
6400
6401 Section *section = nil;
6402
6403 #if TryIndexedCollation
6404 if ([[self class] hasIndexedCollation]) {
6405 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6406 NSArray *titles = [collation sectionIndexTitles];
6407 int secidx = -1;
6408
6409 _profile(PackageTable$reloadData$Section)
6410 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6411 Package *package;
6412 int index;
6413
6414 _profile(PackageTable$reloadData$Section$Package)
6415 package = [packages_ objectAtIndex:offset];
6416 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6417 _end
6418
6419 while (secidx < index) {
6420 secidx += 1;
6421
6422 _profile(PackageTable$reloadData$Section$Allocate)
6423 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6424 _end
6425
6426 _profile(PackageTable$reloadData$Section$Add)
6427 [sections_ addObject:section];
6428 _end
6429 }
6430
6431 [section addToCount];
6432 }
6433 _end
6434 } else
6435 #endif
6436 {
6437 [index_ removeAllObjects];
6438
6439 _profile(PackageTable$reloadData$Section)
6440 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6441 Package *package;
6442 unichar index;
6443
6444 _profile(PackageTable$reloadData$Section$Package)
6445 package = [packages_ objectAtIndex:offset];
6446 index = [package index];
6447 _end
6448
6449 if (section == nil || [section index] != index) {
6450 _profile(PackageTable$reloadData$Section$Allocate)
6451 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6452 _end
6453
6454 [index_ addObject:[section name]];
6455 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6456
6457 _profile(PackageTable$reloadData$Section$Add)
6458 [sections_ addObject:section];
6459 _end
6460 }
6461
6462 [section addToCount];
6463 }
6464 _end
6465 }
6466
6467 _profile(PackageTable$reloadData$List)
6468 [list_ reloadData];
6469 _end
6470 }
6471
6472 - (void) resetCursor {
6473 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6474 }
6475
6476 @end
6477 /* }}} */
6478 /* Filtered Package List Controller {{{ */
6479 @interface FilteredPackageListController : PackageListController {
6480 SEL filter_;
6481 IMP imp_;
6482 id object_;
6483 }
6484
6485 - (void) setObject:(id)object;
6486 - (void) setObject:(id)object forFilter:(SEL)filter;
6487
6488 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6489
6490 @end
6491
6492 @implementation FilteredPackageListController
6493
6494 - (void) dealloc {
6495 if (object_ != nil)
6496 [object_ release];
6497 [super dealloc];
6498 }
6499
6500 - (void) setFilter:(SEL)filter {
6501 filter_ = filter;
6502
6503 /* XXX: this is an unsafe optimization of doomy hell */
6504 Method method(class_getInstanceMethod([Package class], filter));
6505 _assert(method != NULL);
6506 imp_ = method_getImplementation(method);
6507 _assert(imp_ != NULL);
6508 }
6509
6510 - (void) setObject:(id)object {
6511 if (object_ != nil)
6512 [object_ release];
6513 if (object == nil)
6514 object_ = nil;
6515 else
6516 object_ = [object retain];
6517 }
6518
6519 - (void) setObject:(id)object forFilter:(SEL)filter {
6520 [self setFilter:filter];
6521 [self setObject:object];
6522 }
6523
6524 - (bool) hasPackage:(Package *)package {
6525 _profile(FilteredPackageTable$hasPackage)
6526 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6527 _end
6528 }
6529
6530 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6531 if ((self = [super initWithDatabase:database title:title]) != nil) {
6532 [self setFilter:filter];
6533 [self setObject:object];
6534 } return self;
6535 }
6536
6537 @end
6538 /* }}} */
6539
6540 /* Home Controller {{{ */
6541 @interface HomeController : CYBrowserController {
6542 }
6543
6544 @end
6545
6546 @implementation HomeController
6547
6548 - (id) init {
6549 if ((self = [super init]) != nil) {
6550 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6551 } return self;
6552 }
6553
6554 - (NSURL *) navigationURL {
6555 return [NSURL URLWithString:@"cydia://home"];
6556 }
6557
6558 - (void) aboutButtonClicked {
6559 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6560
6561 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6562 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6563 [alert setCancelButtonIndex:0];
6564
6565 [alert setMessage:
6566 @"Copyright (C) 2008-2011\n"
6567 "Jay Freeman (saurik)\n"
6568 "saurik@saurik.com\n"
6569 "http://www.saurik.com/"
6570 ];
6571
6572 [alert show];
6573 }
6574
6575 - (void) viewDidLoad {
6576 [super viewDidLoad];
6577
6578 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6579 initWithTitle:UCLocalize("ABOUT")
6580 style:UIBarButtonItemStylePlain
6581 target:self
6582 action:@selector(aboutButtonClicked)
6583 ] autorelease]];
6584 }
6585
6586 @end
6587 /* }}} */
6588 /* Manage Controller {{{ */
6589 @interface ManageController : CYBrowserController {
6590 }
6591
6592 - (void) queueStatusDidChange;
6593
6594 @end
6595
6596 @implementation ManageController
6597
6598 - (id) init {
6599 if ((self = [super init]) != nil) {
6600 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6601 } return self;
6602 }
6603
6604 - (NSURL *) navigationURL {
6605 return [NSURL URLWithString:@"cydia://manage"];
6606 }
6607
6608 - (void) viewDidLoad {
6609 [super viewDidLoad];
6610
6611 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6612 initWithTitle:UCLocalize("SETTINGS")
6613 style:UIBarButtonItemStylePlain
6614 target:self
6615 action:@selector(settingsButtonClicked)
6616 ] autorelease]];
6617
6618 [self queueStatusDidChange];
6619 }
6620
6621 - (void) settingsButtonClicked {
6622 [delegate_ showSettings];
6623 }
6624
6625 #if !AlwaysReload
6626 - (void) queueButtonClicked {
6627 [delegate_ queue];
6628 }
6629
6630 - (void) applyLoadingTitle {
6631 // Disable "Loading" title.
6632 }
6633
6634 - (void) applyRightButton {
6635 // Disable right button.
6636 }
6637 #endif
6638
6639 - (void) queueStatusDidChange {
6640 #if !AlwaysReload
6641 if (!IsWildcat_ && Queuing_) {
6642 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6643 initWithTitle:UCLocalize("QUEUE")
6644 style:UIBarButtonItemStyleDone
6645 target:self
6646 action:@selector(queueButtonClicked)
6647 ] autorelease]];
6648 } else {
6649 [[self navigationItem] setRightBarButtonItem:nil];
6650 }
6651 #endif
6652 }
6653
6654 - (bool) isLoading {
6655 // Never show as loading.
6656 return false;
6657 }
6658
6659 @end
6660 /* }}} */
6661
6662 /* Refresh Bar {{{ */
6663 @interface RefreshBar : UINavigationBar {
6664 UIProgressIndicator *indicator_;
6665 UITextLabel *prompt_;
6666 UIProgressBar *progress_;
6667 UINavigationButton *cancel_;
6668 }
6669
6670 @end
6671
6672 @implementation RefreshBar
6673
6674 - (void) dealloc {
6675 [indicator_ release];
6676 [prompt_ release];
6677 [progress_ release];
6678 [cancel_ release];
6679 [super dealloc];
6680 }
6681
6682 - (void) positionViews {
6683 CGRect frame = [cancel_ frame];
6684 frame.size = [cancel_ sizeThatFits:frame.size];
6685 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6686 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6687 [cancel_ setFrame:frame];
6688
6689 CGSize prgsize = {75, 100};
6690 CGRect prgrect = {{
6691 [self frame].size.width - prgsize.width - 10,
6692 ([self frame].size.height - prgsize.height) / 2
6693 } , prgsize};
6694 [progress_ setFrame:prgrect];
6695
6696 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6697 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6698 CGRect indrect = {{indoffset, indoffset}, indsize};
6699 [indicator_ setFrame:indrect];
6700
6701 CGSize prmsize = {215, indsize.height + 4};
6702 CGRect prmrect = {{
6703 indoffset * 2 + indsize.width,
6704 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6705 }, prmsize};
6706 [prompt_ setFrame:prmrect];
6707 }
6708
6709 - (void) setFrame:(CGRect)frame {
6710 [super setFrame:frame];
6711 [self positionViews];
6712 }
6713
6714 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6715 if ((self = [super initWithFrame:frame]) != nil) {
6716 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6717
6718 [self setBarStyle:UIBarStyleBlack];
6719
6720 UIBarStyle barstyle([self _barStyle:NO]);
6721 bool ugly(barstyle == UIBarStyleDefault);
6722
6723 UIProgressIndicatorStyle style = ugly ?
6724 UIProgressIndicatorStyleMediumBrown :
6725 UIProgressIndicatorStyleMediumWhite;
6726
6727 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6728 [indicator_ setStyle:style];
6729 [indicator_ startAnimation];
6730 [self addSubview:indicator_];
6731
6732 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6733 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6734 [prompt_ setBackgroundColor:[UIColor clearColor]];
6735 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6736 [self addSubview:prompt_];
6737
6738 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6739 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6740 [progress_ setStyle:0];
6741 [self addSubview:progress_];
6742
6743 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6744 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6745 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6746 [cancel_ setBarStyle:barstyle];
6747
6748 [self positionViews];
6749 } return self;
6750 }
6751
6752 - (void) setCancellable:(bool)cancellable {
6753 if (cancellable)
6754 [self addSubview:cancel_];
6755 else
6756 [cancel_ removeFromSuperview];
6757 }
6758
6759 - (void) start {
6760 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6761 [progress_ setProgress:0];
6762 }
6763
6764 - (void) stop {
6765 [self setCancellable:NO];
6766 }
6767
6768 - (void) setPrompt:(NSString *)prompt {
6769 [prompt_ setText:prompt];
6770 }
6771
6772 - (void) setProgress:(float)progress {
6773 [progress_ setProgress:progress];
6774 }
6775
6776 @end
6777 /* }}} */
6778
6779 /* Cydia Navigation Controller Interface {{{ */
6780 @interface UINavigationController (Cydia)
6781
6782 - (NSArray *) navigationURLCollection;
6783 - (void) unloadData;
6784
6785 @end
6786 /* }}} */
6787
6788 /* Cydia Tab Bar Controller {{{ */
6789 @interface CYTabBarController : UITabBarController <
6790 UITabBarControllerDelegate,
6791 ProgressDelegate
6792 > {
6793 _transient Database *database_;
6794 RefreshBar *refreshbar_;
6795
6796 bool dropped_;
6797 bool updating_;
6798 // XXX: ok, "updatedelegate_"?...
6799 _transient NSObject<CydiaDelegate> *updatedelegate_;
6800
6801 id root_;
6802 UIViewController *remembered_;
6803 _transient UIViewController *transient_;
6804 }
6805
6806 - (NSArray *) navigationURLCollection;
6807 - (void) dropBar:(BOOL)animated;
6808 - (void) beginUpdate;
6809 - (void) raiseBar:(BOOL)animated;
6810 - (BOOL) updating;
6811 - (void) unloadData;
6812
6813 @end
6814
6815 @implementation CYTabBarController
6816
6817 - (void) setUnselectedViewController:(UIViewController *)transient {
6818 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6819 if (transient != nil) {
6820 if (transient_ == nil)
6821 remembered_ = [[controllers objectAtIndex:0] retain];
6822 transient_ = transient;
6823 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6824 [controllers replaceObjectAtIndex:0 withObject:transient_];
6825 [self setSelectedIndex:0];
6826 [self setViewControllers:controllers];
6827 [self concealTabBarSelection];
6828 } else if (remembered_ != nil) {
6829 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6830 transient_ = transient;
6831 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6832 [remembered_ release];
6833 remembered_ = nil;
6834 [self setViewControllers:controllers];
6835 [self revealTabBarSelection];
6836 }
6837 }
6838
6839 - (UIViewController *) unselectedViewController {
6840 return transient_;
6841 }
6842
6843 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6844 if ([self unselectedViewController])
6845 [self setUnselectedViewController:nil];
6846 }
6847
6848 - (NSArray *) navigationURLCollection {
6849 NSMutableArray *items([NSMutableArray array]);
6850
6851 // XXX: Should this deal with transient view controllers?
6852 for (id navigation in [self viewControllers]) {
6853 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6854 if (stack != nil)
6855 [items addObject:stack];
6856 }
6857
6858 return items;
6859 }
6860
6861 - (void) unloadData {
6862 UIViewController *selected([self selectedViewController]);
6863 for (UINavigationController *controller in [self viewControllers])
6864 [controller unloadData];
6865
6866 [selected reloadData];
6867
6868 if (UIViewController *unselected = [self unselectedViewController])
6869 [unselected reloadData];
6870
6871 [super unloadData];
6872 }
6873
6874 - (void) dealloc {
6875 [refreshbar_ release];
6876 [[NSNotificationCenter defaultCenter] removeObserver:self];
6877
6878 [super dealloc];
6879 }
6880
6881 - (id) initWithDatabase:(Database *)database {
6882 if ((self = [super init]) != nil) {
6883 database_ = database;
6884 [self setDelegate:self];
6885
6886 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6887 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6888
6889 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6890 } return self;
6891 }
6892
6893 - (void) setUpdate:(NSDate *)date {
6894 [self beginUpdate];
6895 }
6896
6897 - (void) beginUpdate {
6898 [refreshbar_ start];
6899 [self dropBar:YES];
6900
6901 [updatedelegate_ retainNetworkActivityIndicator];
6902 updating_ = true;
6903
6904 [NSThread
6905 detachNewThreadSelector:@selector(performUpdate)
6906 toTarget:self
6907 withObject:nil
6908 ];
6909 }
6910
6911 - (void) performUpdate { _pooled
6912 Status status;
6913 status.setDelegate(self);
6914 [database_ updateWithStatus:status];
6915
6916 [self
6917 performSelectorOnMainThread:@selector(completeUpdate)
6918 withObject:nil
6919 waitUntilDone:NO
6920 ];
6921 }
6922
6923 - (void) stopUpdateWithSelector:(SEL)selector {
6924 updating_ = false;
6925 [updatedelegate_ releaseNetworkActivityIndicator];
6926
6927 [self raiseBar:YES];
6928 [refreshbar_ stop];
6929
6930 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6931 }
6932
6933 - (void) completeUpdate {
6934 if (!updating_)
6935 return;
6936 [self stopUpdateWithSelector:@selector(reloadData)];
6937 }
6938
6939 - (void) cancelUpdate {
6940 [self stopUpdateWithSelector:@selector(updateData)];
6941 }
6942
6943 - (void) cancelPressed {
6944 [self cancelUpdate];
6945 }
6946
6947 - (BOOL) updating {
6948 return updating_;
6949 }
6950
6951 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6952 [refreshbar_ setPrompt:[event compoundMessage]];
6953 }
6954
6955 - (bool) isProgressCancelled {
6956 return !updating_;
6957 }
6958
6959 - (void) setProgressCancellable:(NSNumber *)cancellable {
6960 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6961 }
6962
6963 - (void) setProgressPercent:(NSNumber *)percent {
6964 [refreshbar_ setProgress:[percent floatValue]];
6965 }
6966
6967 - (void) setProgressStatus:(NSDictionary *)status {
6968 if (status != nil)
6969 [self setProgressPercent:[status objectForKey:@"Percent"]];
6970 }
6971
6972 - (void) setUpdateDelegate:(id)delegate {
6973 updatedelegate_ = delegate;
6974 }
6975
6976 - (CGFloat) statusBarHeight {
6977 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6978 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6979 } else {
6980 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6981 }
6982 }
6983
6984 - (UIView *) transitionView {
6985 if ([self respondsToSelector:@selector(_transitionView)])
6986 return [self _transitionView];
6987 else
6988 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6989 }
6990
6991 - (void) dropBar:(BOOL)animated {
6992 if (dropped_)
6993 return;
6994 dropped_ = true;
6995
6996 UIView *transition([self transitionView]);
6997 [[self view] addSubview:refreshbar_];
6998
6999 CGRect barframe([refreshbar_ frame]);
7000
7001 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7002 barframe.origin.y = [self statusBarHeight];
7003 else
7004 barframe.origin.y = 0;
7005
7006 [refreshbar_ setFrame:barframe];
7007
7008 if (animated)
7009 [UIView beginAnimations:nil context:NULL];
7010
7011 CGRect viewframe = [transition frame];
7012 viewframe.origin.y += barframe.size.height;
7013 viewframe.size.height -= barframe.size.height;
7014 [transition setFrame:viewframe];
7015
7016 if (animated)
7017 [UIView commitAnimations];
7018
7019 // Ensure bar has the proper width for our view, it might have changed
7020 barframe.size.width = viewframe.size.width;
7021 [refreshbar_ setFrame:barframe];
7022
7023 // XXX: fix Apple's layout bug
7024 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7025 }
7026
7027 - (void) raiseBar:(BOOL)animated {
7028 if (!dropped_)
7029 return;
7030 dropped_ = false;
7031
7032 UIView *transition([self transitionView]);
7033 [refreshbar_ removeFromSuperview];
7034
7035 CGRect barframe([refreshbar_ frame]);
7036
7037 if (animated)
7038 [UIView beginAnimations:nil context:NULL];
7039
7040 CGRect viewframe = [transition frame];
7041 viewframe.origin.y -= barframe.size.height;
7042 viewframe.size.height += barframe.size.height;
7043 [transition setFrame:viewframe];
7044
7045 if (animated)
7046 [UIView commitAnimations];
7047
7048 // XXX: fix Apple's layout bug
7049 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7050 }
7051
7052 #if 0
7053 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7054 // XXX: fix Apple's layout bug
7055 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7056 }
7057 #endif
7058
7059 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7060 bool dropped(dropped_);
7061
7062 if (dropped)
7063 [self raiseBar:NO];
7064
7065 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7066
7067 if (dropped)
7068 [self dropBar:NO];
7069
7070 // XXX: fix Apple's layout bug
7071 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7072 }
7073
7074 - (void) statusBarFrameChanged:(NSNotification *)notification {
7075 if (dropped_) {
7076 [self raiseBar:NO];
7077 [self dropBar:NO];
7078 }
7079 }
7080
7081 @end
7082 /* }}} */
7083
7084 /* Cydia Navigation Controller Implementation {{{ */
7085 @implementation UINavigationController (Cydia)
7086
7087 - (NSArray *) navigationURLCollection {
7088 NSMutableArray *stack([NSMutableArray array]);
7089
7090 for (CYViewController *controller in [self viewControllers]) {
7091 NSString *url = [[controller navigationURL] absoluteString];
7092 if (url != nil)
7093 [stack addObject:url];
7094 }
7095
7096 return stack;
7097 }
7098
7099 - (void) reloadData {
7100 [super reloadData];
7101
7102 if (UIViewController *visible = [self visibleViewController])
7103 [visible reloadData];
7104 }
7105
7106 - (void) unloadData {
7107 for (CYViewController *page in [self viewControllers])
7108 [page unloadData];
7109
7110 [super unloadData];
7111 }
7112
7113 @end
7114 /* }}} */
7115
7116 /* Cydia:// Protocol {{{ */
7117 @interface CydiaURLProtocol : NSURLProtocol {
7118 }
7119
7120 @end
7121
7122 @implementation CydiaURLProtocol
7123
7124 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7125 NSURL *url([request URL]);
7126 if (url == nil)
7127 return NO;
7128
7129 NSString *scheme([[url scheme] lowercaseString]);
7130 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7131 return YES;
7132 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7133 return YES;
7134
7135 return NO;
7136 }
7137
7138 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7139 return request;
7140 }
7141
7142 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7143 id<NSURLProtocolClient> client([self client]);
7144 if (icon == nil)
7145 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7146 else {
7147 NSData *data(UIImagePNGRepresentation(icon));
7148
7149 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7150 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7151 [client URLProtocol:self didLoadData:data];
7152 [client URLProtocolDidFinishLoading:self];
7153 }
7154 }
7155
7156 - (void) startLoading {
7157 id<NSURLProtocolClient> client([self client]);
7158 NSURLRequest *request([self request]);
7159
7160 NSURL *url([request URL]);
7161 NSString *href([url absoluteString]);
7162 NSString *scheme([[url scheme] lowercaseString]);
7163
7164 NSString *path;
7165
7166 if ([scheme isEqualToString:@"cydia"])
7167 path = [href substringFromIndex:8];
7168 else if ([scheme isEqualToString:@"about"])
7169 path = [href substringFromIndex:12];
7170 else _assert(false);
7171
7172 NSRange slash([path rangeOfString:@"/"]);
7173
7174 NSString *command;
7175 if (slash.location == NSNotFound) {
7176 command = path;
7177 path = nil;
7178 } else {
7179 command = [path substringToIndex:slash.location];
7180 path = [path substringFromIndex:(slash.location + 1)];
7181 }
7182
7183 Database *database([Database sharedInstance]);
7184
7185 if ([command isEqualToString:@"package-icon"]) {
7186 if (path == nil)
7187 goto fail;
7188 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7189 Package *package([database packageWithName:path]);
7190 if (package == nil)
7191 goto fail;
7192 UIImage *icon([package icon]);
7193 [self _returnPNGWithImage:icon forRequest:request];
7194 } else if ([command isEqualToString:@"source-icon"]) {
7195 if (path == nil)
7196 goto fail;
7197 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7198 NSString *source(Simplify(path));
7199 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7200 if (icon == nil)
7201 icon = [UIImage applicationImageNamed:@"unknown.png"];
7202 [self _returnPNGWithImage:icon forRequest:request];
7203 } else if ([command isEqualToString:@"uikit-image"]) {
7204 if (path == nil)
7205 goto fail;
7206 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7207 UIImage *icon(_UIImageWithName(path));
7208 [self _returnPNGWithImage:icon forRequest:request];
7209 } else if ([command isEqualToString:@"section-icon"]) {
7210 if (path == nil)
7211 goto fail;
7212 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7213 NSString *section(Simplify(path));
7214 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7215 if (icon == nil)
7216 icon = [UIImage applicationImageNamed:@"unknown.png"];
7217 [self _returnPNGWithImage:icon forRequest:request];
7218 } else fail: {
7219 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7220 }
7221 }
7222
7223 - (void) stopLoading {
7224 }
7225
7226 @end
7227 /* }}} */
7228
7229 /* Section Controller {{{ */
7230 @interface SectionController : FilteredPackageListController {
7231 _H<NSString> section_;
7232 }
7233
7234 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7235
7236 @end
7237
7238 @implementation SectionController
7239
7240 - (NSURL *) navigationURL {
7241 NSString *name = section_;
7242 if (name == nil)
7243 name = @"all";
7244
7245 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7246 }
7247
7248 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7249 NSString *title;
7250 if (name == nil)
7251 title = UCLocalize("ALL_PACKAGES");
7252 else if (![name isEqual:@""])
7253 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7254 else
7255 title = UCLocalize("NO_SECTION");
7256
7257 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7258 section_ = name;
7259 } return self;
7260 }
7261
7262 @end
7263 /* }}} */
7264 /* Sections Controller {{{ */
7265 @interface SectionsController : CYViewController <
7266 UITableViewDataSource,
7267 UITableViewDelegate
7268 > {
7269 _transient Database *database_;
7270 NSMutableArray *sections_;
7271 NSMutableArray *filtered_;
7272 UITableView *list_;
7273 }
7274
7275 - (id) initWithDatabase:(Database *)database;
7276 - (void) editButtonClicked;
7277
7278 @end
7279
7280 @implementation SectionsController
7281
7282 - (void) dealloc {
7283 [self releaseSubviews];
7284 [sections_ release];
7285 [filtered_ release];
7286
7287 [super dealloc];
7288 }
7289
7290 - (NSURL *) navigationURL {
7291 return [NSURL URLWithString:@"cydia://sections"];
7292 }
7293
7294 - (void) updateNavigationItem {
7295 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7296 if ([sections_ count] == 0) {
7297 [[self navigationItem] setRightBarButtonItem:nil];
7298 } else {
7299 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7300 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7301 target:self
7302 action:@selector(editButtonClicked)
7303 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7304 }
7305 }
7306
7307 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7308 [super setEditing:editing animated:animated];
7309
7310 if (editing)
7311 [list_ reloadData];
7312 else
7313 [delegate_ updateData];
7314
7315 [self updateNavigationItem];
7316 }
7317
7318 - (void) viewDidAppear:(BOOL)animated {
7319 [super viewDidAppear:animated];
7320 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7321 }
7322
7323 - (void) viewWillDisappear:(BOOL)animated {
7324 [super viewWillDisappear:animated];
7325 if ([self isEditing]) [self setEditing:NO];
7326 }
7327
7328 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7329 Section *section = nil;
7330 int index = [indexPath row];
7331 if (![self isEditing]) {
7332 index -= 1;
7333 if (index >= 0)
7334 section = [filtered_ objectAtIndex:index];
7335 } else {
7336 section = [sections_ objectAtIndex:index];
7337 }
7338 return section;
7339 }
7340
7341 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7342 if ([self isEditing])
7343 return [sections_ count];
7344 else
7345 return [filtered_ count] + 1;
7346 }
7347
7348 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7349 return 45.0f;
7350 }*/
7351
7352 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7353 static NSString *reuseIdentifier = @"SectionCell";
7354
7355 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7356 if (cell == nil)
7357 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7358
7359 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7360
7361 return cell;
7362 }
7363
7364 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7365 if ([self isEditing])
7366 return;
7367
7368 Section *section = [self sectionAtIndexPath:indexPath];
7369
7370 SectionController *controller = [[[SectionController alloc]
7371 initWithDatabase:database_
7372 section:[section name]
7373 ] autorelease];
7374 [controller setDelegate:delegate_];
7375
7376 [[self navigationController] pushViewController:controller animated:YES];
7377 }
7378
7379 - (void) loadView {
7380 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7381
7382 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7383 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7384 [list_ setRowHeight:45.0f];
7385 [list_ setDataSource:self];
7386 [list_ setDelegate:self];
7387 [[self view] addSubview:list_];
7388 }
7389
7390 - (void) viewDidLoad {
7391 [super viewDidLoad];
7392
7393 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7394 }
7395
7396 - (void) releaseSubviews {
7397 [list_ release];
7398 list_ = nil;
7399 }
7400
7401 - (id) initWithDatabase:(Database *)database {
7402 if ((self = [super init]) != nil) {
7403 database_ = database;
7404
7405 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7406 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7407 } return self;
7408 }
7409
7410 - (void) reloadData {
7411 [super reloadData];
7412
7413 NSArray *packages = [database_ packages];
7414
7415 [sections_ removeAllObjects];
7416 [filtered_ removeAllObjects];
7417
7418 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7419
7420 _trace();
7421 for (Package *package in packages) {
7422 NSString *name([package section]);
7423 NSString *key(name == nil ? @"" : name);
7424
7425 Section *section;
7426
7427 _profile(SectionsView$reloadData$Section)
7428 section = [sections objectForKey:key];
7429 if (section == nil) {
7430 _profile(SectionsView$reloadData$Section$Allocate)
7431 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7432 [sections setObject:section forKey:key];
7433 _end
7434 }
7435 _end
7436
7437 [section addToCount];
7438
7439 _profile(SectionsView$reloadData$Filter)
7440 if (![package valid] || ![package visible])
7441 continue;
7442 _end
7443
7444 [section addToRow];
7445 }
7446 _trace();
7447
7448 [sections_ addObjectsFromArray:[sections allValues]];
7449
7450 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7451
7452 for (Section *section in sections_) {
7453 size_t count([section row]);
7454 if (count == 0)
7455 continue;
7456
7457 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7458 [section setCount:count];
7459 [filtered_ addObject:section];
7460 }
7461
7462 [self updateNavigationItem];
7463 [list_ reloadData];
7464 _trace();
7465 }
7466
7467 - (void) editButtonClicked {
7468 [self setEditing:![self isEditing] animated:YES];
7469 }
7470
7471 @end
7472 /* }}} */
7473
7474 /* Changes Controller {{{ */
7475 @interface ChangesController : CYViewController <
7476 UITableViewDataSource,
7477 UITableViewDelegate
7478 > {
7479 _transient Database *database_;
7480 unsigned era_;
7481 CFMutableArrayRef packages_;
7482 NSMutableArray *sections_;
7483 UITableView *list_;
7484 unsigned upgrades_;
7485 }
7486
7487 - (id) initWithDatabase:(Database *)database;
7488
7489 @end
7490
7491 @implementation ChangesController
7492
7493 - (void) dealloc {
7494 [self releaseSubviews];
7495 CFRelease(packages_);
7496 [sections_ release];
7497
7498 [super dealloc];
7499 }
7500
7501 - (NSURL *) navigationURL {
7502 return [NSURL URLWithString:@"cydia://changes"];
7503 }
7504
7505 - (void) viewDidAppear:(BOOL)animated {
7506 [super viewDidAppear:animated];
7507 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7508 }
7509
7510 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7511 NSInteger count([sections_ count]);
7512 return count == 0 ? 1 : count;
7513 }
7514
7515 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7516 if ([sections_ count] == 0)
7517 return nil;
7518 return [[sections_ objectAtIndex:section] name];
7519 }
7520
7521 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7522 if ([sections_ count] == 0)
7523 return 0;
7524 return [[sections_ objectAtIndex:section] count];
7525 }
7526
7527 - (Package *) packageAtIndex:(NSUInteger)index {
7528 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7529 }
7530
7531 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7532 @synchronized (database_) {
7533 if ([database_ era] != era_)
7534 return nil;
7535
7536 NSUInteger sectionIndex([path section]);
7537 if (sectionIndex >= [sections_ count])
7538 return nil;
7539 Section *section([sections_ objectAtIndex:sectionIndex]);
7540 NSInteger row([path row]);
7541 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7542 } }
7543
7544 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7545 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7546 if (cell == nil)
7547 cell = [[[PackageCell alloc] init] autorelease];
7548 [cell setPackage:[self packageAtIndexPath:path]];
7549 return cell;
7550 }
7551
7552 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7553 Package *package([self packageAtIndexPath:path]);
7554 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7555 [view setDelegate:delegate_];
7556 [[self navigationController] pushViewController:view animated:YES];
7557 return path;
7558 }
7559
7560 - (void) refreshButtonClicked {
7561 [delegate_ beginUpdate];
7562 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7563 }
7564
7565 - (void) upgradeButtonClicked {
7566 [delegate_ distUpgrade];
7567 }
7568
7569 - (void) loadView {
7570 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7571
7572 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7573 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7574 [list_ setRowHeight:73];
7575 [list_ setDataSource:self];
7576 [list_ setDelegate:self];
7577 [[self view] addSubview:list_];
7578 }
7579
7580 - (void) viewDidLoad {
7581 [super viewDidLoad];
7582
7583 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7584 }
7585
7586 - (void) releaseSubviews {
7587 [list_ release];
7588 list_ = nil;
7589 }
7590
7591 - (id) initWithDatabase:(Database *)database {
7592 if ((self = [super init]) != nil) {
7593 database_ = database;
7594
7595 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7596 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7597 } return self;
7598 }
7599
7600 // this mostly works because reloadData (below) is @synchronized (database_)
7601 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7602 - (void) _reloadPackages:(NSArray *)packages {
7603 CFRelease(packages_);
7604 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7605
7606 _trace();
7607 _profile(ChangesController$_reloadPackages$Filter)
7608 for (Package *package in packages)
7609 if ([package upgradableAndEssential:YES] || [package visible])
7610 CFArrayAppendValue(packages_, package);
7611 _end
7612 _trace();
7613 _profile(ChangesController$_reloadPackages$radixSort)
7614 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7615 _end
7616 _trace();
7617 }
7618
7619 - (void) _reloadData {
7620 @synchronized (database_) {
7621 era_ = [database_ era];
7622 NSArray *packages = [database_ packages];
7623
7624 [sections_ removeAllObjects];
7625
7626 #if 1
7627 UIProgressHUD *hud([delegate_ addProgressHUD]);
7628 [hud setText:UCLocalize("LOADING")];
7629 //NSLog(@"HUD:%@::%@", delegate_, hud);
7630 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7631 [delegate_ removeProgressHUD:hud];
7632 #else
7633 [self _reloadPackages:packages];
7634 #endif
7635
7636 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7637 Section *ignored = nil;
7638 Section *section = nil;
7639 time_t last = 0;
7640
7641 upgrades_ = 0;
7642 bool unseens = false;
7643
7644 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7645
7646 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7647 Package *package = [self packageAtIndex:offset];
7648
7649 BOOL uae = [package upgradableAndEssential:YES];
7650
7651 if (!uae) {
7652 unseens = true;
7653 time_t seen([package seen]);
7654
7655 if (section == nil || last != seen) {
7656 last = seen;
7657
7658 NSString *name;
7659 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7660 [name autorelease];
7661
7662 _profile(ChangesController$reloadData$Allocate)
7663 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7664 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7665 [sections_ addObject:section];
7666 _end
7667 }
7668
7669 [section addToCount];
7670 } else if ([package ignored]) {
7671 if (ignored == nil) {
7672 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7673 }
7674 [ignored addToCount];
7675 } else {
7676 ++upgrades_;
7677 [upgradable addToCount];
7678 }
7679 }
7680 _trace();
7681
7682 CFRelease(formatter);
7683
7684 if (unseens) {
7685 Section *last = [sections_ lastObject];
7686 size_t count = [last count];
7687 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7688 [sections_ removeLastObject];
7689 }
7690
7691 if ([ignored count] != 0)
7692 [sections_ insertObject:ignored atIndex:0];
7693 if (upgrades_ != 0)
7694 [sections_ insertObject:upgradable atIndex:0];
7695
7696 [list_ reloadData];
7697
7698 if (upgrades_ > 0)
7699 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7700 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7701 style:UIBarButtonItemStylePlain
7702 target:self
7703 action:@selector(upgradeButtonClicked)
7704 ] autorelease]];
7705
7706 if (![delegate_ updating])
7707 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7708 initWithTitle:UCLocalize("REFRESH")
7709 style:UIBarButtonItemStylePlain
7710 target:self
7711 action:@selector(refreshButtonClicked)
7712 ] autorelease]];
7713
7714 PrintTimes();
7715 } }
7716
7717 - (void) reloadData {
7718 [super reloadData];
7719 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7720 }
7721
7722 @end
7723 /* }}} */
7724 /* Search Controller {{{ */
7725 @interface SearchController : FilteredPackageListController <
7726 UISearchBarDelegate
7727 > {
7728 _H<UISearchBar> search_;
7729 BOOL searchloaded_;
7730 }
7731
7732 - (id) initWithDatabase:(Database *)database;
7733 - (void) setSearchTerm:(NSString *)term;
7734 - (void) reloadData;
7735
7736 @end
7737
7738 @implementation SearchController
7739
7740 - (void) dealloc {
7741 [search_ setDelegate:nil];
7742 [super dealloc];
7743 }
7744
7745 - (NSURL *) navigationURL {
7746 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7747 return [NSURL URLWithString:@"cydia://search"];
7748 else
7749 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7750 }
7751
7752 - (void) setSearchTerm:(NSString *)searchTerm {
7753 [search_ setText:searchTerm];
7754 [self reloadData];
7755 }
7756
7757 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7758 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7759 [search_ resignFirstResponder];
7760 [self reloadData];
7761 }
7762
7763 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7764 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7765 [self reloadData];
7766 }
7767
7768 - (id) initWithDatabase:(Database *)database {
7769 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7770 search_ = [[[UISearchBar alloc] init] autorelease];
7771 [search_ setDelegate:self];
7772 } return self;
7773 }
7774
7775 - (void) viewDidAppear:(BOOL)animated {
7776 [super viewDidAppear:animated];
7777
7778 if (!searchloaded_) {
7779 searchloaded_ = YES;
7780 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7781 [search_ layoutSubviews];
7782 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7783
7784 UITextField *textField;
7785 if ([search_ respondsToSelector:@selector(searchField)])
7786 textField = [search_ searchField];
7787 else
7788 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7789
7790 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7791 [textField setEnablesReturnKeyAutomatically:NO];
7792 [[self navigationItem] setTitleView:textField];
7793 }
7794 }
7795
7796 - (void) reloadData {
7797 [self setObject:[search_ text]];
7798 [self resetCursor];
7799
7800 [super reloadData];
7801 }
7802
7803 - (void) didSelectPackage:(Package *)package {
7804 [search_ resignFirstResponder];
7805 [super didSelectPackage:package];
7806 }
7807
7808 @end
7809 /* }}} */
7810 /* Package Settings Controller {{{ */
7811 @interface PackageSettingsController : CYViewController <
7812 UITableViewDataSource,
7813 UITableViewDelegate
7814 > {
7815 _transient Database *database_;
7816 NSString *name_;
7817 Package *package_;
7818 UITableView *table_;
7819 UISwitch *subscribedSwitch_;
7820 UISwitch *ignoredSwitch_;
7821 UITableViewCell *subscribedCell_;
7822 UITableViewCell *ignoredCell_;
7823 }
7824
7825 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7826
7827 @end
7828
7829 @implementation PackageSettingsController
7830
7831 - (void) dealloc {
7832 [self releaseSubviews];
7833 [name_ release];
7834 [package_ release];
7835
7836 [super dealloc];
7837 }
7838
7839 - (NSURL *) navigationURL {
7840 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7841 }
7842
7843 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7844 if (package_ == nil)
7845 return 0;
7846
7847 if ([package_ installed] == nil)
7848 return 1;
7849 else
7850 return 2;
7851 }
7852
7853 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7854 if (package_ == nil)
7855 return 0;
7856
7857 // both sections contain just one item right now.
7858 return 1;
7859 }
7860
7861 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7862 return nil;
7863 }
7864
7865 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7866 if (section == 0)
7867 return UCLocalize("SHOW_ALL_CHANGES_EX");
7868 else
7869 return UCLocalize("IGNORE_UPGRADES_EX");
7870 }
7871
7872 - (void) onSubscribed:(id)control {
7873 bool value([control isOn]);
7874 if (package_ == nil)
7875 return;
7876 if ([package_ setSubscribed:value])
7877 [delegate_ updateData];
7878 }
7879
7880 - (void) _updateIgnored {
7881 const char *package([name_ UTF8String]);
7882 bool on([ignoredSwitch_ isOn]);
7883
7884 pid_t pid(ExecFork());
7885 if (pid == 0) {
7886 FILE *dpkg(popen("dpkg --set-selections", "w"));
7887 fwrite(package, strlen(package), 1, dpkg);
7888
7889 if (on)
7890 fwrite(" hold\n", 6, 1, dpkg);
7891 else
7892 fwrite(" install\n", 9, 1, dpkg);
7893
7894 pclose(dpkg);
7895
7896 exit(0);
7897 _assert(false);
7898 }
7899
7900 _forever {
7901 int status;
7902 int result(waitpid(pid, &status, 0));
7903
7904 if (result != -1) {
7905 _assert(result == pid);
7906 break;
7907 }
7908 }
7909 }
7910
7911 - (void) onIgnored:(id)control {
7912 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7913 [invocation setTarget:self];
7914 [invocation setSelector:@selector(_updateIgnored)];
7915
7916 [delegate_ reloadDataWithInvocation:invocation];
7917 }
7918
7919 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7920 if (package_ == nil)
7921 return nil;
7922
7923 switch ([indexPath section]) {
7924 case 0: return subscribedCell_;
7925 case 1: return ignoredCell_;
7926
7927 _nodefault
7928 }
7929
7930 return nil;
7931 }
7932
7933 - (void) loadView {
7934 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7935
7936 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7937 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7938 [table_ setDataSource:self];
7939 [table_ setDelegate:self];
7940 [[self view] addSubview:table_];
7941
7942 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7943 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7944 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7945
7946 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7947 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7948 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7949
7950 subscribedCell_ = [[UITableViewCell alloc] init];
7951 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7952 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7953 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7954
7955 ignoredCell_ = [[UITableViewCell alloc] init];
7956 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7957 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7958 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7959 }
7960
7961 - (void) viewDidLoad {
7962 [super viewDidLoad];
7963
7964 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7965 }
7966
7967 - (void) releaseSubviews {
7968 [ignoredCell_ release];
7969 ignoredCell_ = nil;
7970
7971 [subscribedCell_ release];
7972 subscribedCell_ = nil;
7973
7974 [table_ release];
7975 table_ = nil;
7976
7977 [ignoredSwitch_ release];
7978 ignoredSwitch_ = nil;
7979
7980 [subscribedSwitch_ release];
7981 subscribedSwitch_ = nil;
7982 }
7983
7984 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7985 if ((self = [super init]) != nil) {
7986 database_ = database;
7987 name_ = [package retain];
7988 } return self;
7989 }
7990
7991 - (void) reloadData {
7992 [super reloadData];
7993
7994 if (package_ != nil)
7995 [package_ autorelease];
7996 package_ = [database_ packageWithName:name_];
7997
7998 if (package_ != nil) {
7999 package_ = [package_ retain];
8000 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8001 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8002 } // XXX: what now, G?
8003
8004 [table_ reloadData];
8005 }
8006
8007 @end
8008 /* }}} */
8009
8010 /* Installed Controller {{{ */
8011 @interface InstalledController : FilteredPackageListController {
8012 BOOL expert_;
8013 }
8014
8015 - (id) initWithDatabase:(Database *)database;
8016
8017 - (void) updateRoleButton;
8018 - (void) queueStatusDidChange;
8019
8020 @end
8021
8022 @implementation InstalledController
8023
8024 - (void) dealloc {
8025 [super dealloc];
8026 }
8027
8028 - (NSURL *) navigationURL {
8029 return [NSURL URLWithString:@"cydia://installed"];
8030 }
8031
8032 - (id) initWithDatabase:(Database *)database {
8033 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8034 [self updateRoleButton];
8035 [self queueStatusDidChange];
8036 } return self;
8037 }
8038
8039 #if !AlwaysReload
8040 - (void) queueButtonClicked {
8041 [delegate_ queue];
8042 }
8043 #endif
8044
8045 - (void) queueStatusDidChange {
8046 #if !AlwaysReload
8047 if (IsWildcat_) {
8048 if (Queuing_) {
8049 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8050 initWithTitle:UCLocalize("QUEUE")
8051 style:UIBarButtonItemStyleDone
8052 target:self
8053 action:@selector(queueButtonClicked)
8054 ] autorelease]];
8055 } else {
8056 [[self navigationItem] setLeftBarButtonItem:nil];
8057 }
8058 }
8059 #endif
8060 }
8061
8062 - (void) updateRoleButton {
8063 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8064 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8065 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8066 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8067 target:self
8068 action:@selector(roleButtonClicked)
8069 ] autorelease]];
8070 }
8071
8072 - (void) roleButtonClicked {
8073 [self setObject:[NSNumber numberWithBool:expert_]];
8074 [self reloadData];
8075 expert_ = !expert_;
8076
8077 [self updateRoleButton];
8078 }
8079
8080 @end
8081 /* }}} */
8082
8083 /* Source Cell {{{ */
8084 @interface SourceCell : CYTableViewCell <
8085 ContentDelegate
8086 > {
8087 UIImage *icon_;
8088 NSString *origin_;
8089 NSString *label_;
8090 }
8091
8092 - (void) setSource:(Source *)source;
8093
8094 @end
8095
8096 @implementation SourceCell
8097
8098 - (void) clearSource {
8099 [icon_ release];
8100 [origin_ release];
8101 [label_ release];
8102
8103 icon_ = nil;
8104 origin_ = nil;
8105 label_ = nil;
8106 }
8107
8108 - (void) setSource:(Source *)source {
8109 [self clearSource];
8110
8111 if (icon_ == nil)
8112 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8113 if (icon_ == nil)
8114 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8115 icon_ = [icon_ retain];
8116
8117 origin_ = [[source name] retain];
8118 label_ = [[source uri] retain];
8119
8120 [content_ setNeedsDisplay];
8121 }
8122
8123 - (void) dealloc {
8124 [self clearSource];
8125 [super dealloc];
8126 }
8127
8128 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8129 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8130 UIView *content([self contentView]);
8131 CGRect bounds([content bounds]);
8132
8133 content_ = [[ContentView alloc] initWithFrame:bounds];
8134 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8135 [content_ setBackgroundColor:[UIColor whiteColor]];
8136 [content addSubview:content_];
8137
8138 [content_ setDelegate:self];
8139 [content_ setOpaque:YES];
8140 } return self;
8141 }
8142
8143 - (NSString *) accessibilityLabel {
8144 return label_;
8145 }
8146
8147 - (void) drawContentRect:(CGRect)rect {
8148 bool highlighted(highlighted_);
8149 float width(rect.size.width);
8150
8151 if (icon_ != nil)
8152 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8153
8154 if (highlighted)
8155 UISetColor(White_);
8156
8157 if (!highlighted)
8158 UISetColor(Black_);
8159 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8160
8161 if (!highlighted)
8162 UISetColor(Blue_);
8163 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8164 }
8165
8166 @end
8167 /* }}} */
8168 /* Source Controller {{{ */
8169 @interface SourceController : FilteredPackageListController {
8170 _transient Source *source_;
8171 NSString *key_;
8172 }
8173
8174 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8175
8176 @end
8177
8178 @implementation SourceController
8179
8180 - (NSURL *) navigationURL {
8181 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8182 }
8183
8184 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8185 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8186 source_ = source;
8187 key_ = [[source key] retain];
8188 } return self;
8189 }
8190
8191 - (void) reloadData {
8192 source_ = [database_ sourceWithKey:key_];
8193 [key_ release];
8194 key_ = [[source_ key] retain];
8195 [self setObject:source_];
8196
8197 [[self navigationItem] setTitle:[source_ label]];
8198
8199 [super reloadData];
8200 }
8201
8202 @end
8203 /* }}} */
8204 /* Sources Controller {{{ */
8205 @interface SourcesController : CYViewController <
8206 UITableViewDataSource,
8207 UITableViewDelegate
8208 > {
8209 _transient Database *database_;
8210 UITableView *list_;
8211 NSMutableArray *sources_;
8212 int offset_;
8213
8214 NSString *href_;
8215 UIProgressHUD *hud_;
8216 NSError *error_;
8217
8218 //NSURLConnection *installer_;
8219 NSURLConnection *trivial_;
8220 NSURLConnection *trivial_bz2_;
8221 NSURLConnection *trivial_gz_;
8222 //NSURLConnection *automatic_;
8223
8224 BOOL cydia_;
8225 }
8226
8227 - (id) initWithDatabase:(Database *)database;
8228 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8229
8230 @end
8231
8232 @implementation SourcesController
8233
8234 - (void) _releaseConnection:(NSURLConnection *)connection {
8235 if (connection != nil) {
8236 [connection cancel];
8237 //[connection setDelegate:nil];
8238 [connection release];
8239 }
8240 }
8241
8242 - (void) dealloc {
8243 [self releaseSubviews];
8244
8245 [href_ release];
8246 [hud_ release];
8247 [error_ release];
8248
8249 //[self _releaseConnection:installer_];
8250 [self _releaseConnection:trivial_];
8251 [self _releaseConnection:trivial_gz_];
8252 [self _releaseConnection:trivial_bz2_];
8253 //[self _releaseConnection:automatic_];
8254
8255 [sources_ release];
8256 [super dealloc];
8257 }
8258
8259 - (NSURL *) navigationURL {
8260 return [NSURL URLWithString:@"cydia://sources"];
8261 }
8262
8263 - (void) viewDidAppear:(BOOL)animated {
8264 [super viewDidAppear:animated];
8265 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8266 }
8267
8268 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8269 return offset_ == 0 ? 1 : 2;
8270 }
8271
8272 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8273 switch (section + (offset_ == 0 ? 1 : 0)) {
8274 case 0: return UCLocalize("ENTERED_BY_USER");
8275 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8276
8277 _nodefault
8278 }
8279 }
8280
8281 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8282 int count = [sources_ count];
8283 switch (section) {
8284 case 0: return (offset_ == 0 ? count : offset_);
8285 case 1: return count - offset_;
8286
8287 _nodefault
8288 }
8289 }
8290
8291 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8292 unsigned idx = 0;
8293 switch (indexPath.section) {
8294 case 0: idx = indexPath.row; break;
8295 case 1: idx = indexPath.row + offset_; break;
8296
8297 _nodefault
8298 }
8299 return [sources_ objectAtIndex:idx];
8300 }
8301
8302 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8303 static NSString *cellIdentifier = @"SourceCell";
8304
8305 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8306 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8307 [cell setSource:[self sourceAtIndexPath:indexPath]];
8308 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8309
8310 return cell;
8311 }
8312
8313 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8314 Source *source = [self sourceAtIndexPath:indexPath];
8315
8316 SourceController *controller = [[[SourceController alloc]
8317 initWithDatabase:database_
8318 source:source
8319 ] autorelease];
8320
8321 [controller setDelegate:delegate_];
8322
8323 [[self navigationController] pushViewController:controller animated:YES];
8324 }
8325
8326 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8327 Source *source = [self sourceAtIndexPath:indexPath];
8328 return [source record] != nil;
8329 }
8330
8331 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8332 Source *source = [self sourceAtIndexPath:indexPath];
8333 [Sources_ removeObjectForKey:[source key]];
8334 [delegate_ syncData];
8335 }
8336
8337 - (void) complete {
8338 [delegate_ addTrivialSource:href_];
8339 [delegate_ syncData];
8340 }
8341
8342 - (NSString *) getWarning {
8343 NSString *href(href_);
8344 NSRange colon([href rangeOfString:@"://"]);
8345 if (colon.location != NSNotFound)
8346 href = [href substringFromIndex:(colon.location + 3)];
8347 href = [href stringByAddingPercentEscapes];
8348 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8349 href = [href stringByCachingURLWithCurrentCDN];
8350
8351 NSURL *url([NSURL URLWithString:href]);
8352
8353 NSStringEncoding encoding;
8354 NSError *error(nil);
8355
8356 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8357 return [warning length] == 0 ? nil : warning;
8358 return nil;
8359 }
8360
8361 - (void) _endConnection:(NSURLConnection *)connection {
8362 // XXX: the memory management in this method is horribly awkward
8363
8364 NSURLConnection **field = NULL;
8365 if (connection == trivial_)
8366 field = &trivial_;
8367 else if (connection == trivial_bz2_)
8368 field = &trivial_bz2_;
8369 else if (connection == trivial_gz_)
8370 field = &trivial_gz_;
8371 _assert(field != NULL);
8372 [connection release];
8373 *field = nil;
8374
8375 if (
8376 trivial_ == nil &&
8377 trivial_bz2_ == nil &&
8378 trivial_gz_ == nil
8379 ) {
8380 bool defer(false);
8381
8382 if (cydia_) {
8383 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8384 defer = true;
8385
8386 UIAlertView *alert = [[[UIAlertView alloc]
8387 initWithTitle:UCLocalize("SOURCE_WARNING")
8388 message:warning
8389 delegate:self
8390 cancelButtonTitle:UCLocalize("CANCEL")
8391 otherButtonTitles:
8392 UCLocalize("ADD_ANYWAY"),
8393 nil
8394 ] autorelease];
8395
8396 [alert setContext:@"warning"];
8397 [alert setNumberOfRows:1];
8398 [alert show];
8399 } else
8400 [self complete];
8401 } else if (error_ != nil) {
8402 UIAlertView *alert = [[[UIAlertView alloc]
8403 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8404 message:[error_ localizedDescription]
8405 delegate:self
8406 cancelButtonTitle:UCLocalize("OK")
8407 otherButtonTitles:nil
8408 ] autorelease];
8409
8410 [alert setContext:@"urlerror"];
8411 [alert show];
8412 } else {
8413 UIAlertView *alert = [[[UIAlertView alloc]
8414 initWithTitle:UCLocalize("NOT_REPOSITORY")
8415 message:UCLocalize("NOT_REPOSITORY_EX")
8416 delegate:self
8417 cancelButtonTitle:UCLocalize("OK")
8418 otherButtonTitles:nil
8419 ] autorelease];
8420
8421 [alert setContext:@"trivial"];
8422 [alert show];
8423 }
8424
8425 [delegate_ releaseNetworkActivityIndicator];
8426
8427 [delegate_ removeProgressHUD:hud_];
8428 [hud_ autorelease];
8429 hud_ = nil;
8430
8431 if (!defer) {
8432 [href_ release];
8433 href_ = nil;
8434 }
8435
8436 if (error_ != nil) {
8437 [error_ release];
8438 error_ = nil;
8439 }
8440 }
8441 }
8442
8443 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8444 switch ([response statusCode]) {
8445 case 200:
8446 cydia_ = YES;
8447 }
8448 }
8449
8450 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8451 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8452 if (error_ != nil)
8453 error_ = [error retain];
8454 [self _endConnection:connection];
8455 }
8456
8457 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8458 [self _endConnection:connection];
8459 }
8460
8461 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8462 NSMutableURLRequest *request = [NSMutableURLRequest
8463 requestWithURL:[NSURL URLWithString:href]
8464 cachePolicy:NSURLRequestUseProtocolCachePolicy
8465 timeoutInterval:120.0
8466 ];
8467
8468 [request setHTTPMethod:method];
8469
8470 if (Machine_ != NULL)
8471 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8472 if (UniqueID_ != nil)
8473 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8474
8475 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8476 }
8477
8478 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8479 NSString *context([alert context]);
8480
8481 if ([context isEqualToString:@"source"]) {
8482 switch (button) {
8483 case 1: {
8484 NSString *href = [[alert textField] text];
8485
8486 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8487
8488 if (![href hasSuffix:@"/"])
8489 href_ = [href stringByAppendingString:@"/"];
8490 else
8491 href_ = href;
8492 href_ = [href_ retain];
8493
8494 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8495 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8496 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8497 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8498
8499 cydia_ = false;
8500
8501 // XXX: this is stupid
8502 hud_ = [[delegate_ addProgressHUD] retain];
8503 [hud_ setText:UCLocalize("VERIFYING_URL")];
8504 [delegate_ retainNetworkActivityIndicator];
8505 } break;
8506
8507 case 0:
8508 break;
8509
8510 _nodefault
8511 }
8512
8513 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8514 } else if ([context isEqualToString:@"trivial"])
8515 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8516 else if ([context isEqualToString:@"urlerror"])
8517 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8518 else if ([context isEqualToString:@"warning"]) {
8519 switch (button) {
8520 case 1:
8521 [self complete];
8522 break;
8523
8524 case 0:
8525 break;
8526
8527 _nodefault
8528 }
8529
8530 [href_ release];
8531 href_ = nil;
8532
8533 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8534 }
8535 }
8536
8537 - (void) loadView {
8538 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8539
8540 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8541 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8542 [list_ setRowHeight:56];
8543 [list_ setDataSource:self];
8544 [list_ setDelegate:self];
8545 [[self view] addSubview:list_];
8546 }
8547
8548 - (void) viewDidLoad {
8549 [super viewDidLoad];
8550
8551 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8552 [self updateButtonsForEditingStatus:NO animated:NO];
8553 }
8554
8555 - (void) releaseSubviews {
8556 [list_ release];
8557 list_ = nil;
8558 }
8559
8560 - (id) initWithDatabase:(Database *)database {
8561 if ((self = [super init]) != nil) {
8562 database_ = database;
8563 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8564 } return self;
8565 }
8566
8567 - (void) reloadData {
8568 [super reloadData];
8569
8570 pkgSourceList list;
8571 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8572 return;
8573
8574 [sources_ removeAllObjects];
8575 [sources_ addObjectsFromArray:[database_ sources]];
8576 _trace();
8577 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8578 _trace();
8579
8580 int count([sources_ count]);
8581 offset_ = 0;
8582 for (int i = 0; i != count; i++) {
8583 if ([[sources_ objectAtIndex:i] record] == nil)
8584 break;
8585 offset_++;
8586 }
8587
8588 [list_ setEditing:NO];
8589 [self updateButtonsForEditingStatus:NO animated:NO];
8590 [list_ reloadData];
8591 }
8592
8593 - (void) showAddSourcePrompt {
8594 UIAlertView *alert = [[[UIAlertView alloc]
8595 initWithTitle:UCLocalize("ENTER_APT_URL")
8596 message:nil
8597 delegate:self
8598 cancelButtonTitle:UCLocalize("CANCEL")
8599 otherButtonTitles:
8600 UCLocalize("ADD_SOURCE"),
8601 nil
8602 ] autorelease];
8603
8604 [alert setContext:@"source"];
8605 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8606
8607 [alert setNumberOfRows:1];
8608 [alert addTextFieldWithValue:@"http://" label:@""];
8609
8610 UITextInputTraits *traits = [[alert textField] textInputTraits];
8611 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8612 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8613 [traits setKeyboardType:UIKeyboardTypeURL];
8614 // XXX: UIReturnKeyDone
8615 [traits setReturnKeyType:UIReturnKeyNext];
8616
8617 [alert show];
8618 }
8619
8620 - (void) addButtonClicked {
8621 [self showAddSourcePrompt];
8622 }
8623
8624 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8625 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8626 initWithTitle:UCLocalize("ADD")
8627 style:UIBarButtonItemStylePlain
8628 target:self
8629 action:@selector(addButtonClicked)
8630 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8631
8632 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8633 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8634 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8635 target:self
8636 action:@selector(editButtonClicked)
8637 ] autorelease] animated:animated];
8638
8639 if (IsWildcat_ && !editing)
8640 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8641 initWithTitle:UCLocalize("SETTINGS")
8642 style:UIBarButtonItemStylePlain
8643 target:self
8644 action:@selector(settingsButtonClicked)
8645 ] autorelease]];
8646 }
8647
8648 - (void) settingsButtonClicked {
8649 [delegate_ showSettings];
8650 }
8651
8652 - (void) editButtonClicked {
8653 [list_ setEditing:![list_ isEditing] animated:YES];
8654
8655 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8656 }
8657
8658 @end
8659 /* }}} */
8660
8661 /* Settings Controller {{{ */
8662 @interface SettingsController : CYViewController <
8663 UITableViewDataSource,
8664 UITableViewDelegate
8665 > {
8666 _transient Database *database_;
8667 // XXX: ok, "roledelegate_"?...
8668 _transient id roledelegate_;
8669 UITableView *table_;
8670 UISegmentedControl *segment_;
8671 UIView *container_;
8672 }
8673
8674 - (void) showDoneButton;
8675 - (void) resizeSegmentedControl;
8676
8677 @end
8678
8679 @implementation SettingsController
8680
8681 - (void) dealloc {
8682 [self releaseSubviews];
8683
8684 [super dealloc];
8685 }
8686
8687 - (void) loadView {
8688 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8689
8690 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8691 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8692 [table_ setDelegate:self];
8693 [table_ setDataSource:self];
8694 [[self view] addSubview:table_];
8695
8696 NSArray *items = [NSArray arrayWithObjects:
8697 UCLocalize("USER"),
8698 UCLocalize("HACKER"),
8699 UCLocalize("DEVELOPER"),
8700 nil];
8701 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8702 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8703 [container_ addSubview:segment_];
8704 }
8705
8706 - (void) viewDidLoad {
8707 [super viewDidLoad];
8708
8709 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8710
8711 int index = -1;
8712 if ([Role_ isEqualToString:@"User"]) index = 0;
8713 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8714 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8715 if (index != -1) {
8716 [segment_ setSelectedSegmentIndex:index];
8717 [self showDoneButton];
8718 }
8719
8720 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8721 [self resizeSegmentedControl];
8722 }
8723
8724 - (void) releaseSubviews {
8725 [table_ release];
8726 table_ = nil;
8727
8728 [segment_ release];
8729 segment_ = nil;
8730
8731 [container_ release];
8732 container_ = nil;
8733 }
8734
8735 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8736 if ((self = [super init]) != nil) {
8737 database_ = database;
8738 roledelegate_ = delegate;
8739 } return self;
8740 }
8741
8742 - (void) resizeSegmentedControl {
8743 CGFloat width = [[self view] frame].size.width;
8744 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8745 }
8746
8747 - (void) viewWillAppear:(BOOL)animated {
8748 [super viewWillAppear:animated];
8749
8750 [self resizeSegmentedControl];
8751 }
8752
8753 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8754 [self resizeSegmentedControl];
8755 }
8756
8757 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8758 [self resizeSegmentedControl];
8759 }
8760
8761 - (void) save {
8762 NSString *role(nil);
8763
8764 switch ([segment_ selectedSegmentIndex]) {
8765 case 0: role = @"User"; break;
8766 case 1: role = @"Hacker"; break;
8767 case 2: role = @"Developer"; break;
8768
8769 _nodefault
8770 }
8771
8772 if (![role isEqualToString:Role_]) {
8773 bool rolling(Role_ == nil);
8774 Role_ = role;
8775
8776 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8777 Role_, @"Role",
8778 nil];
8779
8780 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8781 Changed_ = true;
8782
8783 if (rolling)
8784 [roledelegate_ loadData];
8785 else
8786 [roledelegate_ updateData];
8787 }
8788 }
8789
8790 - (void) segmentChanged:(UISegmentedControl *)control {
8791 [self showDoneButton];
8792 }
8793
8794 - (void) saveAndClose {
8795 [self save];
8796
8797 [[self navigationItem] setRightBarButtonItem:nil];
8798 [[self navigationController] dismissModalViewControllerAnimated:YES];
8799 }
8800
8801 - (void) doneButtonClicked {
8802 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8803 [spinner startAnimating];
8804 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8805 [[self navigationItem] setRightBarButtonItem:spinItem];
8806
8807 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8808 }
8809
8810 - (void) showDoneButton {
8811 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8812 initWithTitle:UCLocalize("DONE")
8813 style:UIBarButtonItemStyleDone
8814 target:self
8815 action:@selector(doneButtonClicked)
8816 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8817 }
8818
8819 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8820 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8821 return 6;
8822 }
8823
8824 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8825 return 0; // :(
8826 }
8827
8828 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8829 return nil; // This method is required by the protocol.
8830 }
8831
8832 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8833 if (section == 1)
8834 return UCLocalize("ROLE_EX");
8835 if (section == 4)
8836 return [NSString stringWithFormat:
8837 @"%@: %@\n%@: %@\n%@: %@",
8838 UCLocalize("USER"), UCLocalize("USER_EX"),
8839 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8840 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8841 ];
8842 else return nil;
8843 }
8844
8845 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8846 return section == 3 ? 44.0f : 0;
8847 }
8848
8849 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8850 return section == 3 ? container_ : nil;
8851 }
8852
8853 - (void) reloadData {
8854 [super reloadData];
8855
8856 [table_ reloadData];
8857 }
8858
8859 @end
8860 /* }}} */
8861 /* Stash Controller {{{ */
8862 @interface StashController : CYViewController {
8863 UIActivityIndicatorView *spinner_;
8864 UILabel *status_;
8865 UILabel *caption_;
8866 }
8867
8868 @end
8869
8870 @implementation StashController
8871
8872 - (void) dealloc {
8873 [self releaseSubviews];
8874
8875 [super dealloc];
8876 }
8877
8878 - (void) loadView {
8879 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8880 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8881
8882 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8883 CGRect spinrect = [spinner_ frame];
8884 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8885 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8886 [spinner_ setFrame:spinrect];
8887 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8888 [[self view] addSubview:spinner_];
8889 [spinner_ startAnimating];
8890
8891 CGRect captrect;
8892 captrect.size.width = [[self view] frame].size.width;
8893 captrect.size.height = 40.0f;
8894 captrect.origin.x = 0;
8895 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8896 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8897 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8898 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8899 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8900 [caption_ setTextColor:[UIColor whiteColor]];
8901 [caption_ setBackgroundColor:[UIColor clearColor]];
8902 [caption_ setShadowColor:[UIColor blackColor]];
8903 [caption_ setTextAlignment:UITextAlignmentCenter];
8904 [[self view] addSubview:caption_];
8905
8906 CGRect statusrect;
8907 statusrect.size.width = [[self view] frame].size.width;
8908 statusrect.size.height = 30.0f;
8909 statusrect.origin.x = 0;
8910 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8911 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8912 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8913 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8914 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8915 [status_ setTextColor:[UIColor whiteColor]];
8916 [status_ setBackgroundColor:[UIColor clearColor]];
8917 [status_ setShadowColor:[UIColor blackColor]];
8918 [status_ setTextAlignment:UITextAlignmentCenter];
8919 [[self view] addSubview:status_];
8920 }
8921
8922 - (void) releaseSubviews {
8923 [spinner_ release];
8924 spinner_ = nil;
8925
8926 [status_ release];
8927 status_ = nil;
8928
8929 [caption_ release];
8930 caption_ = nil;
8931 }
8932
8933 @end
8934 /* }}} */
8935
8936 @interface Cydia : UIApplication <
8937 ConfirmationControllerDelegate,
8938 DatabaseDelegate,
8939 CydiaDelegate,
8940 UINavigationControllerDelegate,
8941 UITabBarControllerDelegate
8942 > {
8943 // XXX: evaluate all fields for _transient
8944
8945 UIWindow *window_;
8946 CYTabBarController *tabbar_;
8947 CYEmulatedLoadingController *emulated_;
8948
8949 NSMutableArray *essential_;
8950 NSMutableArray *broken_;
8951
8952 Database *database_;
8953
8954 NSURL *starturl_;
8955
8956 unsigned locked_;
8957 unsigned activity_;
8958
8959 StashController *stash_;
8960
8961 bool loaded_;
8962 }
8963
8964 - (void) loadData;
8965
8966 @end
8967
8968 @implementation Cydia
8969
8970 - (void) beginUpdate {
8971 [tabbar_ beginUpdate];
8972 }
8973
8974 - (BOOL) updating {
8975 return [tabbar_ updating];
8976 }
8977
8978 - (void) _loaded {
8979 if ([broken_ count] != 0) {
8980 int count = [broken_ count];
8981
8982 UIAlertView *alert = [[[UIAlertView alloc]
8983 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8984 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8985 delegate:self
8986 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8987 otherButtonTitles:
8988 UCLocalize("TEMPORARY_IGNORE"),
8989 nil
8990 ] autorelease];
8991
8992 [alert setContext:@"fixhalf"];
8993 [alert setNumberOfRows:2];
8994 [alert show];
8995 } else if (!Ignored_ && [essential_ count] != 0) {
8996 int count = [essential_ count];
8997
8998 UIAlertView *alert = [[[UIAlertView alloc]
8999 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9000 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9001 delegate:self
9002 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9003 otherButtonTitles:
9004 UCLocalize("UPGRADE_ESSENTIAL"),
9005 UCLocalize("COMPLETE_UPGRADE"),
9006 nil
9007 ] autorelease];
9008
9009 [alert setContext:@"upgrade"];
9010 [alert show];
9011 }
9012 }
9013
9014 - (void) _saveConfig {
9015 _trace();
9016 MetaFile_.Sync();
9017 _trace();
9018
9019 if (Changed_) {
9020 NSString *error(nil);
9021
9022 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9023 _trace();
9024 NSError *error(nil);
9025 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9026 NSLog(@"failure to save metadata data: %@", error);
9027 _trace();
9028
9029 Changed_ = false;
9030 } else {
9031 NSLog(@"failure to serialize metadata: %@", error);
9032 }
9033 }
9034 }
9035
9036 // Navigation controller for the queuing badge.
9037 - (UINavigationController *) queueNavigationController {
9038 NSArray *controllers = [tabbar_ viewControllers];
9039 return [controllers objectAtIndex:3];
9040 }
9041
9042 - (void) unloadData {
9043 [tabbar_ unloadData];
9044 }
9045
9046 - (void) _updateData {
9047 [self _saveConfig];
9048
9049 [self unloadData];
9050
9051 UINavigationController *navigation = [self queueNavigationController];
9052
9053 id queuedelegate = nil;
9054 if ([[navigation viewControllers] count] > 0)
9055 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9056
9057 [queuedelegate queueStatusDidChange];
9058 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9059 }
9060
9061 - (void) _refreshIfPossible:(NSDate *)update {
9062 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9063
9064 bool recently = false;
9065 if (update != nil) {
9066 NSTimeInterval interval([update timeIntervalSinceNow]);
9067 if (interval <= 0 && interval > -(15*60))
9068 recently = true;
9069 }
9070
9071 // Don't automatic refresh if:
9072 // - We already refreshed recently.
9073 // - We already auto-refreshed this launch.
9074 // - Auto-refresh is disabled.
9075 if (recently || loaded_ || ManualRefresh) {
9076 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9077
9078 // If we are cancelling, we need to make sure it knows it's already loaded.
9079 loaded_ = true;
9080 return;
9081 } else {
9082 // We are going to load, so remember that.
9083 loaded_ = true;
9084 }
9085
9086 SCNetworkReachabilityFlags flags; {
9087 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9088 SCNetworkReachabilityGetFlags(reachability, &flags);
9089 CFRelease(reachability);
9090 }
9091
9092 // XXX: this elaborate mess is what Apple is using to determine this? :(
9093 // XXX: do we care if the user has to intervene? maybe that's ok?
9094 bool reachable(
9095 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9096 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9097 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9098 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9099 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9100 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9101 )
9102 );
9103
9104 // If we can reach the server, auto-refresh!
9105 if (reachable)
9106 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9107
9108 [pool release];
9109 }
9110
9111 - (void) refreshIfPossible {
9112 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9113 }
9114
9115 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9116 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9117 [hud setText:UCLocalize("RELOADING_DATA")];
9118
9119 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9120
9121 if (hud != nil)
9122 [self removeProgressHUD:hud];
9123
9124 size_t changes(0);
9125
9126 [essential_ removeAllObjects];
9127 [broken_ removeAllObjects];
9128
9129 NSArray *packages([database_ packages]);
9130 for (Package *package in packages) {
9131 if ([package half])
9132 [broken_ addObject:package];
9133 if ([package upgradableAndEssential:NO]) {
9134 if ([package essential])
9135 [essential_ addObject:package];
9136 ++changes;
9137 }
9138 }
9139
9140 NSLog(@"changes:#%u", changes);
9141
9142 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9143 if (changes != 0) {
9144 _trace();
9145 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9146 [changesItem setBadgeValue:badge];
9147 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9148 [self setApplicationIconBadgeNumber:changes];
9149 } else {
9150 _trace();
9151 [changesItem setBadgeValue:nil];
9152 [changesItem setAnimatedBadge:NO];
9153 [self setApplicationIconBadgeNumber:0];
9154 }
9155
9156 [self _updateData];
9157
9158 [self refreshIfPossible];
9159 }
9160
9161 - (void) updateData {
9162 [self _updateData];
9163 }
9164
9165 - (void) update_ {
9166 [database_ update];
9167 }
9168
9169 - (void) complete {
9170 @synchronized (self) {
9171 [self _reloadDataWithInvocation:nil];
9172 }
9173 }
9174
9175 - (void) disemulate {
9176 if (emulated_ == nil)
9177 return;
9178
9179 [window_ addSubview:[tabbar_ view]];
9180 [[emulated_ view] removeFromSuperview];
9181 [emulated_ release];
9182 emulated_ = nil;
9183 [window_ setUserInteractionEnabled:YES];
9184 }
9185
9186 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9187 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9188 if (IsWildcat_)
9189 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9190
9191 UIViewController *parent;
9192 if (emulated_ == nil)
9193 parent = tabbar_;
9194 else if (!force)
9195 parent = emulated_;
9196 else {
9197 [self disemulate];
9198 parent = tabbar_;
9199 }
9200
9201 [parent presentModalViewController:navigation animated:YES];
9202 }
9203
9204 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9205 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9206
9207 if (navigation != nil)
9208 [navigation pushViewController:progress animated:YES];
9209 else
9210 [self presentModalViewController:progress force:YES];
9211
9212 [progress invoke:invocation withTitle:title];
9213 return progress;
9214 }
9215
9216 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9217 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9218 }
9219
9220 - (void) repairWithInvocation:(NSInvocation *)invocation {
9221 _trace();
9222 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9223 _trace();
9224 }
9225
9226 - (void) repairWithSelector:(SEL)selector {
9227 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9228 }
9229
9230 - (void) syncData {
9231 [self _saveConfig];
9232
9233 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9234 _assert(file != NULL);
9235
9236 for (NSString *key in [Sources_ allKeys]) {
9237 NSDictionary *source([Sources_ objectForKey:key]);
9238
9239 fprintf(file, "%s %s %s\n",
9240 [[source objectForKey:@"Type"] UTF8String],
9241 [[source objectForKey:@"URI"] UTF8String],
9242 [[source objectForKey:@"Distribution"] UTF8String]
9243 );
9244 }
9245
9246 fclose(file);
9247
9248 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9249
9250 [self complete];
9251 }
9252
9253 - (void) addTrivialSource:(NSString *)href {
9254 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9255 @"deb", @"Type",
9256 href, @"URI",
9257 @"./", @"Distribution",
9258 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9259
9260 Changed_ = true;
9261 }
9262
9263 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9264 @synchronized (self) {
9265 [self _reloadDataWithInvocation:invocation];
9266 }
9267 }
9268
9269 - (void) reloadData {
9270 [self reloadDataWithInvocation:nil];
9271 }
9272
9273 - (void) resolve {
9274 pkgProblemResolver *resolver = [database_ resolver];
9275
9276 resolver->InstallProtect();
9277 if (!resolver->Resolve(true))
9278 _error->Discard();
9279 }
9280
9281 - (bool) perform {
9282 // XXX: this is a really crappy way of doing this.
9283 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9284 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9285 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9286 if ([tabbar_ updating])
9287 [tabbar_ cancelUpdate];
9288
9289 if (![database_ prepare])
9290 return false;
9291
9292 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9293 [page setDelegate:self];
9294 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9295
9296 if (IsWildcat_)
9297 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9298 [tabbar_ presentModalViewController:confirm_ animated:YES];
9299
9300 return true;
9301 }
9302
9303 - (void) queue {
9304 @synchronized (self) {
9305 [self perform];
9306 }
9307 }
9308
9309 - (void) clearPackage:(Package *)package {
9310 @synchronized (self) {
9311 [package clear];
9312 [self resolve];
9313 [self perform];
9314 }
9315 }
9316
9317 - (void) installPackages:(NSArray *)packages {
9318 @synchronized (self) {
9319 for (Package *package in packages)
9320 [package install];
9321 [self resolve];
9322 [self perform];
9323 }
9324 }
9325
9326 - (void) installPackage:(Package *)package {
9327 @synchronized (self) {
9328 [package install];
9329 [self resolve];
9330 [self perform];
9331 }
9332 }
9333
9334 - (void) removePackage:(Package *)package {
9335 @synchronized (self) {
9336 [package remove];
9337 [self resolve];
9338 [self perform];
9339 }
9340 }
9341
9342 - (void) distUpgrade {
9343 @synchronized (self) {
9344 if (![database_ upgrade])
9345 return;
9346 [self perform];
9347 }
9348 }
9349
9350 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9351 Queuing_ = false;
9352 ++locked_;
9353 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9354 --locked_;
9355 [self complete];
9356 }
9357
9358 - (void) showSettings {
9359 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9360 }
9361
9362 - (void) retainNetworkActivityIndicator {
9363 if (activity_++ == 0)
9364 [self setNetworkActivityIndicatorVisible:YES];
9365
9366 #if TraceLogging
9367 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9368 #endif
9369 }
9370
9371 - (void) releaseNetworkActivityIndicator {
9372 if (--activity_ == 0)
9373 [self setNetworkActivityIndicatorVisible:NO];
9374
9375 #if TraceLogging
9376 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9377 #endif
9378
9379 }
9380
9381 - (void) cancelAndClear:(bool)clear {
9382 @synchronized (self) {
9383 if (clear) {
9384 [database_ clear];
9385 Queuing_ = false;
9386 } else {
9387 Queuing_ = true;
9388 }
9389
9390 [self _updateData];
9391 }
9392 }
9393
9394 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9395 NSString *context([alert context]);
9396
9397 if ([context isEqualToString:@"conffile"]) {
9398 FILE *input = [database_ input];
9399 if (button == [alert cancelButtonIndex])
9400 fprintf(input, "N\n");
9401 else if (button == [alert firstOtherButtonIndex])
9402 fprintf(input, "Y\n");
9403 fflush(input);
9404
9405 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9406 } else if ([context isEqualToString:@"fixhalf"]) {
9407 if (button == [alert cancelButtonIndex]) {
9408 @synchronized (self) {
9409 for (Package *broken in broken_) {
9410 [broken remove];
9411
9412 NSString *id = [broken id];
9413 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9414 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9415 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9416 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9417 }
9418
9419 [self resolve];
9420 [self perform];
9421 }
9422 } else if (button == [alert firstOtherButtonIndex]) {
9423 [broken_ removeAllObjects];
9424 [self _loaded];
9425 }
9426
9427 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9428 } else if ([context isEqualToString:@"upgrade"]) {
9429 if (button == [alert firstOtherButtonIndex]) {
9430 @synchronized (self) {
9431 for (Package *essential in essential_)
9432 [essential install];
9433
9434 [self resolve];
9435 [self perform];
9436 }
9437 } else if (button == [alert firstOtherButtonIndex] + 1) {
9438 [self distUpgrade];
9439 } else if (button == [alert cancelButtonIndex]) {
9440 Ignored_ = YES;
9441 }
9442
9443 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9444 }
9445 }
9446
9447 - (void) system:(NSString *)command { _pooled
9448 _trace();
9449 system([command UTF8String]);
9450 _trace();
9451 }
9452
9453 - (void) applicationWillSuspend {
9454 [database_ clean];
9455 [super applicationWillSuspend];
9456 }
9457
9458 - (BOOL) isSafeToSuspend {
9459 if (locked_ != 0) {
9460 #if !ForRelease
9461 NSLog(@"isSafeToSuspend: locked_ != 0");
9462 #endif
9463 return false;
9464 }
9465
9466 // Use external process status API internally.
9467 // This is probably a really bad idea.
9468 // XXX: what is the point of this? does this solve anything at all?
9469 uint64_t status = 0;
9470 int notify_token;
9471 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9472 notify_get_state(notify_token, &status);
9473 notify_cancel(notify_token);
9474 }
9475
9476 if (status != 0) {
9477 #if !ForRelease
9478 NSLog(@"isSafeToSuspend: status != 0");
9479 #endif
9480 return false;
9481 }
9482
9483 #if !ForRelease
9484 NSLog(@"isSafeToSuspend: -> true");
9485 #endif
9486 return true;
9487 }
9488
9489 - (void) applicationSuspend:(__GSEvent *)event {
9490 if ([self isSafeToSuspend])
9491 [super applicationSuspend:event];
9492 }
9493
9494 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9495 if ([self isSafeToSuspend])
9496 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9497 }
9498
9499 - (void) _setSuspended:(BOOL)value {
9500 if ([self isSafeToSuspend])
9501 [super _setSuspended:value];
9502 }
9503
9504 - (UIProgressHUD *) addProgressHUD {
9505 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9506 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9507
9508 [window_ setUserInteractionEnabled:NO];
9509
9510 UIViewController *target(tabbar_);
9511 if (UIViewController *modal = [target modalViewController])
9512 target = modal;
9513
9514 UIView *view([target view]);
9515 [view addSubview:hud];
9516
9517 [hud show:YES];
9518
9519 ++locked_;
9520 return hud;
9521 }
9522
9523 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9524 --locked_;
9525 [hud show:NO];
9526 [hud removeFromSuperview];
9527 [window_ setUserInteractionEnabled:YES];
9528 }
9529
9530 - (CYViewController *) pageForPackage:(NSString *)name {
9531 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9532 }
9533
9534 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9535 NSString *scheme([[url scheme] lowercaseString]);
9536 if ([[url absoluteString] length] <= [scheme length] + 3)
9537 return nil;
9538 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9539 NSArray *components([path pathComponents]);
9540
9541 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9542 return [self pageForPackage:[components objectAtIndex:1]];
9543
9544 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9545 return nil;
9546
9547 NSString *base([components objectAtIndex:0]);
9548
9549 CYViewController *controller = nil;
9550
9551 if ([base isEqualToString:@"url"]) {
9552 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9553 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9554 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9555 } else if (!external && [components count] == 1) {
9556 if ([base isEqualToString:@"manage"]) {
9557 controller = [[[ManageController alloc] init] autorelease];
9558 }
9559
9560 if ([base isEqualToString:@"sources"]) {
9561 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9562 }
9563
9564 if ([base isEqualToString:@"home"]) {
9565 controller = [[[HomeController alloc] init] autorelease];
9566 }
9567
9568 if ([base isEqualToString:@"sections"]) {
9569 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9570 }
9571
9572 if ([base isEqualToString:@"search"]) {
9573 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9574 }
9575
9576 if ([base isEqualToString:@"changes"]) {
9577 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9578 }
9579
9580 if ([base isEqualToString:@"installed"]) {
9581 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9582 }
9583 } else if ([components count] == 2) {
9584 NSString *argument = [components objectAtIndex:1];
9585
9586 if ([base isEqualToString:@"package"]) {
9587 controller = [self pageForPackage:argument];
9588 }
9589
9590 if (!external && [base isEqualToString:@"search"]) {
9591 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9592 [(SearchController *)controller setSearchTerm:argument];
9593 }
9594
9595 if (!external && [base isEqualToString:@"sections"]) {
9596 if ([argument isEqualToString:@"all"])
9597 argument = nil;
9598 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9599 }
9600
9601 if (!external && [base isEqualToString:@"sources"]) {
9602 if ([argument isEqualToString:@"add"]) {
9603 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9604 [(SourcesController *)controller showAddSourcePrompt];
9605 } else {
9606 Source *source = [database_ sourceWithKey:argument];
9607 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9608 }
9609 }
9610
9611 if (!external && [base isEqualToString:@"launch"]) {
9612 [self launchApplicationWithIdentifier:argument suspended:NO];
9613 return nil;
9614 }
9615 } else if (!external && [components count] == 3) {
9616 NSString *arg1 = [components objectAtIndex:1];
9617 NSString *arg2 = [components objectAtIndex:2];
9618
9619 if ([base isEqualToString:@"package"]) {
9620 if ([arg2 isEqualToString:@"settings"]) {
9621 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9622 } else if ([arg2 isEqualToString:@"files"]) {
9623 if (Package *package = [database_ packageWithName:arg1]) {
9624 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9625 [(FileTable *)controller setPackage:package];
9626 }
9627 }
9628 }
9629 }
9630
9631 [controller setDelegate:self];
9632 return controller;
9633 }
9634
9635 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9636 CYViewController *page([self pageForURL:url forExternal:external]);
9637
9638 if (page != nil) {
9639 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9640 [nav setViewControllers:[NSArray arrayWithObject:page]];
9641 [tabbar_ setUnselectedViewController:nav];
9642 }
9643
9644 return page != nil;
9645 }
9646
9647 - (void) applicationOpenURL:(NSURL *)url {
9648 [super applicationOpenURL:url];
9649
9650 if (!loaded_) starturl_ = [url retain];
9651 else [self openCydiaURL:url forExternal:YES];
9652 }
9653
9654 - (void) applicationWillResignActive:(UIApplication *)application {
9655 // Stop refreshing if you get a phone call or lock the device.
9656 if ([tabbar_ updating])
9657 [tabbar_ cancelUpdate];
9658
9659 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9660 [super applicationWillResignActive:application];
9661 }
9662
9663 - (void) applicationWillTerminate:(UIApplication *)application {
9664 Changed_ = true;
9665 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9666 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9667 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9668
9669 [self _saveConfig];
9670 }
9671
9672 - (void) setConfigurationData:(NSString *)data {
9673 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9674
9675 if (!conffile_r(data)) {
9676 lprintf("E:invalid conffile\n");
9677 return;
9678 }
9679
9680 NSString *ofile = conffile_r[1];
9681 //NSString *nfile = conffile_r[2];
9682
9683 UIAlertView *alert = [[[UIAlertView alloc]
9684 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9685 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9686 delegate:self
9687 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9688 otherButtonTitles:
9689 UCLocalize("ACCEPT_NEW_COPY"),
9690 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9691 nil
9692 ] autorelease];
9693
9694 [alert setContext:@"conffile"];
9695 [alert setNumberOfRows:2];
9696 [alert show];
9697 }
9698
9699 - (void) addStashController {
9700 ++locked_;
9701 stash_ = [[StashController alloc] init];
9702 [window_ addSubview:[stash_ view]];
9703 }
9704
9705 - (void) removeStashController {
9706 [[stash_ view] removeFromSuperview];
9707 [stash_ release];
9708 --locked_;
9709 }
9710
9711 - (void) stash {
9712 [self setIdleTimerDisabled:YES];
9713
9714 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9715 UpdateExternalStatus(1);
9716 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9717 UpdateExternalStatus(0);
9718
9719 [self removeStashController];
9720
9721 if (ExecFork() == 0) {
9722 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9723 perror("launchctl stop");
9724 }
9725 }
9726
9727 - (void) setupViewControllers {
9728 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9729
9730 NSMutableArray *items([NSMutableArray arrayWithObjects:
9731 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9732 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9733 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9734 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9735 nil]);
9736
9737 if (IsWildcat_) {
9738 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9739 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9740 } else {
9741 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9742 }
9743
9744 NSMutableArray *controllers([NSMutableArray array]);
9745 for (UITabBarItem *item in items) {
9746 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9747 [controller setTabBarItem:item];
9748 [controllers addObject:controller];
9749 }
9750 [tabbar_ setViewControllers:controllers];
9751
9752 [tabbar_ setUpdateDelegate:self];
9753 }
9754
9755 - (void) applicationDidFinishLaunching:(id)unused {
9756 _trace();
9757 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9758 [self setApplicationSupportsShakeToEdit:NO];
9759
9760 @synchronized (HostConfig_) {
9761 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9762 }
9763
9764 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9765 initWithMemoryCapacity:524288
9766 diskCapacity:10485760
9767 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9768 ] autorelease]];
9769
9770 [CYBrowserController _initialize];
9771
9772 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9773
9774 Font12_ = [[UIFont systemFontOfSize:12] retain];
9775 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9776 Font14_ = [[UIFont systemFontOfSize:14] retain];
9777 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9778 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9779
9780 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9781 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9782
9783 // XXX: I really need this thing... like, seriously... I'm sorry
9784 [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9785
9786 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9787 [window_ orderFront:self];
9788 [window_ makeKey:self];
9789 [window_ setHidden:NO];
9790
9791 if (
9792 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9793 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9794 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9795 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9796 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9797 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9798 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9799 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9800 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9801 false
9802 ) {
9803 [self addStashController];
9804 // XXX: this would be much cleaner as a yieldToSelector:
9805 // that way the removeStashController could happen right here inline
9806 // we also could no longer require the useless stash_ field anymore
9807 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9808 return;
9809 }
9810
9811 database_ = [Database sharedInstance];
9812 [database_ setDelegate:self];
9813
9814 [window_ setUserInteractionEnabled:NO];
9815 [self setupViewControllers];
9816
9817 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9818 [window_ addSubview:[emulated_ view]];
9819
9820 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9821 _trace();
9822 }
9823
9824 - (NSArray *) defaultStartPages {
9825 NSMutableArray *standard = [NSMutableArray array];
9826 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9827 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9828 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9829 if (!IsWildcat_) {
9830 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9831 } else {
9832 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9833 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9834 }
9835 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9836 return standard;
9837 }
9838
9839 - (void) loadData {
9840 _trace();
9841 if (Role_ == nil) {
9842 [window_ setUserInteractionEnabled:YES];
9843 [self showSettings];
9844 return;
9845 } else {
9846 if ([emulated_ modalViewController] != nil)
9847 [emulated_ dismissModalViewControllerAnimated:YES];
9848 [window_ setUserInteractionEnabled:NO];
9849 }
9850
9851 [self reloadData];
9852 PrintTimes();
9853
9854 [self disemulate];
9855
9856 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9857 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9858 int standardIndex = 0;
9859 NSArray *standard = [self defaultStartPages];
9860
9861 BOOL valid = YES;
9862
9863 if (saved == nil)
9864 valid = NO;
9865
9866 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9867 if (valid && closed != nil) {
9868 NSTimeInterval interval([closed timeIntervalSinceNow]);
9869 // XXX: Is 15 minutes the optimal time here?
9870 if (interval > 0 && interval <= -(15*60))
9871 valid = NO;
9872 }
9873
9874 if (valid && [saved count] != [standard count])
9875 valid = NO;
9876
9877 if (valid) {
9878 for (unsigned int i = 0; i < [standard count]; i++) {
9879 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9880 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9881 // but it's good enough for now.
9882 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9883 valid = NO;
9884 break;
9885 }
9886 }
9887 }
9888
9889 NSArray *items = nil;
9890 if (valid) {
9891 [tabbar_ setSelectedIndex:savedIndex];
9892 items = saved;
9893 } else {
9894 [tabbar_ setSelectedIndex:standardIndex];
9895 items = standard;
9896 }
9897
9898 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9899 NSArray *stack = [items objectAtIndex:tab];
9900 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9901 NSMutableArray *current = [NSMutableArray array];
9902
9903 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9904 NSString *addr = [stack objectAtIndex:nav];
9905 NSURL *url = [NSURL URLWithString:addr];
9906 CYViewController *page = [self pageForURL:url forExternal:NO];
9907 if (page != nil)
9908 [current addObject:page];
9909 }
9910
9911 [navigation setViewControllers:current];
9912 }
9913
9914 // (Try to) show the startup URL.
9915 if (starturl_ != nil) {
9916 [self openCydiaURL:starturl_ forExternal:NO];
9917 [starturl_ release];
9918 starturl_ = nil;
9919 }
9920 }
9921
9922 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9923 if (item != nil && IsWildcat_) {
9924 [sheet showFromBarButtonItem:item animated:YES];
9925 } else {
9926 [sheet showInView:window_];
9927 }
9928 }
9929
9930 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9931 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9932 [progress setTitle:task];
9933 [progress addProgressEvent:event];
9934 }
9935
9936 - (void) addProgressEventForTask:(NSArray *)data {
9937 CydiaProgressEvent *event([data objectAtIndex:0]);
9938 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9939 [self addProgressEvent:event forTask:task];
9940 }
9941
9942 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9943 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9944 }
9945
9946 @end
9947
9948 /*IMP alloc_;
9949 id Alloc_(id self, SEL selector) {
9950 id object = alloc_(self, selector);
9951 lprintf("[%s]A-%p\n", self->isa->name, object);
9952 return object;
9953 }*/
9954
9955 /*IMP dealloc_;
9956 id Dealloc_(id self, SEL selector) {
9957 id object = dealloc_(self, selector);
9958 lprintf("[%s]D-%p\n", self->isa->name, object);
9959 return object;
9960 }*/
9961
9962 Class $WebDefaultUIKitDelegate;
9963
9964 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9965 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9966 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9967 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9968 }
9969
9970 static NSSet *MobilizedFiles_;
9971
9972 static NSURL *MobilizeURL(NSURL *url) {
9973 NSString *path([url path]);
9974 if ([path hasPrefix:@"/var/root/"]) {
9975 NSString *file([path substringFromIndex:10]);
9976 if ([MobilizedFiles_ containsObject:file])
9977 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9978 }
9979
9980 return url;
9981 }
9982
9983 Class $CFXPreferencesPropertyListSource;
9984 @class CFXPreferencesPropertyListSource;
9985
9986 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9987 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9988 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9989 url = MobilizeURL(url);
9990 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9991 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9992 url = old;
9993 [pool release];
9994 return value;
9995 }
9996
9997 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9998 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9999 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10000 url = MobilizeURL(url);
10001 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10002 //NSLog(@"%@ %@", [url absoluteString], value);
10003 url = old;
10004 [pool release];
10005 return value;
10006 }
10007
10008 Class $NSURLConnection;
10009
10010 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10011 NSMutableURLRequest *copy([request mutableCopy]);
10012
10013 NSURL *url([copy URL]);
10014 NSString *host([url host]);
10015 NSString *scheme([[url scheme] lowercaseString]);
10016
10017 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10018
10019 @synchronized (HostConfig_) {
10020 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10021 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10022 [copy setHTTPShouldUsePipelining:YES];
10023 }
10024
10025 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10026 } return self;
10027 }
10028
10029 int main(int argc, char *argv[]) { _pooled
10030 _trace();
10031
10032 UpdateExternalStatus(0);
10033
10034 if (Class $UIDevice = objc_getClass("UIDevice")) {
10035 UIDevice *device([$UIDevice currentDevice]);
10036 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10037 } else
10038 IsWildcat_ = false;
10039
10040 UIScreen *screen([UIScreen mainScreen]);
10041 if ([screen respondsToSelector:@selector(scale)])
10042 ScreenScale_ = [screen scale];
10043 else
10044 ScreenScale_ = 1;
10045
10046 UIDevice *device([UIDevice currentDevice]);
10047 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10048 Idiom_ = @"iphone";
10049 else {
10050 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10051 if (idiom == UIUserInterfaceIdiomPhone)
10052 Idiom_ = @"iphone";
10053 else if (idiom == UIUserInterfaceIdiomPad)
10054 Idiom_ = @"ipad";
10055 else
10056 NSLog(@"unknown UIUserInterfaceIdiom!");
10057 }
10058
10059 SessionData_ = [[NSMutableDictionary alloc] initWithCapacity:4];
10060
10061 HostConfig_ = [[NSObject alloc] init];
10062 @synchronized (HostConfig_) {
10063 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10064 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10065 }
10066
10067 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
10068
10069 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10070
10071 MobilizedFiles_ = [NSMutableSet setWithObjects:
10072 @"Library/Preferences/com.apple.Accessibility.plist",
10073 @"Library/Preferences/com.apple.preferences.sounds.plist",
10074 nil];
10075
10076 /* Library Hacks {{{ */
10077 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10078
10079 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10080
10081 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10082 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10083 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10084 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10085 }
10086
10087 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10088 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10089 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10090 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10091 }
10092
10093 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10094 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10095 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10096 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10097 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10098 }
10099
10100 $NSURLConnection = objc_getClass("NSURLConnection");
10101 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10102 if (NSURLConnection$init$ != NULL) {
10103 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10104 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10105 }
10106 /* }}} */
10107 /* Set Locale {{{ */
10108 Locale_ = CFLocaleCopyCurrent();
10109 Languages_ = [NSLocale preferredLanguages];
10110
10111 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10112 //NSLog(@"%@", [Languages_ description]);
10113
10114 const char *lang;
10115 if (Locale_ != NULL)
10116 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10117 else if (Languages_ != nil && [Languages_ count] != 0)
10118 lang = [[Languages_ objectAtIndex:0] UTF8String];
10119 else
10120 // XXX: consider just setting to C and then falling through?
10121 lang = NULL;
10122
10123 if (lang != NULL) {
10124 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10125 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10126 }
10127
10128 NSLog(@"Setting Language: %s", lang);
10129
10130 if (lang != NULL) {
10131 setenv("LANG", lang, true);
10132 std::setlocale(LC_ALL, lang);
10133 }
10134 /* }}} */
10135
10136 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10137
10138 /* Parse Arguments {{{ */
10139 bool substrate(false);
10140
10141 if (argc != 0) {
10142 char **args(argv);
10143 int arge(1);
10144
10145 for (int argi(1); argi != argc; ++argi)
10146 if (strcmp(argv[argi], "--") == 0) {
10147 arge = argi;
10148 argv[argi] = argv[0];
10149 argv += argi;
10150 argc -= argi;
10151 break;
10152 }
10153
10154 for (int argi(1); argi != arge; ++argi)
10155 if (strcmp(args[argi], "--substrate") == 0)
10156 substrate = true;
10157 else
10158 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10159 }
10160 /* }}} */
10161
10162 App_ = [[NSBundle mainBundle] bundlePath];
10163 Advanced_ = YES;
10164
10165 setuid(0);
10166 setgid(0);
10167
10168 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10169 alloc_ = alloc->method_imp;
10170 alloc->method_imp = (IMP) &Alloc_;*/
10171
10172 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10173 dealloc_ = dealloc->method_imp;
10174 dealloc->method_imp = (IMP) &Dealloc_;*/
10175
10176 /* System Information {{{ */
10177 size_t size;
10178
10179 int maxproc;
10180 size = sizeof(maxproc);
10181 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10182 perror("sysctlbyname(\"kern.maxproc\", ?)");
10183 else if (maxproc < 64) {
10184 maxproc = 64;
10185 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10186 perror("sysctlbyname(\"kern.maxproc\", #)");
10187 }
10188
10189 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10190 char *osversion = new char[size];
10191 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10192 perror("sysctlbyname(\"kern.osversion\", ?)");
10193 else
10194 System_ = [NSString stringWithUTF8String:osversion];
10195
10196 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10197 char *machine = new char[size];
10198 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10199 perror("sysctlbyname(\"hw.machine\", ?)");
10200 else
10201 Machine_ = machine;
10202
10203 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10204 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10205 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10206 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10207 CFRelease(serial);
10208 }
10209
10210 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10211 NSData *data((NSData *) ecid);
10212 size_t length([data length]);
10213 uint8_t bytes[length];
10214 [data getBytes:bytes];
10215 char string[length * 2 + 1];
10216 for (size_t i(0); i != length; ++i)
10217 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10218 ChipID_ = [NSString stringWithUTF8String:string];
10219 CFRelease(ecid);
10220 }
10221
10222 IOObjectRelease(service);
10223 }
10224 }
10225
10226 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10227
10228 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10229 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10230 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10231
10232 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10233 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10234 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10235
10236 if (mcc != NULL && mnc != NULL)
10237 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10238
10239 if (mnc != NULL)
10240 CFRelease(mnc);
10241 if (mcc != NULL)
10242 CFRelease(mcc);
10243
10244 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10245 Build_ = [system objectForKey:@"ProductBuildVersion"];
10246 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10247 Product_ = [info objectForKey:@"SafariProductVersion"];
10248 Safari_ = [info objectForKey:@"CFBundleVersion"];
10249 }
10250 /* }}} */
10251 /* Load Database {{{ */
10252 _trace();
10253 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10254 _trace();
10255 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10256
10257 if (Metadata_ == NULL)
10258 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10259 else {
10260 Settings_ = [Metadata_ objectForKey:@"Settings"];
10261
10262 Packages_ = [Metadata_ objectForKey:@"Packages"];
10263 Sections_ = [Metadata_ objectForKey:@"Sections"];
10264 Sources_ = [Metadata_ objectForKey:@"Sources"];
10265
10266 Token_ = [Metadata_ objectForKey:@"Token"];
10267 }
10268
10269 if (Settings_ != nil)
10270 Role_ = [Settings_ objectForKey:@"Role"];
10271
10272 if (Sections_ == nil) {
10273 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10274 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10275 }
10276
10277 if (Sources_ == nil) {
10278 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10279 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10280 }
10281 /* }}} */
10282
10283 _trace();
10284 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10285 _trace();
10286
10287 if (Packages_ != nil) {
10288 bool fail(false);
10289 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10290 _trace();
10291
10292 if (!fail) {
10293 [Metadata_ removeObjectForKey:@"Packages"];
10294 Packages_ = nil;
10295 Changed_ = true;
10296 }
10297 }
10298
10299 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10300
10301 #define MobileSubstrate_(name) \
10302 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10303 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10304 if (handle == NULL) \
10305 NSLog(@"%s", dlerror()); \
10306 }
10307
10308 MobileSubstrate_(Activator)
10309 MobileSubstrate_(libstatusbar)
10310 MobileSubstrate_(SimulatedKeyEvents)
10311 MobileSubstrate_(WinterBoard)
10312
10313 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10314 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10315
10316 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10317
10318 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10319 unlink("/tmp/.cydia.fw");
10320 goto firmware;
10321 } else if (access("/User", F_OK) != 0 || version < 4) {
10322 firmware:
10323 _trace();
10324 system("/usr/libexec/cydia/firmware.sh");
10325 _trace();
10326 }
10327
10328 _assert([[NSFileManager defaultManager]
10329 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10330 withIntermediateDirectories:YES
10331 attributes:nil
10332 error:NULL
10333 ]);
10334
10335 if (access("/tmp/cydia.chk", F_OK) == 0) {
10336 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10337 _assert(errno == ENOENT);
10338 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10339 _assert(errno == ENOENT);
10340 }
10341
10342 /* APT Initialization {{{ */
10343 _assert(pkgInitConfig(*_config));
10344 _assert(pkgInitSystem(*_config, _system));
10345
10346 if (lang != NULL)
10347 _config->Set("APT::Acquire::Translation", lang);
10348
10349 // XXX: this timeout might be important :(
10350 //_config->Set("Acquire::http::Timeout", 15);
10351
10352 _config->Set("Acquire::http::MaxParallel", 3);
10353 /* }}} */
10354 /* Color Choices {{{ */
10355 space_ = CGColorSpaceCreateDeviceRGB();
10356
10357 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10358 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10359 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10360 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10361 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10362 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10363 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10364 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10365 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10366
10367 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10368 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10369 /* }}}*/
10370 /* UIKit Configuration {{{ */
10371 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10372 if ($GSFontSetUseLegacyFontMetrics != NULL)
10373 $GSFontSetUseLegacyFontMetrics(YES);
10374
10375 // XXX: I have a feeling this was important
10376 //UIKeyboardDisableAutomaticAppearance();
10377 /* }}} */
10378
10379 Colon_ = UCLocalize("COLON_DELIMITED");
10380 Elision_ = UCLocalize("ELISION");
10381 Error_ = UCLocalize("ERROR");
10382 Warning_ = UCLocalize("WARNING");
10383
10384 _trace();
10385 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10386
10387 CGColorSpaceRelease(space_);
10388 CFRelease(Locale_);
10389
10390 return value;
10391 }