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