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