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