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