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