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