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