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