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