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