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