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