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