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