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