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