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