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