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