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