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