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