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