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