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