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