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