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