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