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