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