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