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