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