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