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