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