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