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