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