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