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