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