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