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