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