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