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