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