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