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