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