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