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