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