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