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