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