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