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