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