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