-
Notifications
You must be signed in to change notification settings - Fork 35
/
MobileCydia.mm
9517 lines (7565 loc) · 282 KB
/
MobileCydia.mm
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Cydia - iPhone UIKit Front-End for Debian APT
* Copyright (C) 2008-2015 Jay Freeman (saurik)
*/
/* GNU General Public License, Version 3 {{{ */
/*
* Cydia is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Cydia is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cydia. If not, see <http://www.gnu.org/licenses/>.
**/
/* }}} */
// XXX: wtf/FastMalloc.h... wtf?
#define USE_SYSTEM_MALLOC 1
/* #include Directives {{{ */
#include "CyteKit/UCPlatform.h"
#include "CyteKit/Localize.h"
#include <unicode/ustring.h>
#include <unicode/utrans.h>
#include <objc/objc.h>
#include <objc/runtime.h>
#include <CoreGraphics/CoreGraphics.h>
#include <Foundation/Foundation.h>
#if 0
#define DEPLOYMENT_TARGET_MACOSX 1
#define CF_BUILDING_CF 1
#include <CoreFoundation/CFInternal.h>
#endif
#include <CoreFoundation/CFUniChar.h>
#include <SystemConfiguration/SystemConfiguration.h>
#include <UIKit/UIKit.h>
#include "iPhonePrivate.h"
#include <QuartzCore/CALayer.h>
#include <WebCore/WebCoreThread.h>
#include <algorithm>
#include <fstream>
#include <iomanip>
#include <set>
#include <sstream>
#include <string>
#include "fdstream.hpp"
#undef ABS
#include "apt.h"
#include <apt-pkg/acquire.h>
#include <apt-pkg/acquire-item.h>
#include <apt-pkg/algorithms.h>
#include <apt-pkg/cachefile.h>
#include <apt-pkg/clean.h>
#include <apt-pkg/configuration.h>
#include <apt-pkg/debindexfile.h>
#include <apt-pkg/debmetaindex.h>
#include <apt-pkg/error.h>
#include <apt-pkg/init.h>
#include <apt-pkg/mmap.h>
#include <apt-pkg/pkgrecords.h>
#include <apt-pkg/sha1.h>
#include <apt-pkg/sourcelist.h>
#include <apt-pkg/sptr.h>
#include <apt-pkg/strutl.h>
#include <apt-pkg/tagfile.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/param.h>
#include <sys/mount.h>
#include <sys/reboot.h>
#include <dirent.h>
#include <fcntl.h>
#include <notify.h>
#include <dlfcn.h>
extern "C" {
#include <mach-o/nlist.h>
}
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <Cytore.hpp>
#include "Sources.h"
#include "Substrate.hpp"
#include "Menes/Menes.h"
#include "CyteKit/CyteKit.h"
#include "CyteKit/RegEx.hpp"
#include "Cydia/MIMEAddress.h"
#include "Cydia/LoadingViewController.h"
#include "Cydia/ProgressEvent.h"
/* }}} */
/* Profiler {{{ */
struct timeval _ltv;
bool _itv;
#define _timestamp ({ \
struct timeval tv; \
gettimeofday(&tv, NULL); \
tv.tv_sec * 1000000 + tv.tv_usec; \
})
typedef std::vector<class ProfileTime *> TimeList;
TimeList times_;
class ProfileTime {
private:
const char *name_;
uint64_t total_;
uint64_t count_;
public:
ProfileTime(const char *name) :
name_(name),
total_(0)
{
times_.push_back(this);
}
void AddTime(uint64_t time) {
total_ += time;
++count_;
}
void Print() {
if (total_ != 0)
std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
total_ = 0;
count_ = 0;
}
};
class ProfileTimer {
private:
ProfileTime &time_;
uint64_t start_;
public:
ProfileTimer(ProfileTime &time) :
time_(time),
start_(_timestamp)
{
}
~ProfileTimer() {
time_.AddTime(_timestamp - start_);
}
};
void PrintTimes() {
for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
(*i)->Print();
std::cerr << "========" << std::endl;
}
#define _profile(name) { \
static ProfileTime name(#name); \
ProfileTimer _ ## name(name);
#define _end }
/* }}} */
extern NSString *Cydia_;
#define lprintf(args...) fprintf(stderr, args)
#define ForRelease 1
#define TraceLogging (1 && !ForRelease)
#define HistogramInsertionSort (0 && !ForRelease)
#define ProfileTimes (0 && !ForRelease)
#define ForSaurik (0 && !ForRelease)
#define LogBrowser (0 && !ForRelease)
#define TrackResize (0 && !ForRelease)
#define ManualRefresh (1 && !ForRelease)
#define ShowInternals (0 && !ForRelease)
#define AlwaysReload (0 && !ForRelease)
#if !TraceLogging
#undef _trace
#define _trace(args...)
#endif
#if !ProfileTimes
#undef _profile
#define _profile(name) {
#undef _end
#define _end }
#define PrintTimes() do {} while (false)
#endif
// Hash Functions/Structures {{{
extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
union SplitHash {
uint32_t u32;
uint16_t u16[2];
};
// }}}
static NSString *Colon_;
NSString *Elision_;
static NSString *Error_;
static NSString *Warning_;
static NSString *Cache_;
#define Cache(file) \
[NSString stringWithFormat:@"%@/%s", Cache_, file]
static void (*$SBSSetInterceptsMenuButtonForever)(bool);
static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
static CFStringRef (*$MGCopyAnswer)(CFStringRef);
static NSString *UniqueIdentifier(UIDevice *device = nil) {
if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
return [device ?: [UIDevice currentDevice] uniqueIdentifier];
else
return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
}
static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
static _finline NSString *CydiaURL(NSString *path) {
char page[26];
page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
page[25] = '\0';
return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
}
static NSString *ShellEscape(NSString *value) {
return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
}
static _finline void UpdateExternalStatus(uint64_t newStatus) {
int notify_token;
if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
notify_set_state(notify_token, newStatus);
notify_cancel(notify_token);
}
notify_post("com.saurik.Cydia.status");
}
/* NSForcedOrderingSearch doesn't work on the iPhone */
static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
/* Insertion Sort {{{ */
template <typename Type_>
size_t CFBSearch_(const Type_ &element, const void *list, size_t count, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
const char *ptr = (const char *)list;
while (0 < count) {
size_t half = count / 2;
const char *probe = ptr + sizeof(Type_) * half;
CFComparisonResult cr = comparator(element, * (const Type_ *) probe, context);
if (0 == cr) return (probe - (const char *)list) / sizeof(Type_);
ptr = (cr < 0) ? ptr : probe + sizeof(Type_);
count = (cr < 0) ? half : (half + (count & 1) - 1);
}
return (ptr - (const char *)list) / sizeof(Type_);
}
template <typename Type_>
void CYArrayInsertionSortValues(Type_ *values, size_t length, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
if (length == 0)
return;
#if HistogramInsertionSort > 0
uint32_t total(0), *offsets(new uint32_t[length]);
#endif
for (size_t index(1); index != length; ++index) {
Type_ value(values[index]);
#if 0
size_t correct(CFBSearch_(value, values, index, comparator, context));
#else
size_t correct(index);
while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
#if HistogramInsertionSort > 1
NSLog(@"%@ < %@", value, values[correct - 1]);
#endif
if (--correct == 0)
break;
if (index - correct >= 8) {
correct = CFBSearch_(value, values, correct, comparator, context);
break;
}
}
#endif
if (correct != index) {
size_t offset(index - correct);
#if HistogramInsertionSort
total += offset;
++offsets[offset];
if (offset > 10)
NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
#endif
memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
values[correct] = value;
}
}
#if HistogramInsertionSort > 0
for (size_t index(0); index != range.length; ++index)
if (offsets[index] != 0)
NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
delete [] offsets;
#endif
}
/* }}} */
/* Cydia NSString Additions {{{ */
@interface NSString (Cydia)
- (NSComparisonResult) compareByPath:(NSString *)other;
- (NSString *) stringByAddingPercentEscapesIncludingReserved;
@end
@implementation NSString (Cydia)
- (NSComparisonResult) compareByPath:(NSString *)other {
NSString *prefix = [self commonPrefixWithString:other options:0];
size_t length = [prefix length];
NSRange lrange = NSMakeRange(length, [self length] - length);
NSRange rrange = NSMakeRange(length, [other length] - length);
lrange = [self rangeOfString:@"/" options:0 range:lrange];
rrange = [other rangeOfString:@"/" options:0 range:rrange];
NSComparisonResult value;
if (lrange.location == NSNotFound && rrange.location == NSNotFound)
value = NSOrderedSame;
else if (lrange.location == NSNotFound)
value = NSOrderedAscending;
else if (rrange.location == NSNotFound)
value = NSOrderedDescending;
else
value = NSOrderedSame;
NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
[self substringWithRange:NSMakeRange(length, lrange.location - length)];
NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
[other substringWithRange:NSMakeRange(length, rrange.location - length)];
NSComparisonResult result = [lpath compare:rpath];
return result == NSOrderedSame ? value : result;
}
- (NSString *) stringByAddingPercentEscapesIncludingReserved {
return [(id)CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(CFStringRef) self,
NULL,
CFSTR(";/?:@&=+$,"),
kCFStringEncodingUTF8
) autorelease];
}
@end
/* }}} */
/* C++ NSString Wrapper Cache {{{ */
static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
return size == 0 ? NULL :
CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
}
static _finline CFStringRef CYStringCreate(const std::string &data) {
return CYStringCreate(data.data(), data.size());
}
static _finline CFStringRef CYStringCreate(const char *data) {
return CYStringCreate(data, strlen(data));
}
class CYString {
private:
char *data_;
size_t size_;
CFStringRef cache_;
_finline void clear_() {
if (cache_ != NULL) {
CFRelease(cache_);
cache_ = NULL;
}
}
public:
_finline bool empty() const {
return size_ == 0;
}
_finline size_t size() const {
return size_;
}
_finline char *data() const {
return data_;
}
_finline void clear() {
size_ = 0;
clear_();
}
_finline CYString() :
data_(0),
size_(0),
cache_(NULL)
{
}
_finline ~CYString() {
clear_();
}
void operator =(const CYString &rhs) {
data_ = rhs.data_;
size_ = rhs.size_;
if (rhs.cache_ == nil)
cache_ = NULL;
else
cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
}
void copy(CYPool *pool) {
char *temp(pool->malloc<char>(size_ + 1));
memcpy(temp, data_, size_);
temp[size_] = '\0';
data_ = temp;
}
void set(CYPool *pool, const char *data, size_t size) {
if (size == 0)
clear();
else {
clear_();
data_ = const_cast<char *>(data);
size_ = size;
if (pool != NULL)
copy(pool);
}
}
_finline void set(CYPool *pool, const char *data) {
set(pool, data, data == NULL ? 0 : strlen(data));
}
_finline void set(CYPool *pool, const std::string &rhs) {
set(pool, rhs.data(), rhs.size());
}
bool operator ==(const CYString &rhs) const {
return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
}
_finline operator CFStringRef() {
if (cache_ == NULL)
cache_ = CYStringCreate(data_, size_);
return cache_;
}
_finline operator id() {
return (NSString *) static_cast<CFStringRef>(*this);
}
_finline operator const char *() {
return reinterpret_cast<const char *>(data_);
}
};
/* }}} */
/* C++ NSString Algorithm Adapters {{{ */
extern "C" {
CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
}
struct NSStringMapHash :
std::unary_function<NSString *, size_t>
{
_finline size_t operator ()(NSString *value) const {
return CFStringHashNSString((CFStringRef) value);
}
};
struct NSStringMapLess :
std::binary_function<NSString *, NSString *, bool>
{
_finline bool operator ()(NSString *lhs, NSString *rhs) const {
return [lhs compare:rhs] == NSOrderedAscending;
}
};
struct NSStringMapEqual :
std::binary_function<NSString *, NSString *, bool>
{
_finline bool operator ()(NSString *lhs, NSString *rhs) const {
return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
//CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
//[lhs isEqualToString:rhs];
}
};
/* }}} */
/* CoreGraphics Primitives {{{ */
class CYColor {
private:
CGColorRef color_;
static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
CGFloat color[] = {red, green, blue, alpha};
return CGColorCreate(space, color);
}
public:
CYColor() :
color_(NULL)
{
}
CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
color_(Create_(space, red, green, blue, alpha))
{
Set(space, red, green, blue, alpha);
}
void Clear() {
if (color_ != NULL)
CGColorRelease(color_);
}
~CYColor() {
Clear();
}
void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
Clear();
color_ = Create_(space, red, green, blue, alpha);
}
operator CGColorRef() {
return color_;
}
};
/* }}} */
/* Random Global Variables {{{ */
static int PulseInterval_ = 500000;
static const NSString *UI_;
static int Finish_;
static bool RestartSubstrate_;
static NSArray *Finishes_;
#define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
#define NotifyConfig_ "/etc/notify.conf"
static bool Queuing_;
static CYColor Blue_;
static CYColor Blueish_;
static CYColor Black_;
static CYColor Folder_;
static CYColor Off_;
static CYColor White_;
static CYColor Gray_;
static CYColor Green_;
static CYColor Purple_;
static CYColor Purplish_;
static UIColor *InstallingColor_;
static UIColor *RemovingColor_;
static NSString *App_;
static BOOL Advanced_;
static BOOL Ignored_;
static _H<UIFont> Font12_;
static _H<UIFont> Font12Bold_;
static _H<UIFont> Font14_;
static _H<UIFont> Font18_;
static _H<UIFont> Font18Bold_;
static _H<UIFont> Font22Bold_;
static _H<NSString> UniqueID_;
static _H<NSLocale> CollationLocale_;
static _H<NSArray> CollationThumbs_;
static std::vector<NSInteger> CollationOffset_;
static _H<NSArray> CollationTitles_;
static _H<NSArray> CollationStarts_;
static UTransliterator *CollationTransl_;
//static Function<NSString *, NSString *> CollationModify_;
typedef std::basic_string<UChar> ustring;
static ustring CollationString_;
#define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
#define UC ustring &str(*reinterpret_cast<ustring *>(rep))
static struct UReplaceableCallbacks CollationUCalls_ = {
.length = [](const UReplaceable *rep) -> int32_t { CUC;
return str.size();
},
.charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
//fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
if (offset >= str.size())
return 0xffff;
return str[offset];
},
.char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
//fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
if (offset >= str.size())
return 0xffff;
UChar32 c;
U16_GET(str.data(), 0, offset, str.size(), c);
return c;
},
.replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
//fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
str.replace(start, limit - start, text, length);
},
.extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
//fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
str.copy(dst, limit - start, start);
},
.copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
//fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
str.replace(dest, 0, str, start, limit - start);
},
};
static CFLocaleRef Locale_;
static NSArray *Languages_;
static CGColorSpaceRef space_;
#define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
#define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
static NSDictionary *SectionMap_;
static _H<NSDate> Backgrounded_;
static _transient NSMutableDictionary *Values_;
static _transient NSMutableDictionary *Sections_;
_H<NSMutableDictionary> Sources_;
static _transient NSNumber *Version_;
static time_t now_;
static _H<NSMutableDictionary> SessionData_;
static _H<NSMutableSet> BridgedHosts_;
static _H<NSMutableSet> InsecureHosts_;
static NSString *kCydiaProgressEventTypeError = @"Error";
static NSString *kCydiaProgressEventTypeInformation = @"Information";
static NSString *kCydiaProgressEventTypeStatus = @"Status";
static NSString *kCydiaProgressEventTypeWarning = @"Warning";
/* }}} */
/* Display Helpers {{{ */
static _finline const char *StripVersion_(const char *version) {
const char *colon(strchr(version, ':'));
return colon == NULL ? version : colon + 1;
}
NSString *LocalizeSection(NSString *section) {
static RegEx title_r("(.*?) \\((.*)\\)");
if (title_r(section)) {
NSString *parent(title_r[1]);
NSString *child(title_r[2]);
return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
LocalizeSection(parent),
LocalizeSection(child)
];
}
return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
}
NSString *Simplify(NSString *title) {
const char *data = [title UTF8String];
size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
static RegEx square_r("\\[(.*)\\]");
if (square_r(data, size))
return Simplify(square_r[1]);
static RegEx paren_r("\\((.*)\\)");
if (paren_r(data, size))
return Simplify(paren_r[1]);
static RegEx title_r("(.*?) \\((.*)\\)");
if (title_r(data, size))
return Simplify(title_r[1]);
return title;
}
/* }}} */
bool isSectionVisible(NSString *section) {
NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
return hidden == nil || ![hidden boolValue];
}
static NSString *VerifySource(NSString *href) {
static RegEx href_r("(http(s?)://|file:///)[^# ]*");
if (!href_r(href)) {
[[[[UIAlertView alloc]
initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
message:UCLocalize("INVALID_URL_EX")
delegate:nil
cancelButtonTitle:UCLocalize("OK")
otherButtonTitles:nil
] autorelease] show];
return nil;
}
if (![href hasSuffix:@"/"])
href = [href stringByAppendingString:@"/"];
return href;
}
@class Cydia;
/* Delegate Prototypes {{{ */
@class Package;
@class Source;
@class CydiaProgressEvent;
@protocol DatabaseDelegate
- (void) repairWithSelector:(SEL)selector;
- (void) setConfigurationData:(NSString *)data;
- (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
@end
@class CYPackageController;
@protocol SourceDelegate
- (void) setFetch:(NSNumber *)fetch;
@end
@protocol FetchDelegate
- (bool) isSourceCancelled;
- (void) startSourceFetch:(NSString *)uri;
- (void) stopSourceFetch:(NSString *)uri;
@end
@protocol CydiaDelegate
- (void) returnToCydia;
- (void) saveState;
- (void) retainNetworkActivityIndicator;
- (void) releaseNetworkActivityIndicator;
- (void) clearPackage:(Package *)package;
- (void) installPackage:(Package *)package;
- (void) installPackages:(NSArray *)packages;
- (void) removePackage:(Package *)package;
- (void) beginUpdate;
- (BOOL) updating;
- (bool) requestUpdate;
- (void) distUpgrade;
- (void) loadData;
- (void) updateData;
- (void) _saveConfig;
- (void) syncData;
- (void) addSource:(NSDictionary *)source;
- (BOOL) addTrivialSource:(NSString *)href;
- (UIProgressHUD *) addProgressHUD;
- (void) removeProgressHUD:(UIProgressHUD *)hud;
- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
- (void) reloadDataWithInvocation:(NSInvocation *)invocation;
@end
/* }}} */
/* CancelStatus {{{ */
class CancelStatus :
public pkgAcquireStatus
{
private:
bool cancelled_;
public:
CancelStatus() :
cancelled_(false)
{
}
virtual bool MediaChange(std::string media, std::string drive) {
return false;
}
virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
Done(desc);
}
virtual bool Pulse_(pkgAcquire *Owner) = 0;
virtual bool Pulse(pkgAcquire *Owner) {
if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
return true;
else {
cancelled_ = true;
return false;
}
}
_finline bool WasCancelled() const {
return cancelled_;
}
};
/* }}} */
/* DelegateStatus {{{ */
class CydiaStatus :
public CancelStatus
{
private:
_transient NSObject<ProgressDelegate> *delegate_;
public:
CydiaStatus() :
delegate_(nil)
{
}
void setDelegate(NSObject<ProgressDelegate> *delegate) {
delegate_ = delegate;
}
virtual void Fetch(pkgAcquire::ItemDesc &desc) {
NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
[delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
}
virtual void Done(pkgAcquire::ItemDesc &desc) {
NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
[delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
}
virtual void Fail(pkgAcquire::ItemDesc &desc) {
if (
desc.Owner->Status == pkgAcquire::Item::StatIdle ||
desc.Owner->Status == pkgAcquire::Item::StatDone
)
return;
std::string &error(desc.Owner->ErrorText);
if (error.empty())
return;
CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
[delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
}
virtual bool Pulse_(pkgAcquire *Owner) {
double percent(
double(CurrentBytes + CurrentItems) /
double(TotalBytes + TotalItems)
);
[delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:percent], @"Percent",
[NSNumber numberWithDouble:CurrentBytes], @"Current",
[NSNumber numberWithDouble:TotalBytes], @"Total",
[NSNumber numberWithDouble:CurrentCPS], @"Speed",
nil] waitUntilDone:YES];
return ![delegate_ isProgressCancelled];
}
virtual void Start() {
pkgAcquireStatus::Start();
[delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
}
virtual void Stop() {
pkgAcquireStatus::Stop();
[delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
[delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
}
};
/* }}} */
/* Database Interface {{{ */
typedef std::map< unsigned long, _H<Source> > SourceMap;
@interface Database : NSObject {
NSZone *zone_;
CYPool pool_;
unsigned era_;
_H<NSDate> delock_;
pkgCacheFile cache_;
pkgDepCache::Policy *policy_;
pkgRecords *records_;
pkgProblemResolver *resolver_;
pkgAcquire *fetcher_;
FileFd *lock_;
SPtr<pkgPackageManager> manager_;
pkgSourceList *list_;
SourceMap sourceMap_;
_H<NSMutableArray> sourceList_;
_H<NSArray> packages_;
_transient NSObject<DatabaseDelegate> *delegate_;
_transient NSObject<ProgressDelegate> *progress_;
CydiaStatus status_;
int cydiafd_;
int statusfd_;
FILE *input_;
std::map<const char *, _H<NSString> > sections_;
}
+ (Database *) sharedInstance;
- (unsigned) era;
- (bool) hasPackages;
- (void) _readCydia:(NSNumber *)fd;
- (void) _readStatus:(NSNumber *)fd;
- (void) _readOutput:(NSNumber *)fd;
- (FILE *) input;
- (Package *) packageWithName:(NSString *)name;
- (pkgCacheFile &) cache;
- (pkgDepCache::Policy *) policy;
- (pkgRecords *) records;
- (pkgProblemResolver *) resolver;
- (pkgAcquire &) fetcher;
- (pkgSourceList &) list;
- (NSArray *) packages;
- (NSArray *) sources;
- (Source *) sourceWithKey:(NSString *)key;
- (void) reloadDataWithInvocation:(NSInvocation *)invocation;
- (void) configure;
- (bool) prepare;
- (void) perform;
- (bool) upgrade;
- (void) update;
- (void) updateWithStatus:(CancelStatus &)status;
- (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
- (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;