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