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