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