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