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