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