]> git.saurik.com Git - cydia.git/blame - MobileCydia.mm
The new version of Cydia needs newer translations.
[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_;
5d79f7bf
JF
6235 _H<NSMutableArray> buttons_;
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
f79a4512 6249/* XXX: this is not safe at all... localization of /fail/ */
5a09ae08 6250- (void) _clickButtonWithName:(NSString *)name {
43f3d7f6 6251 if ([name isEqualToString:UCLocalize("CLEAR")])
dc63e78f 6252 [delegate_ clearPackage:package_];
43f3d7f6 6253 else if ([name isEqualToString:UCLocalize("INSTALL")])
5a09ae08 6254 [delegate_ installPackage:package_];
43f3d7f6 6255 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5a09ae08 6256 [delegate_ installPackage:package_];
43f3d7f6 6257 else if ([name isEqualToString:UCLocalize("REMOVE")])
5a09ae08 6258 [delegate_ removePackage:package_];
43f3d7f6 6259 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5a09ae08
JF
6260 [delegate_ installPackage:package_];
6261 else _assert(false);
6262}
6263
674dce72 6264- (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
1cedb821 6265 NSString *context([sheet context]);
5a09ae08 6266
1cedb821 6267 if ([context isEqualToString:@"modify"]) {
674dce72
GP
6268 if (button != [sheet cancelButtonIndex]) {
6269 NSString *buttonName = [buttons_ objectAtIndex:button];
6270 [self _clickButtonWithName:buttonName];
6271 }
bc11cf5b 6272
674dce72 6273 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
674dce72 6274 }
b4d89997 6275}
2367a917 6276
3e9c9e85 6277- (bool) _allowJavaScriptPanel {
3bd1c2a2 6278 return commercial_;
3e9c9e85
JF
6279}
6280
9487f027 6281#if !AlwaysReload
9daa7f25 6282- (void) _customButtonClicked {
670a0494
JF
6283 int count([buttons_ count]);
6284 if (count == 0)
6285 return;
2367a917 6286
5a09ae08
JF
6287 if (count == 1)
6288 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6289 else {
674dce72 6290 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5a09ae08 6291 [buttons addObjectsFromArray:buttons_];
36bb2ca2 6292
674dce72 6293 UIActionSheet *sheet = [[[UIActionSheet alloc]
9ea8d159 6294 initWithTitle:nil
36bb2ca2 6295 delegate:self
674dce72
GP
6296 cancelButtonTitle:nil
6297 destructiveButtonTitle:nil
6298 otherButtonTitles:nil
6299 ] autorelease];
6300
6301 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6302 if (!IsWildcat_) {
6303 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6304 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6305 }
6306 [sheet setContext:@"modify"];
bc11cf5b 6307
b5e7eebb 6308 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
36bb2ca2 6309 }
b4d89997 6310}
12b59862 6311
2e6c1426 6312- (void) reloadButtonClicked {
07d0e88e
JF
6313 if (commercial_ && function_ == nil && [package_ uninstalled])
6314 return;
6315 [self customButtonClicked];
2fad210a
GP
6316}
6317
6318- (void) applyLoadingTitle {
6319 // Don't show "Loading" as the title. Ever.
2e6c1426 6320}
a5938ea5
DH
6321
6322- (UIBarButtonItem *) rightButton {
2634b249 6323 return button_;
a5938ea5 6324}
9487f027 6325#endif
2367a917 6326
77259cab
JF
6327- (void) setPageColor:(UIColor *)color {
6328 return [super setPageColor:nil];
6329}
6330
f050e4d9 6331- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
b5e7eebb 6332 if ((self = [super init]) != nil) {
36bb2ca2 6333 database_ = database;
5d79f7bf 6334 buttons_ = [NSMutableArray arrayWithCapacity:4];
5612913e 6335 name_ = name == nil ? @"" : [NSString stringWithString:name];
f050e4d9 6336 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
36bb2ca2 6337 } return self;
dc5812ec
JF
6338}
6339
57e8b225 6340- (void) reloadData {
9dac415b
JF
6341 [super reloadData];
6342
57e8b225 6343 package_ = [database_ packageWithName:name_];
36bb2ca2 6344
5a09ae08
JF
6345 [buttons_ removeAllObjects];
6346
57e8b225 6347 if (package_ != nil) {
5d79f7bf 6348 [(Package *) package_ parse];
68d927e2 6349
57e8b225 6350 commercial_ = [package_ isCommercial];
36bb2ca2 6351
dc63e78f 6352 if ([package_ mode] != nil)
43f3d7f6 6353 [buttons_ addObject:UCLocalize("CLEAR")];
5a09ae08 6354 if ([package_ source] == nil);
31f3cfff 6355 else if ([package_ upgradableAndEssential:NO])
43f3d7f6 6356 [buttons_ addObject:UCLocalize("UPGRADE")];
6a155117 6357 else if ([package_ uninstalled])
43f3d7f6 6358 [buttons_ addObject:UCLocalize("INSTALL")];
5a09ae08 6359 else
43f3d7f6 6360 [buttons_ addObject:UCLocalize("REINSTALL")];
6a155117 6361 if (![package_ uninstalled])
43f3d7f6 6362 [buttons_ addObject:UCLocalize("REMOVE")];
2634b249 6363 }
f79a4512 6364
2634b249
JF
6365 NSString *title;
6366 switch ([buttons_ count]) {
6367 case 0: title = nil; break;
6368 case 1: title = [buttons_ objectAtIndex:0]; break;
6369 default: title = UCLocalize("MODIFY"); break;
36bb2ca2 6370 }
2634b249 6371
5d79f7bf 6372 button_ = [[[UIBarButtonItem alloc]
2634b249
JF
6373 initWithTitle:title
6374 style:UIBarButtonItemStylePlain
6375 target:self
6376 action:@selector(customButtonClicked)
5d79f7bf 6377 ] autorelease];
b5e7eebb 6378}
f79a4512 6379
3bd1c2a2
JF
6380- (bool) isLoading {
6381 return commercial_ ? [super isLoading] : false;
9fe5e5f8
JF
6382}
6383
b4d89997
JF
6384@end
6385/* }}} */
5829aea2 6386
f50860ee 6387/* Package List Controller {{{ */
cd79e8cf 6388@interface PackageListController : CyteViewController <
c21004b9
JF
6389 UITableViewDataSource,
6390 UITableViewDelegate
6391> {
36bb2ca2 6392 _transient Database *database_;
0175295c 6393 unsigned era_;
56bf1e78 6394 _H<NSArray> packages_;
e5491e28 6395 _H<NSArray> sections_;
bf7c998c 6396 _H<UITableView, 2> list_;
aeeb755b
JF
6397
6398 _H<NSArray> thumbs_;
6399 std::vector<NSInteger> offset_;
6400
7b33d201 6401 _H<NSString> title_;
56bf1e78 6402 unsigned reloading_;
dc5812ec
JF
6403}
6404
f50860ee 6405- (id) initWithDatabase:(Database *)database title:(NSString *)title;
b4d89997 6406- (void) setDelegate:(id)delegate;
a0be02eb 6407- (void) resetCursor;
59f3d290 6408- (void) clearData;
b4d89997 6409
e5491e28
JF
6410- (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6411
b4d89997
JF
6412@end
6413
f50860ee 6414@implementation PackageListController
b4d89997 6415
f050e4d9
JF
6416- (NSURL *) referrerURL {
6417 return [self navigationURL];
6418}
6419
59f3d290
JF
6420- (bool) isSummarized {
6421 return false;
6422}
6423
9c5737d5
JF
6424- (bool) showsSections {
6425 return true;
6426}
6427
f50860ee
GP
6428- (void) deselectWithAnimation:(BOOL)animated {
6429 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6430}
6431
bfb45dcb
GP
6432- (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6433 CGRect base = [[self view] bounds];
6434 base.size.height -= bounds.size.height;
6435 base.origin = [list_ frame].origin;
6436
6437 [UIView beginAnimations:nil context:NULL];
6438 [UIView setAnimationBeginsFromCurrentState:YES];
6439 [UIView setAnimationCurve:curve];
6440 [UIView setAnimationDuration:duration];
6441 [list_ setFrame:base];
6442 [UIView commitAnimations];
6443}
6444
6445- (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6446 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6447}
6448
6449- (void) resizeForKeyboardBounds:(CGRect)bounds {
6450 [self resizeForKeyboardBounds:bounds duration:0];
6451}
6452
655c7ded
JF
6453- (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6454 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6455 *curve = UIViewAnimationCurveEaseInOut;
6456 else
6457 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6458
6459 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6460 *duration = 0.3;
6461 else
6462 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6463}
6464
bfb45dcb
GP
6465- (void) keyboardWillShow:(NSNotification *)notification {
6466 CGRect bounds;
6467 CGPoint center;
bfb45dcb
GP
6468 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6469 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:&center];
655c7ded
JF
6470
6471 NSTimeInterval duration;
6472 UIViewAnimationCurve curve;
6473 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
bfb45dcb 6474
8323c1b9 6475 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
38991110 6476 UIViewController *base = self;
19f2d77f
JF
6477 while ([base parentOrPresentingViewController] != nil)
6478 base = [base parentOrPresentingViewController];
38991110 6479 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
bfb45dcb
GP
6480 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6481
2e35f65f 6482 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
0b7516cf 6483 intersection.size.height += CYStatusBarHeight();
2e35f65f 6484
bfb45dcb
GP
6485 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6486}
6487
6488- (void) keyboardWillHide:(NSNotification *)notification {
6489 NSTimeInterval duration;
6490 UIViewAnimationCurve curve;
655c7ded 6491 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
bfb45dcb
GP
6492
6493 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6494}
6495
6496- (void) viewWillAppear:(BOOL)animated {
6497 [super viewWillAppear:animated];
6498
6499 [self resizeForKeyboardBounds:CGRectZero];
6500 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6501 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6502}
6503
6504- (void) viewWillDisappear:(BOOL)animated {
6505 [super viewWillDisappear:animated];
6506
6507 [self resizeForKeyboardBounds:CGRectZero];
6508 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6509 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6510}
6511
f50860ee
GP
6512- (void) viewDidAppear:(BOOL)animated {
6513 [super viewDidAppear:animated];
6514 [self deselectWithAnimation:animated];
6515}
6516
6517- (void) didSelectPackage:(Package *)package {
f050e4d9 6518 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
f50860ee
GP
6519 [view setDelegate:delegate_];
6520 [[self navigationController] pushViewController:view animated:YES];
6521}
6522
327624b6
JF
6523- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6524 NSInteger count([sections_ count]);
6525 return count == 0 ? 1 : count;
b4d89997 6526}
2367a917 6527
327624b6 6528- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
a891c345 6529 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
327624b6 6530 return nil;
b4d89997
JF
6531 return [[sections_ objectAtIndex:section] name];
6532}
dc5812ec 6533
327624b6
JF
6534- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6535 if ([sections_ count] == 0)
6536 return 0;
6537 return [[sections_ objectAtIndex:section] count];
b4d89997 6538}
dc5812ec 6539
327624b6 6540- (Package *) packageAtIndexPath:(NSIndexPath *)path {
0175295c
JF
6541@synchronized (database_) {
6542 if ([database_ era] != era_)
6543 return nil;
6544
327624b6
JF
6545 Section *section([sections_ objectAtIndex:[path section]]);
6546 NSInteger row([path row]);
6547 Package *package([packages_ objectAtIndex:([section row] + row)]);
0175295c
JF
6548 return [[package retain] autorelease];
6549} }
dc5812ec 6550
327624b6 6551- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
c21004b9 6552 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
327624b6
JF
6553 if (cell == nil)
6554 cell = [[[PackageCell alloc] init] autorelease];
60bef540
JF
6555
6556 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6557 [cell setPackage:package asSummary:[self isSummarized]];
327624b6 6558 return cell;
b4d89997 6559}
dc5812ec 6560
f50860ee 6561- (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
327624b6 6562 Package *package([self packageAtIndexPath:path]);
59c6ae22 6563 package = [database_ packageWithName:[package id]];
f50860ee 6564 [self didSelectPackage:package];
327624b6
JF
6565}
6566
6567- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
aeeb755b 6568 return thumbs_;
327624b6
JF
6569}
6570
a891c345 6571- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
aeeb755b 6572 return offset_[index];
dc5812ec
JF
6573}
6574
59f3d290
JF
6575- (void) updateHeight {
6576 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6577}
6578
f50860ee
GP
6579- (id) initWithDatabase:(Database *)database title:(NSString *)title {
6580 if ((self = [super init]) != nil) {
36bb2ca2 6581 database_ = database;
f50860ee
GP
6582 title_ = [title copy];
6583 [[self navigationItem] setTitle:title_];
61cc4dbc
JF
6584 } return self;
6585}
dc5812ec 6586
61cc4dbc 6587- (void) loadView {
b62b3788
JF
6588 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6589 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6590 [self setView:view];
6591
6592 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
61cc4dbc 6593 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
b62b3788 6594 [view addSubview:list_];
1527b095 6595
61cc4dbc
JF
6596 // XXX: is 20 the most optimal number here?
6597 [list_ setSectionIndexMinimumDisplayRowCount:20];
59f3d290 6598
61cc4dbc
JF
6599 [(UITableView *) list_ setDataSource:self];
6600 [list_ setDelegate:self];
6601
6602 [self updateHeight];
6603}
6604
6605- (void) releaseSubviews {
6606 list_ = nil;
7be3eb32 6607
4f9acb7c
JF
6608 packages_ = nil;
6609 sections_ = nil;
aeeb755b
JF
6610
6611 thumbs_ = nil;
6612 offset_.clear();
4f9acb7c 6613
7be3eb32 6614 [super releaseSubviews];
dc5812ec
JF
6615}
6616
6617- (void) setDelegate:(id)delegate {
2367a917 6618 delegate_ = delegate;
b4d89997
JF
6619}
6620
3025d5b4
JF
6621- (bool) shouldYield {
6622 return false;
6623}
b4d89997 6624
56bf1e78
JF
6625- (bool) shouldBlock {
6626 return false;
6627}
6628
9c5737d5 6629- (NSMutableArray *) _reloadPackages {
695fdd5c 6630@synchronized (database_) {
c28bc6f1
JF
6631 era_ = [database_ era];
6632 NSArray *packages([database_ packages]);
6633
9c5737d5 6634 return [NSMutableArray arrayWithArray:packages];
695fdd5c 6635} }
3025d5b4
JF
6636
6637- (void) _reloadData {
56bf1e78
JF
6638 if (reloading_ != 0) {
6639 reloading_ = 2;
6640 return;
6641 }
6642
e5491e28 6643 NSMutableArray *packages;
ae60e2c1 6644
0c8f53c0 6645 reload:
3025d5b4 6646 if ([self shouldYield]) {
bec28dda
JF
6647 do {
6648 UIProgressHUD *hud;
56bf1e78 6649
bec28dda
JF
6650 if (![self shouldBlock])
6651 hud = nil;
6652 else {
6653 hud = [delegate_ addProgressHUD];
6654 [hud setText:UCLocalize("LOADING")];
6655 }
56bf1e78 6656
56bf1e78 6657 reloading_ = 1;
ae60e2c1 6658 packages = [self yieldToSelector:@selector(_reloadPackages)];
bec28dda
JF
6659
6660 if (hud != nil)
6661 [delegate_ removeProgressHUD:hud];
56bf1e78 6662 } while (reloading_ == 2);
3025d5b4 6663 } else {
ae60e2c1 6664 packages = [self _reloadPackages];
3025d5b4 6665 }
36bb2ca2 6666
0c8f53c0
JF
6667@synchronized (database_) {
6668 if (era_ != [database_ era])
6669 goto reload;
6670 reloading_ = 0;
6671
aeeb755b
JF
6672 thumbs_ = nil;
6673 offset_.clear();
6674
ae60e2c1 6675 packages_ = packages;
aeeb755b
JF
6676
6677 if ([self showsSections])
6678 sections_ = [self sectionsForPackages:packages];
6679 else {
6680 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6681 [section setCount:[packages_ count]];
6682 sections_ = [NSArray arrayWithObject:section];
6683 }
ae60e2c1 6684
e5491e28
JF
6685 [self updateHeight];
6686
6687 _profile(PackageTable$reloadData$List)
6688 [(UITableView *) list_ setDataSource:self];
6689 [list_ reloadData];
6690 _end
1a83afc6
JF
6691}
6692
6693 PrintTimes();
6694}
e5491e28
JF
6695
6696- (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
aeeb755b
JF
6697 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6698 size_t end([packages count]);
b4d89997 6699
aeeb755b
JF
6700 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6701 Section *section(prefix);
c4dcf2c2 6702
aeeb755b
JF
6703 thumbs_ = CollationThumbs_;
6704 offset_ = CollationOffset_;
b4d89997 6705
aeeb755b
JF
6706 size_t offset(0);
6707 size_t offsets([CollationStarts_ count]);
b4d89997 6708
aeeb755b
JF
6709 NSString *start([CollationStarts_ objectAtIndex:offset]);
6710 size_t length([start length]);
327624b6 6711
aeeb755b
JF
6712 for (size_t index(0); index != end; ++index) {
6713 if (start != nil) {
6714 Package *package([packages objectAtIndex:index]);
22fd24dd 6715 NSString *name(PackageName(package, @selector(cyname)));
a891c345 6716
aeeb755b 6717 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
22fd24dd 6718 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
aeeb755b
JF
6719 NSString *title([CollationTitles_ objectAtIndex:offset]);
6720 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6721 [sections addObject:section];
a891c345 6722
aeeb755b
JF
6723 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6724 if (start == nil)
6725 break;
6726 length = [start length];
808c6eb6 6727 }
59f3d290
JF
6728 }
6729
aeeb755b
JF
6730 [section addToCount];
6731 }
a891c345 6732
aeeb755b
JF
6733 for (; offset != offsets; ++offset) {
6734 NSString *title([CollationTitles_ objectAtIndex:offset]);
6735 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6736 [sections addObject:section];
6737 }
a891c345 6738
aeeb755b
JF
6739 if ([prefix count] != 0) {
6740 Section *suffix([sections lastObject]);
6741 [prefix setName:[suffix name]];
6742 [suffix setName:nil];
6743 [sections insertObject:prefix atIndex:(offsets - 1)];
a891c345 6744 }
b4d89997 6745
e5491e28
JF
6746 return sections;
6747}
b4d89997 6748
3025d5b4
JF
6749- (void) reloadData {
6750 [super reloadData];
6d246265
JF
6751
6752 if ([self shouldYield])
6753 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6754 else
6755 [self _reloadData];
3025d5b4
JF
6756}
6757
a0be02eb 6758- (void) resetCursor {
4c6a29cd 6759 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
a0be02eb
JF
6760}
6761
59f3d290
JF
6762- (void) clearData {
6763 [self updateHeight];
6764
6765 [list_ setDataSource:nil];
6766 [list_ reloadData];
6767
6768 [self resetCursor];
6769}
6770
a3328c28
JF
6771@end
6772/* }}} */
f50860ee 6773/* Filtered Package List Controller {{{ */
89bdef78
JF
6774typedef Function<bool, Package *> PackageFilter;
6775typedef Function<void, NSMutableArray *> PackageSorter;
f50860ee 6776@interface FilteredPackageListController : PackageListController {
89bdef78
JF
6777 PackageFilter filter_;
6778 PackageSorter sorter_;
a3328c28
JF
6779}
6780
89bdef78 6781- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
3025d5b4 6782
89bdef78
JF
6783- (void) setFilter:(PackageFilter)filter;
6784- (void) setSorter:(PackageSorter)sorter;
a3328c28
JF
6785
6786@end
6787
f50860ee 6788@implementation FilteredPackageListController
a3328c28 6789
89bdef78 6790- (void) setFilter:(PackageFilter)filter {
aa32d91b 6791@synchronized (self) {
01d93940 6792 filter_ = filter;
55066b9e
JF
6793} }
6794
89bdef78 6795- (void) setSorter:(PackageSorter)sorter {
55066b9e 6796@synchronized (self) {
89bdef78 6797 sorter_ = sorter;
d84597fe 6798} }
01d93940 6799
9c5737d5 6800- (NSMutableArray *) _reloadPackages {
aa32d91b 6801@synchronized (database_) {
c28bc6f1 6802 era_ = [database_ era];
c28bc6f1 6803
dd4e70dc
JF
6804 NSArray *packages([database_ packages]);
6805 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
aa32d91b 6806
89bdef78 6807 PackageFilter filter;
dd4e70dc 6808 PackageSorter sorter;
aa32d91b
JF
6809
6810 @synchronized (self) {
aa32d91b 6811 filter = filter_;
89bdef78 6812 sorter = sorter_;
aa32d91b
JF
6813 }
6814
6815 _profile(PackageTable$reloadData$Filter)
6816 for (Package *package in packages)
89bdef78 6817 if ([package valid] && filter(package))
aa32d91b 6818 [filtered addObject:package];
76933519 6819 _end
aa32d91b 6820
89bdef78
JF
6821 if (sorter)
6822 sorter(filtered);
aa32d91b 6823 return filtered;
dd4e70dc 6824} }
55066b9e 6825
89bdef78 6826- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
55066b9e
JF
6827 if ((self = [super initWithDatabase:database title:title]) != nil) {
6828 [self setFilter:filter];
a3328c28
JF
6829 } return self;
6830}
6831
dc5812ec 6832@end
b5e7eebb
GP
6833/* }}} */
6834
5829aea2 6835/* Home Controller {{{ */
a576488f 6836@interface HomeController : CydiaWebViewController {
02f21c73
JF
6837 CFRunLoopRef runloop_;
6838 SCNetworkReachabilityRef reachability_;
b4d89997 6839}
6840bff3 6840
7b0ce2da 6841@end
b4d89997 6842
5829aea2 6843@implementation HomeController
46aa9775 6844
02f21c73
JF
6845static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6846 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6847}
6848
3c62d654
JF
6849- (id) init {
6850 if ((self = [super init]) != nil) {
90351d93 6851 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
ed7bfd8c 6852 [self reloadData];
02f21c73
JF
6853
6854 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6855 if (reachability_ != NULL) {
6856 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6857 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6858
6859 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6860 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6861 runloop_ = runloop;
6862 }
3c62d654
JF
6863 } return self;
6864}
6865
02f21c73
JF
6866- (void) dealloc {
6867 if (reachability_ != NULL && runloop_ != NULL)
6868 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6869 [super dealloc];
6870}
6871
fe8e721f
GP
6872- (NSURL *) navigationURL {
6873 return [NSURL URLWithString:@"cydia://home"];
6874}
6875
5829aea2
GP
6876- (void) aboutButtonClicked {
6877 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
b4d89997 6878
5829aea2
GP
6879 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6880 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6881 [alert setCancelButtonIndex:0];
46aa9775 6882
5829aea2 6883 [alert setMessage:
6fa0bb60 6884 @"Copyright \u00a9 2008-2014\n"
7e865c1e
JF
6885 "SaurikIT, LLC\n"
6886 "\n"
5829aea2
GP
6887 "Jay Freeman (saurik)\n"
6888 "saurik@saurik.com\n"
6889 "http://www.saurik.com/"
6890 ];
46aa9775 6891
5829aea2 6892 [alert show];
a0376fc1
JF
6893}
6894
e6124cb6
JF
6895- (UIBarButtonItem *) leftButton {
6896 return [[[UIBarButtonItem alloc]
35f0a3b5
GP
6897 initWithTitle:UCLocalize("ABOUT")
6898 style:UIBarButtonItemStylePlain
6899 target:self
6900 action:@selector(aboutButtonClicked)
e6124cb6 6901 ] autorelease];
7b0ce2da
JF
6902}
6903
5829aea2
GP
6904@end
6905/* }}} */
7b0ce2da 6906
28e596e4 6907/* Cydia Navigation Controller Interface {{{ */
15f0d613 6908@interface UINavigationController (Cydia)
28e596e4
JF
6909
6910- (NSArray *) navigationURLCollection;
15f0d613 6911- (void) unloadData;
28e596e4
JF
6912
6913@end
6914/* }}} */
7b0ce2da 6915
5829aea2 6916/* Cydia Tab Bar Controller {{{ */
5fe2bcc6 6917@interface CydiaTabBarController : CyteTabBarController <
9f99f3da 6918 UITabBarControllerDelegate,
21ac0ce2 6919 FetchDelegate
5829aea2
GP
6920> {
6921 _transient Database *database_;
7b0ce2da 6922
e67ebdad
JF
6923 _H<UIActivityIndicatorView> indicator_;
6924
5829aea2
GP
6925 bool updating_;
6926 // XXX: ok, "updatedelegate_"?...
6927 _transient NSObject<CydiaDelegate> *updatedelegate_;
7b0ce2da
JF
6928}
6929
35f0a3b5 6930- (NSArray *) navigationURLCollection;
5829aea2 6931- (void) beginUpdate;
5829aea2 6932- (BOOL) updating;
1cedb821 6933
5829aea2 6934@end
2fc76a2d 6935
5fe2bcc6 6936@implementation CydiaTabBarController
9f99f3da 6937
35f0a3b5 6938- (NSArray *) navigationURLCollection {
fe8e721f
GP
6939 NSMutableArray *items([NSMutableArray array]);
6940
35f0a3b5 6941 // XXX: Should this deal with transient view controllers?
fe8e721f 6942 for (id navigation in [self viewControllers]) {
35f0a3b5 6943 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
fe8e721f
GP
6944 if (stack != nil)
6945 [items addObject:stack];
2fc76a2d 6946 }
c713af59 6947
fe8e721f
GP
6948 return items;
6949}
6950
b5e7eebb
GP
6951- (id) initWithDatabase:(Database *)database {
6952 if ((self = [super init]) != nil) {
7b0ce2da 6953 database_ = database;
9f99f3da 6954 [self setDelegate:self];
04fe1349 6955
e67ebdad
JF
6956 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6957 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7b0ce2da 6958
e67ebdad 6959 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7b0ce2da
JF
6960 } return self;
6961}
6962
5829aea2
GP
6963- (void) setUpdate:(NSDate *)date {
6964 [self beginUpdate];
6965}
1cedb821 6966
5829aea2 6967- (void) beginUpdate {
20d59843
JF
6968 if (updating_)
6969 return;
6970
e67ebdad
JF
6971 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6972 UITabBarItem *item([controller tabBarItem]);
6973
6974 [item setBadgeValue:@""];
6975 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6976
6977 [indicator_ startAnimating];
6978 [badge addSubview:indicator_];
7b0ce2da 6979
5829aea2
GP
6980 [updatedelegate_ retainNetworkActivityIndicator];
6981 updating_ = true;
7b0ce2da 6982
5829aea2
GP
6983 [NSThread
6984 detachNewThreadSelector:@selector(performUpdate)
6985 toTarget:self
6986 withObject:nil
6987 ];
7b0ce2da
JF
6988}
6989
d13edf44
JF
6990- (void) performUpdate {
6991 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6992
21ac0ce2 6993 SourceStatus status(self, database_);
5829aea2
GP
6994 [database_ updateWithStatus:status];
6995
6996 [self
6997 performSelectorOnMainThread:@selector(completeUpdate)
6998 withObject:nil
6999 waitUntilDone:NO
7000 ];
d13edf44
JF
7001
7002 [pool release];
f6e13561
GP
7003}
7004
5829aea2
GP
7005- (void) stopUpdateWithSelector:(SEL)selector {
7006 updating_ = false;
7007 [updatedelegate_ releaseNetworkActivityIndicator];
b5e7eebb 7008
e67ebdad
JF
7009 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7010 [[controller tabBarItem] setBadgeValue:nil];
7011
7012 [indicator_ removeFromSuperview];
7013 [indicator_ stopAnimating];
bc11cf5b 7014
5829aea2 7015 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
2bdd73bd
GP
7016}
7017
5829aea2
GP
7018- (void) completeUpdate {
7019 if (!updating_)
7020 return;
7021 [self stopUpdateWithSelector:@selector(reloadData)];
7b0ce2da
JF
7022}
7023
5829aea2 7024- (void) cancelUpdate {
383a58ac 7025 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7b0ce2da
JF
7026}
7027
5829aea2
GP
7028- (void) cancelPressed {
7029 [self cancelUpdate];
7030}
7b0ce2da 7031
5829aea2
GP
7032- (BOOL) updating {
7033 return updating_;
7b0ce2da
JF
7034}
7035
21ac0ce2 7036- (bool) isSourceCancelled {
5829aea2
GP
7037 return !updating_;
7038}
7b0ce2da 7039
21ac0ce2 7040- (void) startSourceFetch:(NSString *)uri {
7b0ce2da
JF
7041}
7042
21ac0ce2 7043- (void) stopSourceFetch:(NSString *)uri {
bcbac8f7
JF
7044}
7045
5829aea2
GP
7046- (void) setUpdateDelegate:(id)delegate {
7047 updatedelegate_ = delegate;
7b0ce2da
JF
7048}
7049
7b0ce2da 7050@end
98228790 7051/* }}} */
f6e13561 7052
28e596e4 7053/* Cydia Navigation Controller Implementation {{{ */
15f0d613 7054@implementation UINavigationController (Cydia)
bc11cf5b 7055
35f0a3b5 7056- (NSArray *) navigationURLCollection {
fe8e721f
GP
7057 NSMutableArray *stack([NSMutableArray array]);
7058
cd79e8cf 7059 for (CyteViewController *controller in [self viewControllers]) {
fe8e721f
GP
7060 NSString *url = [[controller navigationURL] absoluteString];
7061 if (url != nil)
7062 [stack addObject:url];
7063 }
7064
7065 return stack;
7066}
7067
15f0d613
JF
7068- (void) reloadData {
7069 [super reloadData];
7070
21263088
JF
7071 UIViewController *visible([self visibleViewController]);
7072 if (visible != nil)
15f0d613 7073 [visible reloadData];
21263088
JF
7074
7075 // on the iPad, this view controller is ALSO visible. :(
7076 if (IsWildcat_)
7077 if (UIViewController *top = [self topViewController])
7078 if (top != visible)
7079 [top reloadData];
15f0d613 7080}
6c0ba3d9 7081
15f0d613 7082- (void) unloadData {
cd79e8cf 7083 for (CyteViewController *page in [self viewControllers])
15f0d613 7084 [page unloadData];
6c0ba3d9 7085
15f0d613 7086 [super unloadData];
dc63e78f
JF
7087}
7088
5829aea2
GP
7089@end
7090/* }}} */
7b0ce2da 7091
5829aea2
GP
7092/* Cydia:// Protocol {{{ */
7093@interface CydiaURLProtocol : NSURLProtocol {
9fe5e5f8
JF
7094}
7095
7b0ce2da
JF
7096@end
7097
5829aea2
GP
7098@implementation CydiaURLProtocol
7099
7100+ (BOOL) canInitWithRequest:(NSURLRequest *)request {
7101 NSURL *url([request URL]);
7102 if (url == nil)
7103 return NO;
b0a2900d 7104
5829aea2 7105 NSString *scheme([[url scheme] lowercaseString]);
b0a2900d
JF
7106 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7107 return YES;
7108 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7109 return YES;
7110
7111 return NO;
aa5e5990
JF
7112}
7113
5829aea2
GP
7114+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7115 return request;
7116}
aa5e5990 7117
5829aea2
GP
7118- (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7119 id<NSURLProtocolClient> client([self client]);
7120 if (icon == nil)
7121 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7122 else {
7123 NSData *data(UIImagePNGRepresentation(icon));
01d93940 7124
5829aea2
GP
7125 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7126 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7127 [client URLProtocol:self didLoadData:data];
7128 [client URLProtocolDidFinishLoading:self];
7129 }
3931b718
JF
7130}
7131
5829aea2
GP
7132- (void) startLoading {
7133 id<NSURLProtocolClient> client([self client]);
7134 NSURLRequest *request([self request]);
bc11cf5b 7135
5829aea2
GP
7136 NSURL *url([request URL]);
7137 NSString *href([url absoluteString]);
b0a2900d
JF
7138 NSString *scheme([[url scheme] lowercaseString]);
7139
7140 NSString *path;
7141
7142 if ([scheme isEqualToString:@"cydia"])
7143 path = [href substringFromIndex:8];
7144 else if ([scheme isEqualToString:@"about"])
7145 path = [href substringFromIndex:12];
7146 else _assert(false);
bc11cf5b 7147
5829aea2 7148 NSRange slash([path rangeOfString:@"/"]);
bc11cf5b 7149
5829aea2
GP
7150 NSString *command;
7151 if (slash.location == NSNotFound) {
7152 command = path;
7153 path = nil;
7154 } else {
7155 command = [path substringToIndex:slash.location];
7156 path = [path substringFromIndex:(slash.location + 1)];
7157 }
39cda3a8 7158
5829aea2 7159 Database *database([Database sharedInstance]);
bc11cf5b 7160
5829aea2
GP
7161 if ([command isEqualToString:@"package-icon"]) {
7162 if (path == nil)
7163 goto fail;
7164 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7165 Package *package([database packageWithName:path]);
7166 if (package == nil)
7167 goto fail;
eff20a8d 7168 [package parse];
5829aea2
GP
7169 UIImage *icon([package icon]);
7170 [self _returnPNGWithImage:icon forRequest:request];
5829aea2
GP
7171 } else if ([command isEqualToString:@"uikit-image"]) {
7172 if (path == nil)
7173 goto fail;
7174 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7175 UIImage *icon(_UIImageWithName(path));
7176 [self _returnPNGWithImage:icon forRequest:request];
7177 } else if ([command isEqualToString:@"section-icon"]) {
7178 if (path == nil)
7179 goto fail;
7180 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
611efc17 7181 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
5829aea2
GP
7182 if (icon == nil)
7183 icon = [UIImage applicationImageNamed:@"unknown.png"];
7184 [self _returnPNGWithImage:icon forRequest:request];
7185 } else fail: {
7186 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7187 }
39cda3a8
GP
7188}
7189
5829aea2
GP
7190- (void) stopLoading {
7191}
807ae6d7 7192
5829aea2
GP
7193@end
7194/* }}} */
807ae6d7 7195
5829aea2 7196/* Section Controller {{{ */
f50860ee 7197@interface SectionController : FilteredPackageListController {
55066b9e 7198 _H<NSString> key_;
123b380c 7199 _H<NSString> section_;
5829aea2 7200}
807ae6d7 7201
55066b9e 7202- (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
807ae6d7 7203
5829aea2 7204@end
bc11cf5b 7205
5829aea2 7206@implementation SectionController
bc11cf5b 7207
f050e4d9 7208- (NSURL *) referrerURL {
55066b9e
JF
7209 NSString *name(section_);
7210 name = name ?: @"*";
7211 NSString *key(key_);
7212 key = key ?: @"*";
7213 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
f050e4d9
JF
7214}
7215
fe8e721f 7216- (NSURL *) navigationURL {
55066b9e
JF
7217 NSString *name(section_);
7218 name = name ?: @"*";
7219 NSString *key(key_);
7220 key = key ?: @"*";
7221 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
fe8e721f
GP
7222}
7223
55066b9e 7224- (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
5829aea2 7225 NSString *title;
55066b9e 7226 if (section == nil)
5829aea2 7227 title = UCLocalize("ALL_PACKAGES");
55066b9e
JF
7228 else if (![section isEqual:@""])
7229 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
3707eb56 7230 else
5829aea2 7231 title = UCLocalize("NO_SECTION");
fe8e721f 7232
89bdef78 7233 if ((self = [super initWithDatabase:database title:title]) != nil) {
55066b9e
JF
7234 key_ = [source key];
7235 section_ = section;
5829aea2 7236 } return self;
b5e7eebb
GP
7237}
7238
55066b9e 7239- (void) reloadData {
89bdef78
JF
7240 Source *source([database_ sourceWithKey:key_]);
7241 _H<NSString> name(section_);
7242
7243 [self setFilter:[=](Package *package) {
7244 NSString *section([package section]);
7245
7246 return (
7247 name == nil ||
7248 section == nil && [name length] == 0 ||
7249 [name isEqualToString:section]
7250 ) && (
7251 source == nil ||
7252 [package source] == source
7253 ) && [package visible];
7254 }];
7255
55066b9e
JF
7256 [super reloadData];
7257}
7258
b5e7eebb
GP
7259@end
7260/* }}} */
5829aea2 7261/* Sections Controller {{{ */
cd79e8cf 7262@interface SectionsController : CyteViewController <
5829aea2
GP
7263 UITableViewDataSource,
7264 UITableViewDelegate
7585ce66 7265> {
3931b718 7266 _transient Database *database_;
55066b9e 7267 _H<NSString> key_;
7b33d201
JF
7268 _H<NSMutableArray> sections_;
7269 _H<NSMutableArray> filtered_;
bf7c998c 7270 _H<UITableView, 2> list_;
b5e7eebb
GP
7271}
7272
55066b9e 7273- (id) initWithDatabase:(Database *)database source:(Source *)source;
5829aea2 7274- (void) editButtonClicked;
7585ce66 7275
bc11cf5b 7276@end
b5e7eebb 7277
5829aea2 7278@implementation SectionsController
b5e7eebb 7279
fe8e721f 7280- (NSURL *) navigationURL {
55066b9e
JF
7281 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7282}
7283
7284- (Source *) source {
7285 if (key_ == nil)
7286 return nil;
7287 return [database_ sourceWithKey:key_];
fe8e721f
GP
7288}
7289
a784d0a4 7290- (void) updateNavigationItem {
8e5b801a 7291 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
a784d0a4
GP
7292 if ([sections_ count] == 0) {
7293 [[self navigationItem] setRightBarButtonItem:nil];
7294 } else {
7295 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
8e5b801a 7296 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
a784d0a4
GP
7297 target:self
7298 action:@selector(editButtonClicked)
7299 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7300 }
7301}
7302
8e5b801a
GP
7303- (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7304 [super setEditing:editing animated:animated];
35f0a3b5 7305
8e5b801a 7306 if (editing)
5829aea2
GP
7307 [list_ reloadData];
7308 else
7309 [delegate_ updateData];
7585ce66 7310
a784d0a4 7311 [self updateNavigationItem];
b5e7eebb
GP
7312}
7313
5829aea2
GP
7314- (void) viewDidAppear:(BOOL)animated {
7315 [super viewDidAppear:animated];
7316 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7585ce66
JF
7317}
7318
5829aea2
GP
7319- (void) viewWillDisappear:(BOOL)animated {
7320 [super viewWillDisappear:animated];
31eedaae 7321 [self setEditing:NO];
7585ce66
JF
7322}
7323
5829aea2 7324- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
b3551da8 7325 Section *section = nil;
8e5b801a 7326 int index = [indexPath row];
b3551da8 7327 if (![self isEditing]) {
666b48ad 7328 index -= 1;
b3551da8
GP
7329 if (index >= 0)
7330 section = [filtered_ objectAtIndex:index];
7331 } else {
7332 section = [sections_ objectAtIndex:index];
7333 }
5829aea2
GP
7334 return section;
7335}
7585ce66 7336
5829aea2 7337- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8e5b801a
GP
7338 if ([self isEditing])
7339 return [sections_ count];
7340 else
7341 return [filtered_ count] + 1;
7585ce66
JF
7342}
7343
5829aea2
GP
7344/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7345 return 45.0f;
7346}*/
7585ce66 7347
5829aea2
GP
7348- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7349 static NSString *reuseIdentifier = @"SectionCell";
7585ce66 7350
35f0a3b5 7351 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5829aea2
GP
7352 if (cell == nil)
7353 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7585ce66 7354
8e5b801a 7355 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
54043703 7356
5829aea2 7357 return cell;
54043703
JF
7358}
7359
5829aea2 7360- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8e5b801a 7361 if ([self isEditing])
54043703 7362 return;
7585ce66 7363
5829aea2 7364 Section *section = [self sectionAtIndexPath:indexPath];
7585ce66 7365
5829aea2
GP
7366 SectionController *controller = [[[SectionController alloc]
7367 initWithDatabase:database_
55066b9e 7368 source:[self source]
5829aea2
GP
7369 section:[section name]
7370 ] autorelease];
7371 [controller setDelegate:delegate_];
7585ce66 7372
5829aea2 7373 [[self navigationController] pushViewController:controller animated:YES];
7585ce66
JF
7374}
7375
fe8e721f 7376- (void) loadView {
e8cbebe4 7377 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
fe8e721f 7378 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
86a333c6 7379 [list_ setRowHeight:46];
7b33d201 7380 [(UITableView *) list_ setDataSource:self];
fe8e721f 7381 [list_ setDelegate:self];
e8cbebe4 7382 [self setView:list_];
fe8e721f
GP
7383}
7384
7385- (void) viewDidLoad {
7d887d0b
JF
7386 [super viewDidLoad];
7387
fe8e721f
GP
7388 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7389}
7390
7391- (void) releaseSubviews {
fe8e721f 7392 list_ = nil;
7be3eb32 7393
4f9acb7c
JF
7394 sections_ = nil;
7395 filtered_ = nil;
7396
7be3eb32 7397 [super releaseSubviews];
fe8e721f
GP
7398}
7399
55066b9e 7400- (id) initWithDatabase:(Database *)database source:(Source *)source {
5829aea2
GP
7401 if ((self = [super init]) != nil) {
7402 database_ = database;
55066b9e 7403 key_ = [source key];
5829aea2 7404 } return self;
7585ce66
JF
7405}
7406
5829aea2 7407- (void) reloadData {
fe8e721f
GP
7408 [super reloadData];
7409
5829aea2 7410 NSArray *packages = [database_ packages];
7585ce66 7411
4f9acb7c
JF
7412 sections_ = [NSMutableArray arrayWithCapacity:16];
7413 filtered_ = [NSMutableArray arrayWithCapacity:16];
7585ce66 7414
5829aea2 7415 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7585ce66 7416
55066b9e
JF
7417 Source *source([self source]);
7418
5829aea2
GP
7419 _trace();
7420 for (Package *package in packages) {
55066b9e
JF
7421 if (source != nil && [package source] != source)
7422 continue;
7423
5829aea2
GP
7424 NSString *name([package section]);
7425 NSString *key(name == nil ? @"" : name);
7585ce66 7426
5829aea2 7427 Section *section;
7585ce66 7428
5829aea2
GP
7429 _profile(SectionsView$reloadData$Section)
7430 section = [sections objectForKey:key];
7431 if (section == nil) {
7432 _profile(SectionsView$reloadData$Section$Allocate)
729bc910 7433 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
5829aea2
GP
7434 [sections setObject:section forKey:key];
7435 _end
7436 }
7437 _end
7585ce66 7438
5829aea2 7439 [section addToCount];
7585ce66 7440
5829aea2
GP
7441 _profile(SectionsView$reloadData$Filter)
7442 if (![package valid] || ![package visible])
7443 continue;
7444 _end
7585ce66 7445
5829aea2
GP
7446 [section addToRow];
7447 }
7448 _trace();
7585ce66 7449
5829aea2 7450 [sections_ addObjectsFromArray:[sections allValues]];
7585ce66 7451
5829aea2 7452 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7585ce66 7453
7b33d201 7454 for (Section *section in (id) sections_) {
5829aea2
GP
7455 size_t count([section row]);
7456 if (count == 0)
7457 continue;
7585ce66 7458
5829aea2
GP
7459 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7460 [section setCount:count];
7461 [filtered_ addObject:section];
7462 }
7585ce66 7463
a784d0a4 7464 [self updateNavigationItem];
5829aea2
GP
7465 [list_ reloadData];
7466 _trace();
7467}
7585ce66 7468
6840bff3 7469- (void) editButtonClicked {
8e5b801a 7470 [self setEditing:![self isEditing] animated:YES];
5829aea2 7471}
7585ce66 7472
5829aea2
GP
7473@end
7474/* }}} */
7585ce66 7475
5829aea2 7476/* Changes Controller {{{ */
e5491e28 7477@interface ChangesController : FilteredPackageListController {
5829aea2 7478 unsigned upgrades_;
5829aea2 7479}
7585ce66 7480
ea3bb538 7481- (id) initWithDatabase:(Database *)database;
7585ce66 7482
5829aea2 7483@end
7585ce66 7484
5829aea2 7485@implementation ChangesController
7585ce66 7486
e5491e28
JF
7487- (NSURL *) referrerURL {
7488 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
b5e7eebb
GP
7489}
7490
e5491e28
JF
7491- (NSURL *) navigationURL {
7492 return [NSURL URLWithString:@"cydia://changes"];
5829aea2 7493}
b5e7eebb 7494
5829aea2
GP
7495- (Package *) packageAtIndexPath:(NSIndexPath *)path {
7496@synchronized (database_) {
7497 if ([database_ era] != era_)
7498 return nil;
b5e7eebb 7499
5829aea2
GP
7500 NSUInteger sectionIndex([path section]);
7501 if (sectionIndex >= [sections_ count])
7502 return nil;
7503 Section *section([sections_ objectAtIndex:sectionIndex]);
7504 NSInteger row([path row]);
56bf1e78 7505 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
5829aea2 7506} }
b5e7eebb 7507
0e15b67c
JF
7508- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7509 NSString *context([alert context]);
7510
7511 if ([context isEqualToString:@"norefresh"])
7512 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7513}
7514
e67ebdad
JF
7515- (void) setLeftBarButtonItem {
7516 if ([delegate_ updating])
7517 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7518 initWithTitle:UCLocalize("CANCEL")
7519 style:UIBarButtonItemStyleDone
7520 target:self
7521 action:@selector(cancelButtonClicked)
7522 ] autorelease] animated:YES];
7523 else
7524 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7525 initWithTitle:UCLocalize("REFRESH")
7526 style:UIBarButtonItemStylePlain
7527 target:self
7528 action:@selector(refreshButtonClicked)
7529 ] autorelease] animated:YES];
7530}
7531
5829aea2 7532- (void) refreshButtonClicked {
e67ebdad
JF
7533 if ([delegate_ requestUpdate])
7534 [self setLeftBarButtonItem];
7535}
0e15b67c 7536
e67ebdad
JF
7537- (void) cancelButtonClicked {
7538 [delegate_ cancelUpdate];
b5e7eebb
GP
7539}
7540
5829aea2
GP
7541- (void) upgradeButtonClicked {
7542 [delegate_ distUpgrade];
cb6b3a7b 7543 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
b5e7eebb
GP
7544}
7545
e5491e28
JF
7546- (bool) shouldYield {
7547 return true;
fe8e721f
GP
7548}
7549
e5491e28
JF
7550- (bool) shouldBlock {
7551 return true;
fe8e721f
GP
7552}
7553
e5491e28
JF
7554- (void) useFilter {
7555@synchronized (self) {
7556 [self setFilter:[](Package *package) {
7557 return [package upgradableAndEssential:YES] || [package visible];
7558 }];
4f9acb7c 7559
e5491e28
JF
7560 [self setSorter:[](NSMutableArray *packages) {
7561 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7562 }];
7563} }
5829aea2 7564
ea3bb538 7565- (id) initWithDatabase:(Database *)database {
e5491e28
JF
7566 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7567 [self useFilter];
5829aea2 7568 } return self;
807ae6d7
JF
7569}
7570
946c4377
JF
7571- (void) viewDidLoad {
7572 [super viewDidLoad];
7573 [self setLeftBarButtonItem];
7574}
7575
7576- (void) viewWillAppear:(BOOL)animated {
7577 [super viewWillAppear:animated];
7578 [self setLeftBarButtonItem];
7579}
7580
e5491e28 7581- (void) reloadData {
e67ebdad 7582 [self setLeftBarButtonItem];
e5491e28
JF
7583 [super reloadData];
7584}
e67ebdad 7585
e5491e28
JF
7586- (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7587 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
bdca103d 7588
5829aea2
GP
7589 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7590 Section *ignored = nil;
7591 Section *section = nil;
7592 time_t last = 0;
807ae6d7 7593
5829aea2
GP
7594 upgrades_ = 0;
7595 bool unseens = false;
807ae6d7 7596
5829aea2 7597 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
807ae6d7 7598
e5491e28
JF
7599 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7600 Package *package = [packages objectAtIndex:offset];
807ae6d7 7601
5829aea2 7602 BOOL uae = [package upgradableAndEssential:YES];
807ae6d7 7603
5829aea2
GP
7604 if (!uae) {
7605 unseens = true;
7606 time_t seen([package seen]);
d90a4cd6 7607
5829aea2
GP
7608 if (section == nil || last != seen) {
7609 last = seen;
7610
7611 NSString *name;
7612 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7613 [name autorelease];
7614
7615 _profile(ChangesController$reloadData$Allocate)
7616 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7617 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
e5491e28 7618 [sections addObject:section];
5829aea2
GP
7619 _end
7620 }
7621
7622 [section addToCount];
7623 } else if ([package ignored]) {
7624 if (ignored == nil) {
7625 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7626 }
7627 [ignored addToCount];
7628 } else {
7629 ++upgrades_;
7630 [upgradable addToCount];
7631 }
7632 }
7633 _trace();
7634
7635 CFRelease(formatter);
7636
7637 if (unseens) {
e5491e28 7638 Section *last = [sections lastObject];
5829aea2 7639 size_t count = [last count];
e5491e28
JF
7640 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7641 [sections removeLastObject];
5829aea2
GP
7642 }
7643
7644 if ([ignored count] != 0)
e5491e28 7645 [sections insertObject:ignored atIndex:0];
5829aea2 7646 if (upgrades_ != 0)
e5491e28 7647 [sections insertObject:upgradable atIndex:0];
5829aea2
GP
7648
7649 [list_ reloadData];
7650
cb6b3a7b
JF
7651 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7652 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7653 style:UIBarButtonItemStylePlain
7654 target:self
7655 action:@selector(upgradeButtonClicked)
7656 ] autorelease]) animated:YES];
5829aea2 7657
e5491e28 7658 return sections;
a70cd4ba
JF
7659}
7660
5829aea2
GP
7661@end
7662/* }}} */
7663/* Search Controller {{{ */
f50860ee 7664@interface SearchController : FilteredPackageListController <
5829aea2
GP
7665 UISearchBarDelegate
7666> {
bf7c998c 7667 _H<UISearchBar, 1> search_;
fe8e721f 7668 BOOL searchloaded_;
89bdef78 7669 bool summary_;
5829aea2
GP
7670}
7671
43625891 7672- (id) initWithDatabase:(Database *)database query:(NSString *)query;
5829aea2 7673- (void) reloadData;
d90a4cd6
GP
7674
7675@end
7676
5829aea2 7677@implementation SearchController
d90a4cd6 7678
f050e4d9
JF
7679- (NSURL *) referrerURL {
7680 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7681}
7682
fe8e721f 7683- (NSURL *) navigationURL {
35f0a3b5
GP
7684 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7685 return [NSURL URLWithString:@"cydia://search"];
7686 else
b90c7892 7687 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
fe8e721f
GP
7688}
7689
096e25d8 7690- (NSArray *) termsForQuery:(NSString *)query {
945812b9
JF
7691 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7692 for (NSString *component in [query componentsSeparatedByString:@" "])
7693 if ([component length] != 0)
7694 [terms addObject:component];
7695
7696 return terms;
096e25d8
JF
7697}
7698
59f3d290 7699- (void) useSearch {
89bdef78
JF
7700 _H<NSArray> query([self termsForQuery:[search_ text]]);
7701 summary_ = false;
7702
7703@synchronized (self) {
7704 [self setFilter:[=](Package *package) {
7705 if (![package unfiltered])
7706 return false;
7707 if (![package matches:query])
7708 return false;
7709 return true;
7710 }];
7711
7712 [self setSorter:[](NSMutableArray *packages) {
7713 [packages radixSortUsingSelector:@selector(rank)];
7714 }];
7715}
7716
59f3d290
JF
7717 [self clearData];
7718 [self reloadData];
7719}
7720
89bdef78
JF
7721- (void) usePrefix:(NSString *)prefix {
7722 _H<NSString> query(prefix);
7723 summary_ = true;
7724
7725@synchronized (self) {
7726 [self setFilter:[=](Package *package) {
7727 if ([query length] == 0)
7728 return false;
7729 if (![package unfiltered])
7730 return false;
7731 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7732 return false;
7733 return true;
7734 }];
7735
7736 [self setSorter:nullptr];
7737}
7738
7739 [self reloadData];
7740}
7741
3025d5b4 7742- (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
59f3d290 7743 [self clearData];
89bdef78 7744 [self usePrefix:[search_ text]];
3025d5b4
JF
7745}
7746
7747- (void) searchBarButtonClicked:(UISearchBar *)searchBar {
5829aea2 7748 [search_ resignFirstResponder];
59f3d290 7749 [self useSearch];
5829aea2
GP
7750}
7751
3025d5b4
JF
7752- (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7753 [search_ setText:@""];
7754 [self searchBarButtonClicked:searchBar];
7755}
7756
7757- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7758 [self searchBarButtonClicked:searchBar];
7759}
7760
5829aea2 7761- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
89bdef78 7762 [self usePrefix:text];
5829aea2
GP
7763}
7764
3025d5b4 7765- (bool) shouldYield {
56bf1e78
JF
7766 return YES;
7767}
7768
7769- (bool) shouldBlock {
89bdef78 7770 return !summary_;
3025d5b4
JF
7771}
7772
59f3d290 7773- (bool) isSummarized {
89bdef78 7774 return summary_;
59f3d290
JF
7775}
7776
9c5737d5
JF
7777- (bool) showsSections {
7778 return false;
7779}
7780
43625891 7781- (id) initWithDatabase:(Database *)database query:(NSString *)query {
89bdef78 7782 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
900095fd 7783 search_ = [[[UISearchBar alloc] init] autorelease];
830efb5d 7784 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
900095fd 7785 [search_ setDelegate:self];
43625891 7786
830efb5d
JF
7787 UITextField *textField;
7788 if ([search_ respondsToSelector:@selector(searchField)])
7789 textField = [search_ searchField];
7790 else
7791 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7792
7793 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7794 [textField setEnablesReturnKeyAutomatically:NO];
7795 [[self navigationItem] setTitleView:textField];
7796
43625891
JF
7797 if (query != nil)
7798 [search_ setText:query];
89bdef78 7799 [self useSearch];
fe8e721f 7800 } return self;
5829aea2
GP
7801}
7802
6840bff3 7803- (void) viewDidAppear:(BOOL)animated {
5829aea2 7804 [super viewDidAppear:animated];
fe8e721f
GP
7805
7806 if (!searchloaded_) {
7807 searchloaded_ = YES;
7808 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
5829aea2 7809 [search_ layoutSubviews];
d90a4cd6 7810 }
058813ae
GP
7811
7812 if ([self isSummarized])
7813 [search_ becomeFirstResponder];
5829aea2 7814}
d90a4cd6 7815
d90a4cd6 7816- (void) reloadData {
f50860ee 7817 [self resetCursor];
9dac415b 7818 [super reloadData];
d90a4cd6
GP
7819}
7820
5829aea2
GP
7821- (void) didSelectPackage:(Package *)package {
7822 [search_ resignFirstResponder];
7823 [super didSelectPackage:package];
d90a4cd6
GP
7824}
7825
7826@end
7827/* }}} */
5829aea2 7828/* Package Settings Controller {{{ */
cd79e8cf 7829@interface PackageSettingsController : CyteViewController <
c21004b9
JF
7830 UITableViewDataSource,
7831 UITableViewDelegate
7832> {
807ae6d7 7833 _transient Database *database_;
7b33d201
JF
7834 _H<NSString> name_;
7835 _H<Package> package_;
bf7c998c 7836 _H<UITableView, 2> table_;
7b33d201
JF
7837 _H<UISwitch> subscribedSwitch_;
7838 _H<UISwitch> ignoredSwitch_;
7839 _H<UITableViewCell> subscribedCell_;
7840 _H<UITableViewCell> ignoredCell_;
807ae6d7
JF
7841}
7842
5829aea2 7843- (id) initWithDatabase:(Database *)database package:(NSString *)package;
c21004b9 7844
807ae6d7
JF
7845@end
7846
5829aea2 7847@implementation PackageSettingsController
807ae6d7 7848
fe8e721f 7849- (NSURL *) navigationURL {
8861e953 7850 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
fe8e721f
GP
7851}
7852
5829aea2
GP
7853- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7854 if (package_ == nil)
7855 return 0;
e954c30a 7856
2136717a
DH
7857 if ([package_ installed] == nil)
7858 return 1;
7859 else
7860 return 2;
e954c30a
GP
7861}
7862
5829aea2
GP
7863- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7864 if (package_ == nil)
7865 return 0;
7866
2136717a
DH
7867 // both sections contain just one item right now.
7868 return 1;
b5e7eebb
GP
7869}
7870
5829aea2 7871- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
2136717a 7872 return nil;
e954c30a
GP
7873}
7874
5829aea2 7875- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
2136717a
DH
7876 if (section == 0)
7877 return UCLocalize("SHOW_ALL_CHANGES_EX");
7878 else
7879 return UCLocalize("IGNORE_UPGRADES_EX");
807ae6d7
JF
7880}
7881
5829aea2
GP
7882- (void) onSubscribed:(id)control {
7883 bool value([control isOn]);
7884 if (package_ == nil)
7885 return;
7886 if ([package_ setSubscribed:value])
7887 [delegate_ updateData];
807ae6d7
JF
7888}
7889
e5e70358
JF
7890- (void) _updateIgnored {
7891 const char *package([name_ UTF8String]);
7892 bool on([ignoredSwitch_ isOn]);
7893
7894 pid_t pid(ExecFork());
7895 if (pid == 0) {
7896 FILE *dpkg(popen("dpkg --set-selections", "w"));
7897 fwrite(package, strlen(package), 1, dpkg);
7898
7899 if (on)
7900 fwrite(" hold\n", 6, 1, dpkg);
7901 else
7902 fwrite(" install\n", 9, 1, dpkg);
7903
7904 pclose(dpkg);
7905
7906 exit(0);
51c8106a 7907 } ReapZombie(pid);
e5e70358
JF
7908}
7909
5829aea2 7910- (void) onIgnored:(id)control {
e5e70358
JF
7911 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7912 [invocation setTarget:self];
7913 [invocation setSelector:@selector(_updateIgnored)];
7914
7915 [delegate_ reloadDataWithInvocation:invocation];
5829aea2 7916}
807ae6d7 7917
46aa9775 7918- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5829aea2
GP
7919 if (package_ == nil)
7920 return nil;
b5e7eebb 7921
2136717a 7922 switch ([indexPath section]) {
5829aea2
GP
7923 case 0: return subscribedCell_;
7924 case 1: return ignoredCell_;
36fbb2aa 7925
5829aea2
GP
7926 _nodefault
7927 }
807ae6d7 7928
5829aea2 7929 return nil;
807ae6d7
JF
7930}
7931
fe8e721f 7932- (void) loadView {
39470a3a
JF
7933 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7934 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7935 [self setView:view];
807ae6d7 7936
7b33d201 7937 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
fe8e721f 7938 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7b33d201 7939 [(UITableView *) table_ setDataSource:self];
fe8e721f 7940 [table_ setDelegate:self];
39470a3a 7941 [view addSubview:table_];
807ae6d7 7942
7b33d201 7943 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
fe8e721f
GP
7944 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7945 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
807ae6d7 7946
7b33d201 7947 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
fe8e721f
GP
7948 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7949 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
807ae6d7 7950
7b33d201 7951 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
fe8e721f
GP
7952 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7953 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7954 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
5829aea2 7955
7b33d201 7956 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
fe8e721f
GP
7957 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7958 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7959 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
fe8e721f 7960}
5829aea2 7961
fe8e721f 7962- (void) viewDidLoad {
7d887d0b
JF
7963 [super viewDidLoad];
7964
fe8e721f
GP
7965 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7966}
5829aea2 7967
fe8e721f 7968- (void) releaseSubviews {
fe8e721f 7969 ignoredCell_ = nil;
fe8e721f 7970 subscribedCell_ = nil;
fe8e721f 7971 table_ = nil;
fe8e721f 7972 ignoredSwitch_ = nil;
fe8e721f 7973 subscribedSwitch_ = nil;
7be3eb32
JF
7974
7975 [super releaseSubviews];
fe8e721f
GP
7976}
7977
7978- (id) initWithDatabase:(Database *)database package:(NSString *)package {
6840bff3 7979 if ((self = [super init]) != nil) {
fe8e721f 7980 database_ = database;
7b33d201 7981 name_ = package;
807ae6d7
JF
7982 } return self;
7983}
7984
7985- (void) reloadData {
fe8e721f
GP
7986 [super reloadData];
7987
5829aea2 7988 package_ = [database_ packageWithName:name_];
f3e2c0ac 7989
5829aea2 7990 if (package_ != nil) {
5829aea2
GP
7991 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7992 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
f3e2c0ac 7993 } // XXX: what now, G?
dc5812ec 7994
5829aea2
GP
7995 [table_ reloadData];
7996}
6d9712c4 7997
dc5812ec 7998@end
2367a917 7999/* }}} */
d90a4cd6 8000
5829aea2 8001/* Installed Controller {{{ */
f50860ee 8002@interface InstalledController : FilteredPackageListController {
821b1a0c 8003 bool sectioned_;
dc5812ec
JF
8004}
8005
5829aea2 8006- (id) initWithDatabase:(Database *)database;
5829aea2 8007- (void) queueStatusDidChange;
dc5812ec 8008
dc5812ec
JF
8009@end
8010
5829aea2 8011@implementation InstalledController
b4d89997 8012
f050e4d9
JF
8013- (NSURL *) referrerURL {
8014 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8015}
8016
fe8e721f
GP
8017- (NSURL *) navigationURL {
8018 return [NSURL URLWithString:@"cydia://installed"];
8019}
b5e7eebb 8020
b3906a21 8021- (void) useRecent {
821b1a0c
JF
8022 sectioned_ = false;
8023
8024@synchronized (self) {
8025 [self setFilter:[](Package *package) {
8026 return ![package uninstalled] && package->role_ < 7;
8027 }];
8028
8029 [self setSorter:[](NSMutableArray *packages) {
b3906a21 8030 [packages radixSortUsingSelector:@selector(recent)];
821b1a0c
JF
8031 }];
8032} }
8033
89bdef78 8034- (void) useFilter:(UISegmentedControl *)segmented {
821b1a0c
JF
8035 NSInteger selected([segmented selectedSegmentIndex]);
8036 if (selected == 2)
b3906a21 8037 return [self useRecent];
821b1a0c
JF
8038 bool simple(selected == 0);
8039 sectioned_ = true;
89bdef78
JF
8040
8041@synchronized (self) {
8042 [self setFilter:[=](Package *package) {
8043 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8044 }];
821b1a0c
JF
8045
8046 [self setSorter:nullptr];
89bdef78
JF
8047} }
8048
98ddcefd
JF
8049- (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8050 if (sectioned_)
8051 return [super sectionsForPackages:packages];
8052
8053 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8054
8055 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7108bdd2 8056 Section *section(nil);
98ddcefd
JF
8057 time_t last(0);
8058
8059 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8060 Package *package([packages objectAtIndex:offset]);
8061
b3906a21 8062 time_t upgraded([package upgraded]);
0cadb352
JF
8063 if (upgraded < 1168364520)
8064 upgraded = 0;
8065 else
8066 upgraded -= upgraded % (60 * 60 * 24);
98ddcefd 8067
b3906a21
JF
8068 if (section == nil || upgraded != last) {
8069 last = upgraded;
98ddcefd
JF
8070
8071 NSString *name;
0cadb352
JF
8072 if (upgraded == 0)
8073 continue; // XXX: name = UCLocalize("...");
8074 else {
8075 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8076 [name autorelease];
8077 }
98ddcefd
JF
8078
8079 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8080 [sections addObject:section];
8081 }
8082
8083 [section addToCount];
8084 }
8085
8086 CFRelease(formatter);
8087 return sections;
8088}
8089
5829aea2 8090- (id) initWithDatabase:(Database *)database {
89bdef78 8091 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
c8fbe1f4 8092 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
3544397d
JF
8093 [segmented setSelectedSegmentIndex:0];
8094 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8095 [[self navigationItem] setTitleView:segmented];
8096
8097 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
89bdef78 8098 [self useFilter:segmented];
3544397d 8099
5829aea2
GP
8100 [self queueStatusDidChange];
8101 } return self;
dc5812ec
JF
8102}
8103
5829aea2
GP
8104#if !AlwaysReload
8105- (void) queueButtonClicked {
8106 [delegate_ queue];
dc5812ec 8107}
5829aea2 8108#endif
dc5812ec 8109
5829aea2
GP
8110- (void) queueStatusDidChange {
8111#if !AlwaysReload
55066b9e 8112 if (Queuing_) {
7d3660da 8113 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
55066b9e
JF
8114 initWithTitle:UCLocalize("QUEUE")
8115 style:UIBarButtonItemStyleDone
8116 target:self
8117 action:@selector(queueButtonClicked)
8118 ] autorelease]];
8119 } else {
7d3660da 8120 [[self navigationItem] setRightBarButtonItem:nil];
5829aea2
GP
8121 }
8122#endif
dc5812ec
JF
8123}
8124
3544397d 8125- (void) modeChanged:(UISegmentedControl *)segmented {
89bdef78 8126 [self useFilter:segmented];
f50860ee 8127 [self reloadData];
9a7b04c5
JF
8128}
8129
5829aea2
GP
8130@end
8131/* }}} */
b5e7eebb 8132
5829aea2 8133/* Source Cell {{{ */
a9311516 8134@interface SourceCell : CyteTableViewCell <
21ac0ce2
JF
8135 CyteTableViewCellDelegate,
8136 SourceDelegate
5829aea2 8137> {
21ac0ce2 8138 _H<Source, 1> source_;
02735663 8139 _H<NSURL> url_;
7b33d201
JF
8140 _H<UIImage> icon_;
8141 _H<NSString> origin_;
8142 _H<NSString> label_;
21ac0ce2 8143 _H<UIActivityIndicatorView> indicator_;
5829aea2 8144}
dc5812ec 8145
5829aea2 8146- (void) setSource:(Source *)source;
21ac0ce2 8147- (void) setFetch:(NSNumber *)fetch;
6da1297d 8148
5829aea2 8149@end
dc5812ec 8150
5829aea2 8151@implementation SourceCell
36bb2ca2 8152
02735663
JF
8153- (void) _setImage:(NSArray *)data {
8154 if ([url_ isEqual:[data objectAtIndex:0]]) {
8155 icon_ = [data objectAtIndex:1];
8156 [content_ setNeedsDisplay];
8157 }
8252b666
JF
8158}
8159
7bd76e97 8160- (void) _setSource:(NSURL *) url {
8252b666
JF
8161 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8162
7bd76e97
JF
8163 if (NSData *data = [NSURLConnection
8164 sendSynchronousRequest:[NSURLRequest
8165 requestWithURL:url
de5f2673
JF
8166 cachePolicy:NSURLRequestUseProtocolCachePolicy
8167 timeoutInterval:10
7bd76e97
JF
8168 ]
8169
8170 returningResponse:NULL
8171 error:NULL
8172 ])
8173 if (UIImage *image = [UIImage imageWithData:data])
02735663 8174 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8252b666
JF
8175
8176 [pool release];
8177}
8178
5829aea2 8179- (void) setSource:(Source *)source {
21ac0ce2
JF
8180 source_ = source;
8181 [source_ setDelegate:self];
8182
8183 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8184
8252b666 8185 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5829aea2 8186
7b33d201 8187 origin_ = [source name];
7bd76e97 8188 label_ = [source rooturi];
5829aea2
GP
8189
8190 [content_ setNeedsDisplay];
8252b666 8191
02735663
JF
8192 url_ = [source iconURL];
8193 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
77801ff1
JF
8194}
8195
55066b9e 8196- (void) setAllSource {
21ac0ce2
JF
8197 source_ = nil;
8198 [indicator_ stopAnimating];
8199
55066b9e
JF
8200 icon_ = [UIImage applicationImageNamed:@"folder.png"];
8201 origin_ = UCLocalize("ALL_SOURCES");
8202 label_ = UCLocalize("ALL_SOURCES_EX");
8203 [content_ setNeedsDisplay];
8204}
8205
5829aea2
GP
8206- (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8207 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8208 UIView *content([self contentView]);
8209 CGRect bounds([content bounds]);
77801ff1 8210
b97fcfc6 8211 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5829aea2
GP
8212 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8213 [content_ setBackgroundColor:[UIColor whiteColor]];
8214 [content addSubview:content_];
dc5812ec 8215
5829aea2
GP
8216 [content_ setDelegate:self];
8217 [content_ setOpaque:YES];
53db9999 8218
21ac0ce2
JF
8219 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8220 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8221 [content addSubview:indicator_];
8222
53db9999 8223 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
5829aea2
GP
8224 } return self;
8225}
b4d89997 8226
21ac0ce2
JF
8227- (void) layoutSubviews {
8228 [super layoutSubviews];
8229
8230 UIView *content([self contentView]);
8231 CGRect bounds([content bounds]);
8232
8233 CGRect frame([indicator_ frame]);
8234 frame.origin.x = bounds.size.width - frame.size.width;
8323c1b9 8235 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
21ac0ce2
JF
8236
8237 if (kCFCoreFoundationVersionNumber < 800)
8238 frame.origin.x -= 8;
8239 [indicator_ setFrame:frame];
8240}
8241
003fc610 8242- (NSString *) accessibilityLabel {
66abff39 8243 return origin_;
003fc610
GP
8244}
8245
5829aea2
GP
8246- (void) drawContentRect:(CGRect)rect {
8247 bool highlighted(highlighted_);
8248 float width(rect.size.width);
36bb2ca2 8249
25c1dafb
JF
8250 if (icon_ != nil) {
8251 CGRect rect;
8252 rect.size = [(UIImage *) icon_ size];
8253
8254 while (rect.size.width > 32 || rect.size.height > 32) {
8255 rect.size.width /= 2;
8256 rect.size.height /= 2;
8257 }
8258
86a333c6
JF
8259 rect.origin.x = 26 - rect.size.width / 2;
8260 rect.origin.y = 26 - rect.size.height / 2;
25c1dafb 8261
8323c1b9 8262 [icon_ drawInRect:Retina(rect)];
25c1dafb 8263 }
36bb2ca2 8264
5d0438dc 8265 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5829aea2 8266 UISetColor(White_);
dc5812ec 8267
5829aea2
GP
8268 if (!highlighted)
8269 UISetColor(Black_);
ffb4fe6a 8270 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
f79a4512 8271
5829aea2 8272 if (!highlighted)
e93fd095 8273 UISetColor(Gray_);
ffb4fe6a 8274 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5829aea2 8275}
dc5812ec 8276
21ac0ce2
JF
8277- (void) setFetch:(NSNumber *)fetch {
8278 if ([fetch boolValue])
8279 [indicator_ startAnimating];
8280 else
8281 [indicator_ stopAnimating];
8282}
8283
3f8edf70
GP
8284@end
8285/* }}} */
8286/* Sources Controller {{{ */
cd79e8cf 8287@interface SourcesController : CyteViewController <
5829aea2
GP
8288 UITableViewDataSource,
8289 UITableViewDelegate
8290> {
8291 _transient Database *database_;
c33064f1
JF
8292 unsigned era_;
8293
bf7c998c 8294 _H<UITableView, 2> list_;
7b33d201 8295 _H<NSMutableArray> sources_;
5829aea2 8296 int offset_;
723a0072 8297
7b33d201
JF
8298 _H<NSString> href_;
8299 _H<UIProgressHUD> hud_;
8300 _H<NSError> error_;
dc63e78f 8301
5829aea2
GP
8302 NSURLConnection *trivial_bz2_;
8303 NSURLConnection *trivial_gz_;
b4d89997 8304
5829aea2
GP
8305 BOOL cydia_;
8306}
dc5812ec 8307
5829aea2 8308- (id) initWithDatabase:(Database *)database;
31eedaae 8309- (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
5829aea2
GP
8310
8311@end
8312
8313@implementation SourcesController
8314
8315- (void) _releaseConnection:(NSURLConnection *)connection {
8316 if (connection != nil) {
8317 [connection cancel];
8318 //[connection setDelegate:nil];
8319 [connection release];
36bb2ca2 8320 }
5829aea2 8321}
dc5812ec 8322
5829aea2 8323- (void) dealloc {
5829aea2
GP
8324 [self _releaseConnection:trivial_gz_];
8325 [self _releaseConnection:trivial_bz2_];
3178d79b 8326
5829aea2
GP
8327 [super dealloc];
8328}
b5e7eebb 8329
fe8e721f
GP
8330- (NSURL *) navigationURL {
8331 return [NSURL URLWithString:@"cydia://sources"];
8332}
8333
5829aea2
GP
8334- (void) viewDidAppear:(BOOL)animated {
8335 [super viewDidAppear:animated];
8336 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8337}
9bb3b295 8338
5829aea2 8339- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
55066b9e 8340 return 2;
5829aea2 8341}
8fe19fc1 8342
5829aea2 8343- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
55066b9e
JF
8344 if (section == 1)
8345 return UCLocalize("INDIVIDUAL_SOURCES");
90ba4f86 8346 return nil;
36bb2ca2 8347}
b4d89997 8348
5829aea2 8349- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
55066b9e
JF
8350 switch (section) {
8351 case 0: return 1;
8352 case 1: return [sources_ count];
8353 default: return 0;
8354 }
5829aea2 8355}
3178d79b 8356
5829aea2 8357- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
c33064f1
JF
8358@synchronized (database_) {
8359 if ([database_ era] != era_)
8360 return nil;
55066b9e
JF
8361 if ([indexPath section] != 1)
8362 return nil;
8dc0d35d 8363 NSUInteger index([indexPath row]);
55066b9e
JF
8364 if (index >= [sources_ count])
8365 return nil;
8366 return [sources_ objectAtIndex:index];
c33064f1 8367} }
b4d89997 8368
5829aea2
GP
8369- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8370 static NSString *cellIdentifier = @"SourceCell";
8371
8372 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
55066b9e 8373 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
b89fa270 8374 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
5829aea2 8375
55066b9e
JF
8376 Source *source([self sourceAtIndexPath:indexPath]);
8377 if (source == nil)
8378 [cell setAllSource];
8379 else
8380 [cell setSource:source];
8381
5829aea2 8382 return cell;
f6e13561
GP
8383}
8384
5829aea2 8385- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
55066b9e 8386 SectionsController *controller([[[SectionsController alloc]
5829aea2 8387 initWithDatabase:database_
55066b9e
JF
8388 source:[self sourceAtIndexPath:indexPath]
8389 ] autorelease]);
5829aea2 8390
3f8edf70 8391 [controller setDelegate:delegate_];
3f8edf70 8392 [[self navigationController] pushViewController:controller animated:YES];
36bb2ca2 8393}
b4d89997 8394
6840bff3 8395- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
55066b9e
JF
8396 if ([indexPath section] != 1)
8397 return false;
5829aea2
GP
8398 Source *source = [self sourceAtIndexPath:indexPath];
8399 return [source record] != nil;
dcb47737
RP
8400}
8401
6840bff3 8402- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
55066b9e 8403 _assert([indexPath section] == 1);
0e1aa02c
JF
8404 if (editingStyle == UITableViewCellEditingStyleDelete) {
8405 Source *source = [self sourceAtIndexPath:indexPath];
8dc0d35d
JF
8406 if (source == nil) return;
8407
0e1aa02c 8408 [Sources_ removeObjectForKey:[source key]];
c38cbbec
JF
8409 Changed_ = true;
8410
392ff7e4 8411 [delegate_ _saveConfig];
cc3b7d31 8412 [delegate_ reloadDataWithInvocation:nil];
0e1aa02c 8413 }
5829aea2 8414}
bcccf498 8415
51807490
JF
8416- (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8417 [self updateButtonsForEditingStatusAnimated:YES];
8418}
8419
5829aea2 8420- (void) complete {
93460555 8421 [delegate_ addTrivialSource:href_];
da3ec19c
JF
8422 href_ = nil;
8423
5829aea2 8424 [delegate_ syncData];
3178d79b
JF
8425}
8426
5829aea2
GP
8427- (NSString *) getWarning {
8428 NSString *href(href_);
8429 NSRange colon([href rangeOfString:@"://"]);
8430 if (colon.location != NSNotFound)
8431 href = [href substringFromIndex:(colon.location + 3)];
8432 href = [href stringByAddingPercentEscapes];
8433 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5829aea2
GP
8434
8435 NSURL *url([NSURL URLWithString:href]);
8436
8437 NSStringEncoding encoding;
8438 NSError *error(nil);
8439
8440 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8441 return [warning length] == 0 ? nil : warning;
8442 return nil;
807ae6d7 8443}
b4d89997 8444
5829aea2
GP
8445- (void) _endConnection:(NSURLConnection *)connection {
8446 // XXX: the memory management in this method is horribly awkward
8447
8448 NSURLConnection **field = NULL;
44990507 8449 if (connection == trivial_bz2_)
5829aea2
GP
8450 field = &trivial_bz2_;
8451 else if (connection == trivial_gz_)
8452 field = &trivial_gz_;
8453 _assert(field != NULL);
8454 [connection release];
8455 *field = nil;
8456
8457 if (
5829aea2
GP
8458 trivial_bz2_ == nil &&
8459 trivial_gz_ == nil
8460 ) {
da3ec19c
JF
8461 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8462
9eae15b8
JF
8463 [delegate_ releaseNetworkActivityIndicator];
8464
8465 [delegate_ removeProgressHUD:hud_];
9eae15b8
JF
8466 hud_ = nil;
8467
5829aea2 8468 if (cydia_) {
da3ec19c 8469 if (warning != nil) {
5829aea2
GP
8470 UIAlertView *alert = [[[UIAlertView alloc]
8471 initWithTitle:UCLocalize("SOURCE_WARNING")
8472 message:warning
8473 delegate:self
8474 cancelButtonTitle:UCLocalize("CANCEL")
1aa29546
JF
8475 otherButtonTitles:
8476 UCLocalize("ADD_ANYWAY"),
8477 nil
5829aea2
GP
8478 ] autorelease];
8479
8480 [alert setContext:@"warning"];
8481 [alert setNumberOfRows:1];
8482 [alert show];
708cf61e
JF
8483
8484 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8485 error_ = nil;
8486 return;
8487 }
8488
8489 [self complete];
5829aea2
GP
8490 } else if (error_ != nil) {
8491 UIAlertView *alert = [[[UIAlertView alloc]
8492 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8493 message:[error_ localizedDescription]
8494 delegate:self
8495 cancelButtonTitle:UCLocalize("OK")
8496 otherButtonTitles:nil
8497 ] autorelease];
8498
8499 [alert setContext:@"urlerror"];
8500 [alert show];
da3ec19c
JF
8501
8502 href_ = nil;
5829aea2
GP
8503 } else {
8504 UIAlertView *alert = [[[UIAlertView alloc]
8505 initWithTitle:UCLocalize("NOT_REPOSITORY")
8506 message:UCLocalize("NOT_REPOSITORY_EX")
8507 delegate:self
8508 cancelButtonTitle:UCLocalize("OK")
8509 otherButtonTitles:nil
8510 ] autorelease];
8511
8512 [alert setContext:@"trivial"];
8513 [alert show];
da3ec19c
JF
8514
8515 href_ = nil;
5829aea2
GP
8516 }
8517
7b33d201 8518 error_ = nil;
5829aea2 8519 }
807ae6d7 8520}
8fe19fc1 8521
5829aea2
GP
8522- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8523 switch ([response statusCode]) {
8524 case 200:
8525 cydia_ = YES;
8526 }
8e05f686
RP
8527}
8528
5829aea2 8529- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
47ff9ab8 8530 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7b33d201 8531 error_ = error;
5829aea2 8532 [self _endConnection:connection];
807ae6d7 8533}
b4d89997 8534
5829aea2
GP
8535- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8536 [self _endConnection:connection];
8537}
b4d89997 8538
5829aea2 8539- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
2e1652a9
JF
8540 NSURL *url([NSURL URLWithString:href]);
8541
5829aea2 8542 NSMutableURLRequest *request = [NSMutableURLRequest
2e1652a9 8543 requestWithURL:url
5829aea2 8544 cachePolicy:NSURLRequestUseProtocolCachePolicy
dd6f3b7b 8545 timeoutInterval:10
5829aea2 8546 ];
bc11cf5b 8547
5829aea2 8548 [request setHTTPMethod:method];
b4d89997 8549
5829aea2
GP
8550 if (Machine_ != NULL)
8551 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
2e1652a9 8552
1209b7de
JF
8553 if (UniqueID_ != nil)
8554 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8555
2e1652a9 8556 if ([url isCydiaSecure]) {
1209b7de 8557 if (UniqueID_ != nil)
c83678e8 8558 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
2e1652a9 8559 }
b4d89997 8560
5829aea2 8561 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
3178d79b
JF
8562}
8563
6840bff3 8564- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5829aea2 8565 NSString *context([alert context]);
dc5812ec 8566
5829aea2
GP
8567 if ([context isEqualToString:@"source"]) {
8568 switch (button) {
8569 case 1: {
8570 NSString *href = [[alert textField] text];
baf80942 8571
2595e4c3
JF
8572 static Pcre href_r("^http(s?)://[^# ]*$");
8573 if (!href_r(href)) {
8574 UIAlertView *alert = [[[UIAlertView alloc]
f27e8745
JF
8575 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8576 message:UCLocalize("INVALID_URL_EX")
2595e4c3
JF
8577 delegate:self
8578 cancelButtonTitle:UCLocalize("OK")
8579 otherButtonTitles:nil
8580 ] autorelease];
8581
8582 [alert setContext:@"badurl"];
8583 [alert show];
8584
8585 break;
8586 }
8587
5829aea2
GP
8588 if (![href hasSuffix:@"/"])
8589 href_ = [href stringByAppendingString:@"/"];
8590 else
8591 href_ = href;
b4d89997 8592
5829aea2
GP
8593 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8594 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
b4d89997 8595
5829aea2 8596 cydia_ = false;
8fe19fc1 8597
5829aea2 8598 // XXX: this is stupid
7b33d201 8599 hud_ = [delegate_ addProgressHUD];
5829aea2 8600 [hud_ setText:UCLocalize("VERIFYING_URL")];
dcaecde2 8601 [delegate_ retainNetworkActivityIndicator];
5829aea2 8602 } break;
770f2a8e 8603
5829aea2
GP
8604 case 0:
8605 break;
bc11cf5b 8606
5829aea2
GP
8607 _nodefault
8608 }
770f2a8e 8609
5829aea2
GP
8610 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8611 } else if ([context isEqualToString:@"trivial"])
8612 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8613 else if ([context isEqualToString:@"urlerror"])
8614 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8615 else if ([context isEqualToString:@"warning"]) {
8616 switch (button) {
8617 case 1:
da3ec19c 8618 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5829aea2 8619 break;
770f2a8e 8620
5829aea2
GP
8621 case 0:
8622 break;
b5e7eebb 8623
5829aea2
GP
8624 _nodefault
8625 }
770f2a8e 8626
5829aea2
GP
8627 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8628 }
8629}
770f2a8e 8630
e67ebdad
JF
8631- (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8632 BOOL editing([list_ isEditing]);
8633
8634 if (editing)
8635 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8636 initWithTitle:UCLocalize("ADD")
8637 style:UIBarButtonItemStylePlain
8638 target:self
8639 action:@selector(addButtonClicked)
8640 ] autorelease] animated:animated];
8641 else if ([delegate_ updating])
8642 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8643 initWithTitle:UCLocalize("CANCEL")
8644 style:UIBarButtonItemStyleDone
8645 target:self
8646 action:@selector(cancelButtonClicked)
8647 ] autorelease] animated:animated];
8648 else
8649 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8650 initWithTitle:UCLocalize("REFRESH")
8651 style:UIBarButtonItemStylePlain
8652 target:self
8653 action:@selector(refreshButtonClicked)
8654 ] autorelease] animated:animated];
8655
8656 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8657 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8658 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8659 target:self
8660 action:@selector(editButtonClicked)
8661 ] autorelease] animated:animated];
8662}
8663
fe8e721f 8664- (void) loadView {
e8cbebe4 8665 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
fe8e721f 8666 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6ac6e186 8667 [list_ setRowHeight:53];
7b33d201 8668 [(UITableView *) list_ setDataSource:self];
fe8e721f 8669 [list_ setDelegate:self];
e8cbebe4 8670 [self setView:list_];
fe8e721f 8671}
770f2a8e 8672
fe8e721f 8673- (void) viewDidLoad {
7d887d0b
JF
8674 [super viewDidLoad];
8675
fe8e721f 8676 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
31eedaae
JF
8677 [self updateButtonsForEditingStatusAnimated:NO];
8678}
8679
393699d7 8680- (void) viewWillAppear:(BOOL)animated {
31eedaae
JF
8681 [super viewWillAppear:animated];
8682
8683 [list_ setEditing:NO];
8684 [self updateButtonsForEditingStatusAnimated:NO];
fe8e721f 8685}
770f2a8e 8686
fe8e721f 8687- (void) releaseSubviews {
fe8e721f 8688 list_ = nil;
7be3eb32 8689
4f9acb7c
JF
8690 sources_ = nil;
8691
7be3eb32 8692 [super releaseSubviews];
fe8e721f 8693}
770f2a8e 8694
fe8e721f
GP
8695- (id) initWithDatabase:(Database *)database {
8696 if ((self = [super init]) != nil) {
8697 database_ = database;
807ae6d7
JF
8698 } return self;
8699}
770f2a8e 8700
807ae6d7 8701- (void) reloadData {
fe8e721f 8702 [super reloadData];
e67ebdad 8703 [self updateButtonsForEditingStatusAnimated:YES];
fe8e721f 8704
c33064f1
JF
8705@synchronized (database_) {
8706 era_ = [database_ era];
8707
4f9acb7c 8708 sources_ = [NSMutableArray arrayWithCapacity:16];
5829aea2
GP
8709 [sources_ addObjectsFromArray:[database_ sources]];
8710 _trace();
90ba4f86 8711 [sources_ sortUsingSelector:@selector(compareByName:)];
5829aea2
GP
8712 _trace();
8713
8714 int count([sources_ count]);
8715 offset_ = 0;
8716 for (int i = 0; i != count; i++) {
8717 if ([[sources_ objectAtIndex:i] record] == nil)
8718 break;
8719 offset_++;
770f2a8e 8720 }
807ae6d7 8721
5829aea2 8722 [list_ reloadData];
c33064f1 8723} }
770f2a8e 8724
5829aea2
GP
8725- (void) showAddSourcePrompt {
8726 UIAlertView *alert = [[[UIAlertView alloc]
8727 initWithTitle:UCLocalize("ENTER_APT_URL")
8728 message:nil
8729 delegate:self
8730 cancelButtonTitle:UCLocalize("CANCEL")
1aa29546
JF
8731 otherButtonTitles:
8732 UCLocalize("ADD_SOURCE"),
8733 nil
5829aea2 8734 ] autorelease];
770f2a8e 8735
5829aea2 8736 [alert setContext:@"source"];
770f2a8e 8737
5829aea2
GP
8738 [alert setNumberOfRows:1];
8739 [alert addTextFieldWithValue:@"http://" label:@""];
770f2a8e 8740
5829aea2
GP
8741 UITextInputTraits *traits = [[alert textField] textInputTraits];
8742 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8743 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8744 [traits setKeyboardType:UIKeyboardTypeURL];
8745 // XXX: UIReturnKeyDone
8746 [traits setReturnKeyType:UIReturnKeyNext];
770f2a8e 8747
5829aea2 8748 [alert show];
770f2a8e
JF
8749}
8750
5829aea2
GP
8751- (void) addButtonClicked {
8752 [self showAddSourcePrompt];
770f2a8e
JF
8753}
8754
e67ebdad
JF
8755- (void) refreshButtonClicked {
8756 if ([delegate_ requestUpdate])
8757 [self updateButtonsForEditingStatusAnimated:YES];
8758}
5829aea2 8759
e67ebdad
JF
8760- (void) cancelButtonClicked {
8761 [delegate_ cancelUpdate];
5829aea2
GP
8762}
8763
8764- (void) editButtonClicked {
8765 [list_ setEditing:![list_ isEditing] animated:YES];
31eedaae 8766 [self updateButtonsForEditingStatusAnimated:YES];
770f2a8e
JF
8767}
8768
21c6da4b
GP
8769@end
8770/* }}} */
f3e11d24 8771
f3e11d24 8772/* Stash Controller {{{ */
cd79e8cf 8773@interface StashController : CyteViewController {
7b33d201
JF
8774 _H<UIActivityIndicatorView> spinner_;
8775 _H<UILabel> status_;
8776 _H<UILabel> caption_;
f3e11d24 8777}
6840bff3 8778
f3e11d24
GP
8779@end
8780
5829aea2 8781@implementation StashController
f3e11d24 8782
fe8e721f 8783- (void) loadView {
39470a3a
JF
8784 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8785 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8786 [self setView:view];
8787
8788 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
fe8e721f 8789
7b33d201 8790 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
fe8e721f 8791 CGRect spinrect = [spinner_ frame];
8323c1b9 8792 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
fe8e721f
GP
8793 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8794 [spinner_ setFrame:spinrect];
8795 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
39470a3a 8796 [view addSubview:spinner_];
fe8e721f
GP
8797 [spinner_ startAnimating];
8798
8799 CGRect captrect;
8800 captrect.size.width = [[self view] frame].size.width;
8801 captrect.size.height = 40.0f;
8802 captrect.origin.x = 0;
8323c1b9 8803 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
7b33d201 8804 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
fe8e721f
GP
8805 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8806 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8807 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8808 [caption_ setTextColor:[UIColor whiteColor]];
8809 [caption_ setBackgroundColor:[UIColor clearColor]];
8810 [caption_ setShadowColor:[UIColor blackColor]];
b129e6d9 8811 [caption_ setTextAlignment:NSTextAlignmentCenter];
39470a3a 8812 [view addSubview:caption_];
fe8e721f
GP
8813
8814 CGRect statusrect;
8815 statusrect.size.width = [[self view] frame].size.width;
8816 statusrect.size.height = 30.0f;
8817 statusrect.origin.x = 0;
8323c1b9 8818 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
7b33d201 8819 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
fe8e721f
GP
8820 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8821 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8822 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8823 [status_ setTextColor:[UIColor whiteColor]];
8824 [status_ setBackgroundColor:[UIColor clearColor]];
8825 [status_ setShadowColor:[UIColor blackColor]];
b129e6d9 8826 [status_ setTextAlignment:NSTextAlignmentCenter];
39470a3a 8827 [view addSubview:status_];
fe8e721f
GP
8828}
8829
67dd58c7
JF
8830- (void) releaseSubviews {
8831 spinner_ = nil;
8832 status_ = nil;
8833 caption_ = nil;
7be3eb32
JF
8834
8835 [super releaseSubviews];
67dd58c7
JF
8836}
8837
770f2a8e 8838@end
807ae6d7 8839/* }}} */
770f2a8e 8840
a06e9179
JF
8841@interface CYURLCache : SDURLCache {
8842}
8843
8844@end
8845
8846@implementation CYURLCache
8847
8848- (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8849#if !ForRelease
8850 if (false);
8851 else if ([event isEqualToString:@"no-cache"])
8852 event = @"!!!";
8853 else if ([event isEqualToString:@"store"])
8854 event = @">>>";
8855 else if ([event isEqualToString:@"invalid"])
8856 event = @"???";
8857 else if ([event isEqualToString:@"memory"])
8858 event = @"mem";
8859 else if ([event isEqualToString:@"disk"])
8860 event = @"ssd";
8861 else if ([event isEqualToString:@"miss"])
8862 event = @"---";
8863
8864 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8865#endif
8866}
8867
5e845121
JF
8868- (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8869 if (NSURLResponse *response = [cached response])
8870 if (NSString *mime = [response MIMEType])
8871 if ([mime isEqualToString:@"text/cache-manifest"]) {
8872 NSURL *url([response URL]);
8873
8874#if !ForRelease
8875 NSLog(@"###: %@", [url absoluteString]);
8876#endif
8877
8878 @synchronized (HostConfig_) {
8879 [CachedURLs_ addObject:url];
8880 }
8881 }
8882
8883 [super storeCachedResponse:cached forRequest:request];
8884}
8885
a06e9179
JF
8886@end
8887
2367a917 8888@interface Cydia : UIApplication <
adb61bda 8889 ConfirmationControllerDelegate,
6915b806 8890 DatabaseDelegate,
c88974b1 8891 CydiaDelegate
2367a917 8892> {
7b33d201 8893 _H<UIWindow> window_;
5fe2bcc6 8894 _H<CydiaTabBarController> tabbar_;
9549563e 8895 _H<CyteTabBarController> emulated_;
3931b718 8896
7b33d201
JF
8897 _H<NSMutableArray> essential_;
8898 _H<NSMutableArray> broken_;
dc5812ec
JF
8899
8900 Database *database_;
dc5812ec 8901
7b33d201 8902 _H<NSURL> starturl_;
54043703 8903
235f5487 8904 unsigned locked_;
54043703 8905 unsigned activity_;
9b619239 8906
7b33d201 8907 _H<StashController> stash_;
f3e11d24 8908
8c02abc8 8909 bool loaded_;
dc5812ec
JF
8910}
8911
fed0d010 8912- (void) loadData;
670a0494 8913
dc5812ec
JF
8914@end
8915
8916@implementation Cydia
8917
2ef6faad 8918- (void) lockSuspend {
8a3b565c
JF
8919 if (locked_++ == 0) {
8920 if ($SBSSetInterceptsMenuButtonForever != NULL)
8921 (*$SBSSetInterceptsMenuButtonForever)(true);
26c8a4c8
JF
8922
8923 [self setIdleTimerDisabled:YES];
8a3b565c 8924 }
2ef6faad
JF
8925}
8926
8927- (void) unlockSuspend {
8a3b565c 8928 if (--locked_ == 0) {
26c8a4c8
JF
8929 [self setIdleTimerDisabled:NO];
8930
8a3b565c
JF
8931 if ($SBSSetInterceptsMenuButtonForever != NULL)
8932 (*$SBSSetInterceptsMenuButtonForever)(false);
8933 }
2ef6faad
JF
8934}
8935
b5e7eebb 8936- (void) beginUpdate {
7585ce66 8937 [tabbar_ beginUpdate];
b5e7eebb
GP
8938}
8939
e67ebdad
JF
8940- (void) cancelUpdate {
8941 [tabbar_ cancelUpdate];
8942}
8943
8944- (bool) requestUpdate {
8945 if (IsReachable("cydia.saurik.com")) {
8946 [self beginUpdate];
8947 return true;
8948 } else {
8949 UIAlertView *alert = [[[UIAlertView alloc]
8950 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8951 message:@"Host Unreachable" // XXX: Localize
8952 delegate:self
8953 cancelButtonTitle:UCLocalize("OK")
8954 otherButtonTitles:nil
8955 ] autorelease];
8956
8957 [alert setContext:@"norefresh"];
8958 [alert show];
8959
8960 return false;
8961 }
8962}
8963
b5e7eebb 8964- (BOOL) updating {
7585ce66 8965 return [tabbar_ updating];
b5e7eebb
GP
8966}
8967
9bedffaa
JF
8968- (void) _loaded {
8969 if ([broken_ count] != 0) {
8970 int count = [broken_ count];
8971
37d2b2a9 8972 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 8973 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
b5e7eebb
GP
8974 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8975 delegate:self
1dc38e9c 8976 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
1aa29546
JF
8977 otherButtonTitles:
8978 UCLocalize("TEMPORARY_IGNORE"),
8979 nil
9bedffaa
JF
8980 ] autorelease];
8981
37d2b2a9 8982 [alert setContext:@"fixhalf"];
59befad5 8983 [alert setNumberOfRows:2];
37d2b2a9 8984 [alert show];
9bedffaa
JF
8985 } else if (!Ignored_ && [essential_ count] != 0) {
8986 int count = [essential_ count];
8987
37d2b2a9 8988 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 8989 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
b5e7eebb
GP
8990 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8991 delegate:self
8992 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
1aa29546
JF
8993 otherButtonTitles:
8994 UCLocalize("UPGRADE_ESSENTIAL"),
8995 UCLocalize("COMPLETE_UPGRADE"),
8996 nil
9bedffaa
JF
8997 ] autorelease];
8998
37d2b2a9
GP
8999 [alert setContext:@"upgrade"];
9000 [alert show];
9bedffaa
JF
9001 }
9002}
9003
2925cbba
JF
9004- (void) returnToCydia {
9005 [self _loaded];
9006}
9007
7623f855 9008- (void) _saveConfig {
9ac1ef9e
JF
9009 @synchronized (database_) {
9010 _trace();
9011 MetaFile_.Sync();
9012 _trace();
9013 }
ffbb3bd5 9014
7623f855 9015 if (Changed_) {
7623f855 9016 NSString *error(nil);
ffbb3bd5 9017
7623f855
JF
9018 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9019 _trace();
9020 NSError *error(nil);
9021 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9022 NSLog(@"failure to save metadata data: %@", error);
9023 _trace();
ffbb3bd5
JF
9024
9025 Changed_ = false;
7623f855
JF
9026 } else {
9027 NSLog(@"failure to serialize metadata: %@", error);
7623f855 9028 }
7623f855 9029 }
33e30380 9030
25c1dafb 9031 CydiaWriteSources();
7623f855
JF
9032}
9033
89571a5b 9034// Navigation controller for the queuing badge.
15f0d613 9035- (UINavigationController *) queueNavigationController {
89571a5b
GP
9036 NSArray *controllers = [tabbar_ viewControllers];
9037 return [controllers objectAtIndex:3];
9038}
9039
302bf91c
JF
9040- (void) unloadData {
9041 [tabbar_ unloadData];
9042}
9043
7623f855
JF
9044- (void) _updateData {
9045 [self _saveConfig];
302bf91c 9046 [self unloadData];
f6371a33 9047
15f0d613 9048 UINavigationController *navigation = [self queueNavigationController];
b5e7eebb 9049
4305896c 9050 id queuedelegate = nil;
89571a5b
GP
9051 if ([[navigation viewControllers] count] > 0)
9052 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
bc11cf5b 9053
89571a5b
GP
9054 [queuedelegate queueStatusDidChange];
9055 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
7623f855
JF
9056}
9057
53fb38da 9058- (void) _refreshIfPossible:(NSDate *)update {
8c02abc8 9059 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
bc11cf5b 9060
45e21ffa 9061 bool recently = false;
45e21ffa
GP
9062 if (update != nil) {
9063 NSTimeInterval interval([update timeIntervalSinceNow]);
9064 if (interval <= 0 && interval > -(15*60))
9065 recently = true;
9066 }
9067
9068 // Don't automatic refresh if:
9069 // - We already refreshed recently.
9070 // - We already auto-refreshed this launch.
9071 // - Auto-refresh is disabled.
8d3505c5
JF
9072 // - Cydia's server is not reachable
9073 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
35f0a3b5 9074 // If we are cancelling, we need to make sure it knows it's already loaded.
45e21ffa 9075 loaded_ = true;
d13edf44
JF
9076
9077 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
45e21ffa
GP
9078 } else {
9079 // We are going to load, so remember that.
9080 loaded_ = true;
45e21ffa 9081
8d3505c5 9082 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
d13edf44 9083 }
9aecdc9c 9084
8c02abc8 9085 [pool release];
9aecdc9c
GP
9086}
9087
9088- (void) refreshIfPossible {
53fb38da 9089 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9aecdc9c
GP
9090}
9091
e09e1589 9092- (void) reloadDataWithInvocation:(NSInvocation *)invocation {
1a83afc6 9093_profile(reloadDataWithInvocation)
e09e1589 9094@synchronized (self) {
851f4a99 9095 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
1450c2b3
JF
9096 if (hud != nil)
9097 [hud setText:UCLocalize("RELOADING_DATA")];
dc5812ec 9098
4ba8f30a 9099 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
d061f4ba 9100
36bb2ca2 9101 size_t changes(0);
9bedffaa 9102
a54b1c10 9103 [essential_ removeAllObjects];
9bedffaa 9104 [broken_ removeAllObjects];
b4d89997 9105
1a83afc6 9106 _profile(reloadDataWithInvocation$Essential)
670a0494 9107 NSArray *packages([database_ packages]);
affeffc7 9108 for (Package *package in packages) {
9bedffaa
JF
9109 if ([package half])
9110 [broken_ addObject:package];
823e2d97
JF
9111 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9112 if ([package essential] && [package installed] != nil)
a54b1c10 9113 [essential_ addObject:package];
36bb2ca2 9114 ++changes;
a54b1c10 9115 }
36bb2ca2 9116 }
1a83afc6 9117 _end
b4d89997 9118
89571a5b 9119 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
36bb2ca2 9120 if (changes != 0) {
0e1784b4 9121 _trace();
36bb2ca2 9122 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
45e21ffa 9123 [changesItem setBadgeValue:badge];
65a03a7a 9124 [changesItem setAnimatedBadge:([essential_ count] > 0)];
0e1784b4 9125 [self setApplicationIconBadgeNumber:changes];
c25a610d 9126 } else {
0e1784b4 9127 _trace();
45e21ffa
GP
9128 [changesItem setBadgeValue:nil];
9129 [changesItem setAnimatedBadge:NO];
0e1784b4 9130 [self setApplicationIconBadgeNumber:0];
c25a610d 9131 }
b4d89997 9132
7623f855 9133 [self _updateData];
be64dfbf
JF
9134
9135 if (hud != nil)
9136 [self removeProgressHUD:hud];
1a83afc6
JF
9137}
9138_end
9139
9140 PrintTimes();
9141}
6d9712c4 9142
7b0ce2da 9143- (void) updateData {
7623f855 9144 [self _updateData];
b4d89997
JF
9145}
9146
383a58ac
JF
9147- (void) updateDataAndLoad {
9148 [self _updateData];
9149 if ([database_ progressDelegate] == nil)
9150 [self _loaded];
9151}
9152
7b0ce2da
JF
9153- (void) update_ {
9154 [database_ update];
fca2f596 9155 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
7b0ce2da
JF
9156}
9157
2e9123cb
JF
9158- (void) disemulate {
9159 if (emulated_ == nil)
9160 return;
9161
81628115
JF
9162 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9163 [window_ setRootViewController:tabbar_];
237c3d1c
JF
9164 else {
9165 [window_ addSubview:[tabbar_ view]];
9166 [[emulated_ view] removeFromSuperview];
9167 }
9168
2e9123cb
JF
9169 emulated_ = nil;
9170 [window_ setUserInteractionEnabled:YES];
9171}
9172
9173- (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
15f0d613 9174 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
6915b806
JF
9175 if (IsWildcat_)
9176 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
2e9123cb
JF
9177
9178 UIViewController *parent;
9179 if (emulated_ == nil)
9180 parent = tabbar_;
9181 else if (!force)
9182 parent = emulated_;
9183 else {
9184 [self disemulate];
9185 parent = tabbar_;
9186 }
9187
9188 [parent presentModalViewController:navigation animated:YES];
6915b806
JF
9189}
9190
9191- (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9192 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9193
9194 if (navigation != nil)
9195 [navigation pushViewController:progress animated:YES];
9196 else
2e9123cb 9197 [self presentModalViewController:progress force:YES];
6915b806
JF
9198
9199 [progress invoke:invocation withTitle:title];
9200 return progress;
9201}
9202
9203- (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9204 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9205}
9206
9207- (void) repairWithInvocation:(NSInvocation *)invocation {
9208 _trace();
8d5bc2ad 9209 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
6915b806
JF
9210 _trace();
9211}
9212
9213- (void) repairWithSelector:(SEL)selector {
9214 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9215}
9216
e09e1589
JF
9217- (void) reloadData {
9218 [self reloadDataWithInvocation:nil];
2925cbba
JF
9219 if ([database_ progressDelegate] == nil)
9220 [self _loaded];
e09e1589
JF
9221}
9222
7b0ce2da 9223- (void) syncData {
1fe5dc43 9224 [self _saveConfig];
33e30380
JF
9225 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9226}
1fe5dc43 9227
33e30380 9228- (void) addSource:(NSDictionary *) source {
25c1dafb 9229 CydiaAddSource(source);
33e30380 9230}
7b0ce2da 9231
33e30380 9232- (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
25c1dafb 9233 CydiaAddSource(href, distribution, sections);
7b0ce2da
JF
9234}
9235
93460555 9236- (void) addTrivialSource:(NSString *)href {
25c1dafb 9237 CydiaAddSource(href, @"./");
93460555
JF
9238}
9239
b3c8e69c
JF
9240- (void) updateValues {
9241 Changed_ = true;
9242}
9243
b4d89997
JF
9244- (void) resolve {
9245 pkgProblemResolver *resolver = [database_ resolver];
9246
9247 resolver->InstallProtect();
9248 if (!resolver->Resolve(true))
9249 _error->Discard();
2367a917
JF
9250}
9251
670a0494 9252- (bool) perform {
d6c371f5
JF
9253 // XXX: this is a really crappy way of doing this.
9254 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9255 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9256 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9257 if ([tabbar_ updating])
9258 [tabbar_ cancelUpdate];
9259
670a0494
JF
9260 if (![database_ prepare])
9261 return false;
49048579 9262
adb61bda 9263 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
affeffc7 9264 [page setDelegate:self];
15f0d613 9265 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
49048579 9266
36fbb2aa
JF
9267 if (IsWildcat_)
9268 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
7585ce66 9269 [tabbar_ presentModalViewController:confirm_ animated:YES];
670a0494
JF
9270
9271 return true;
3178d79b
JF
9272}
9273
dc63e78f
JF
9274- (void) queue {
9275 @synchronized (self) {
9276 [self perform];
9277 }
9278}
9279
9280- (void) clearPackage:(Package *)package {
9281 @synchronized (self) {
9282 [package clear];
9283 [self resolve];
9284 [self perform];
9285 }
9286}
9287
77801ff1
JF
9288- (void) installPackages:(NSArray *)packages {
9289 @synchronized (self) {
9290 for (Package *package in packages)
9291 [package install];
9292 [self resolve];
9293 [self perform];
9294 }
9295}
9296
36bb2ca2
JF
9297- (void) installPackage:(Package *)package {
9298 @synchronized (self) {
9299 [package install];
9300 [self resolve];
9301 [self perform];
9302 }
9303}
9304
9305- (void) removePackage:(Package *)package {
9306 @synchronized (self) {
9307 [package remove];
9308 [self resolve];
9309 [self perform];
9310 }
9311}
9312
9313- (void) distUpgrade {
9314 @synchronized (self) {
670a0494
JF
9315 if (![database_ upgrade])
9316 return;
36bb2ca2
JF
9317 [self perform];
9318 }
b4d89997
JF
9319}
9320
780cdb3b
JF
9321- (void) _uicache {
9322 _trace();
9323 system("su -c /usr/bin/uicache mobile");
9324 _trace();
9325}
9326
9327- (void) uicache {
9328 UIProgressHUD *hud([self addProgressHUD]);
9329 [hud setText:UCLocalize("LOADING")];
9330 [self yieldToSelector:@selector(_uicache)];
9331 [self removeProgressHUD:hud];
9332}
9333
fca2f596
JF
9334- (void) perform_ {
9335 [database_ perform];
9336 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
780cdb3b 9337 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
fca2f596
JF
9338}
9339
b5e7eebb 9340- (void) confirmWithNavigationController:(UINavigationController *)navigation {
f6371a33 9341 Queuing_ = false;
2ef6faad 9342 [self lockSuspend];
fca2f596 9343 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
2ef6faad 9344 [self unlockSuspend];
dc5812ec
JF
9345}
9346
54043703
JF
9347- (void) retainNetworkActivityIndicator {
9348 if (activity_++ == 0)
9349 [self setNetworkActivityIndicatorVisible:YES];
848ed88b
JF
9350
9351#if TraceLogging
9352 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9353#endif
54043703
JF
9354}
9355
9356- (void) releaseNetworkActivityIndicator {
9357 if (--activity_ == 0)
9358 [self setNetworkActivityIndicatorVisible:NO];
848ed88b
JF
9359
9360#if TraceLogging
9361 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9362#endif
9363
54043703
JF
9364}
9365
674dce72
GP
9366- (void) cancelAndClear:(bool)clear {
9367 @synchronized (self) {
9368 if (clear) {
c6ca67ba 9369 [database_ clear];
b5e7eebb 9370 Queuing_ = false;
674dce72 9371 } else {
b5e7eebb 9372 Queuing_ = true;
6067f1b8
JF
9373 }
9374
a4217bbb 9375 [self _updateData];
674dce72 9376 }
37d2b2a9 9377}
7b0ce2da 9378
b5e7eebb
GP
9379- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9380 NSString *context([alert context]);
bc11cf5b 9381
6915b806
JF
9382 if ([context isEqualToString:@"conffile"]) {
9383 FILE *input = [database_ input];
9384 if (button == [alert cancelButtonIndex])
9385 fprintf(input, "N\n");
9386 else if (button == [alert firstOtherButtonIndex])
9387 fprintf(input, "Y\n");
9388 fflush(input);
9389
9390 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9391 } else if ([context isEqualToString:@"fixhalf"]) {
efa53fa9 9392 if (button == [alert cancelButtonIndex]) {
37d2b2a9 9393 @synchronized (self) {
7b33d201 9394 for (Package *broken in (id) broken_) {
37d2b2a9
GP
9395 [broken remove];
9396
9397 NSString *id = [broken id];
9398 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9399 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9400 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9401 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9402 }
7b0ce2da 9403
37d2b2a9
GP
9404 [self resolve];
9405 [self perform];
9406 }
efa53fa9 9407 } else if (button == [alert firstOtherButtonIndex]) {
37d2b2a9
GP
9408 [broken_ removeAllObjects];
9409 [self _loaded];
7b0ce2da
JF
9410 }
9411
37d2b2a9 9412 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 9413 } else if ([context isEqualToString:@"upgrade"]) {
37d2b2a9
GP
9414 if (button == [alert firstOtherButtonIndex]) {
9415 @synchronized (self) {
7b33d201 9416 for (Package *essential in (id) essential_)
37d2b2a9 9417 [essential install];
7b0ce2da 9418
37d2b2a9
GP
9419 [self resolve];
9420 [self perform];
9421 }
9422 } else if (button == [alert firstOtherButtonIndex] + 1) {
9423 [self distUpgrade];
9424 } else if (button == [alert cancelButtonIndex]) {
9425 Ignored_ = YES;
7b0ce2da
JF
9426 }
9427
37d2b2a9 9428 [alert dismissWithClickedButtonIndex:-1 animated:YES];
1cedb821 9429 }
7b0ce2da
JF
9430}
9431
d13edf44
JF
9432- (void) system:(NSString *)command {
9433 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9434
985d2dff 9435 _trace();
670a0494 9436 system([command UTF8String]);
985d2dff 9437 _trace();
d13edf44
JF
9438
9439 [pool release];
670a0494
JF
9440}
9441
9442- (void) applicationWillSuspend {
9443 [database_ clean];
9444 [super applicationWillSuspend];
bd150f54
JF
9445}
9446
235f5487 9447- (BOOL) isSafeToSuspend {
5927fe03
JF
9448 if (locked_ != 0) {
9449#if !ForRelease
9450 NSLog(@"isSafeToSuspend: locked_ != 0");
9451#endif
9452 return false;
9453 }
9454
7187b5b2
JF
9455 if ([tabbar_ modalViewController] != nil)
9456 return false;
9457
262afe11
GP
9458 // Use external process status API internally.
9459 // This is probably a really bad idea.
235f5487 9460 // XXX: what is the point of this? does this solve anything at all?
262afe11
GP
9461 uint64_t status = 0;
9462 int notify_token;
9463 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
9464 notify_get_state(notify_token, &status);
9465 notify_cancel(notify_token);
9466 }
9467
5927fe03
JF
9468 if (status != 0) {
9469#if !ForRelease
9470 NSLog(@"isSafeToSuspend: status != 0");
9471#endif
9472 return false;
9473 }
9474
9475#if !ForRelease
9476 NSLog(@"isSafeToSuspend: -> true");
9477#endif
9478 return true;
235f5487
JF
9479}
9480
9481- (void) applicationSuspend:(__GSEvent *)event {
9482 if ([self isSafeToSuspend])
bd150f54 9483 [super applicationSuspend:event];
bd150f54
JF
9484}
9485
6d9712c4 9486- (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
235f5487 9487 if ([self isSafeToSuspend])
6d9712c4
JF
9488 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9489}
9490
9491- (void) _setSuspended:(BOOL)value {
235f5487 9492 if ([self isSafeToSuspend])
6d9712c4
JF
9493 [super _setSuspended:value];
9494}
9495
7b0ce2da 9496- (UIProgressHUD *) addProgressHUD {
8c9453da 9497 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
04fe1349
JF
9498 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9499
d061f4ba 9500 [window_ setUserInteractionEnabled:NO];
534e31fc 9501
f36e5eac
JF
9502 UIViewController *target(tabbar_);
9503 if (UIViewController *modal = [target modalViewController])
9504 target = modal;
9505
22b6c4b8 9506 [hud showInView:[target view]];
534e31fc 9507
2ef6faad 9508 [self lockSuspend];
7b0ce2da
JF
9509 return hud;
9510}
9511
d061f4ba 9512- (void) removeProgressHUD:(UIProgressHUD *)hud {
2ef6faad 9513 [self unlockSuspend];
8c9453da 9514 [hud hide];
d061f4ba
JF
9515 [hud removeFromSuperview];
9516 [window_ setUserInteractionEnabled:YES];
9517}
9518
f050e4d9
JF
9519- (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9520 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
c390d3ab
JF
9521}
9522
f050e4d9 9523- (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
e47c4742 9524 NSString *scheme([[url scheme] lowercaseString]);
f6e13561 9525 if ([[url absoluteString] length] <= [scheme length] + 3)
e47c4742 9526 return nil;
f6e13561 9527 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
3a159223 9528 NSArray *components([path componentsSeparatedByString:@"/"]);
f6e13561 9529
4fd0c466 9530 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
f050e4d9 9531 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
4fd0c466
JF
9532 if (controller != nil)
9533 [controller setDelegate:self];
9534 return controller;
9535 }
f6e13561
GP
9536
9537 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
e47c4742 9538 return nil;
f6e13561
GP
9539
9540 NSString *base([components objectAtIndex:0]);
9541
cd79e8cf 9542 CyteViewController *controller = nil;
f5a17517 9543
f70ea899 9544 if ([base isEqualToString:@"url"]) {
106d645f
GP
9545 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9546 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
a576488f 9547 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
028dbd1c 9548 } else if (!external && [components count] == 1) {
f6e13561 9549 if ([base isEqualToString:@"sources"]) {
f5a17517 9550 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
f6e13561
GP
9551 }
9552
9553 if ([base isEqualToString:@"home"]) {
f5a17517 9554 controller = [[[HomeController alloc] init] autorelease];
f6e13561
GP
9555 }
9556
9557 if ([base isEqualToString:@"sections"]) {
55066b9e 9558 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
f6e13561
GP
9559 }
9560
9561 if ([base isEqualToString:@"search"]) {
43625891 9562 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
f6e13561
GP
9563 }
9564
9565 if ([base isEqualToString:@"changes"]) {
ea3bb538 9566 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
f6e13561
GP
9567 }
9568
9569 if ([base isEqualToString:@"installed"]) {
f5a17517 9570 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
f6e13561
GP
9571 }
9572 } else if ([components count] == 2) {
8912cff7 9573 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
f6e13561
GP
9574
9575 if ([base isEqualToString:@"package"]) {
f050e4d9 9576 controller = [self pageForPackage:argument withReferrer:referrer];
f6e13561
GP
9577 }
9578
028dbd1c 9579 if (!external && [base isEqualToString:@"search"]) {
8912cff7 9580 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
f6e13561
GP
9581 }
9582
028dbd1c 9583 if (!external && [base isEqualToString:@"sections"]) {
55066b9e 9584 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
f6e13561 9585 argument = nil;
55066b9e 9586 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
f6e13561
GP
9587 }
9588
028dbd1c 9589 if (!external && [base isEqualToString:@"sources"]) {
f6e13561 9590 if ([argument isEqualToString:@"add"]) {
f5a17517
GP
9591 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9592 [(SourcesController *)controller showAddSourcePrompt];
f6e13561 9593 } else {
8912cff7 9594 Source *source([database_ sourceWithKey:argument]);
55066b9e 9595 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
f6e13561
GP
9596 }
9597 }
9598
028dbd1c 9599 if (!external && [base isEqualToString:@"launch"]) {
f6e13561 9600 [self launchApplicationWithIdentifier:argument suspended:NO];
f5a17517 9601 return nil;
f6e13561 9602 }
028dbd1c 9603 } else if (!external && [components count] == 3) {
8912cff7
JF
9604 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9605 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
f6e13561
GP
9606
9607 if ([base isEqualToString:@"package"]) {
9608 if ([arg2 isEqualToString:@"settings"]) {
f5a17517 9609 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
f6e13561
GP
9610 } else if ([arg2 isEqualToString:@"files"]) {
9611 if (Package *package = [database_ packageWithName:arg1]) {
f5a17517
GP
9612 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9613 [(FileTable *)controller setPackage:package];
f6e13561
GP
9614 }
9615 }
c390d3ab 9616 }
55066b9e
JF
9617
9618 if ([base isEqualToString:@"sections"]) {
9619 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9620 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9621 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9622 }
c390d3ab
JF
9623 }
9624
f5a17517
GP
9625 [controller setDelegate:self];
9626 return controller;
c390d3ab
JF
9627}
9628
028dbd1c 9629- (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
f050e4d9 9630 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
40364973 9631
e965092a
JF
9632 if (page != nil)
9633 [tabbar_ setUnselectedViewController:page];
40364973 9634
f6e13561 9635 return page != nil;
40364973
GP
9636}
9637
c390d3ab
JF
9638- (void) applicationOpenURL:(NSURL *)url {
9639 [super applicationOpenURL:url];
d817e4de 9640
7b33d201
JF
9641 if (!loaded_)
9642 starturl_ = url;
9643 else
9644 [self openCydiaURL:url forExternal:YES];
c390d3ab
JF
9645}
9646
bc11cf5b 9647- (void) applicationWillResignActive:(UIApplication *)application {
7eff7ea6 9648 // Stop refreshing if you get a phone call or lock the device.
7585ce66
JF
9649 if ([tabbar_ updating])
9650 [tabbar_ cancelUpdate];
bc11cf5b 9651
ca584c15
GP
9652 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9653 [super applicationWillResignActive:application];
7eff7ea6
GP
9654}
9655
9dd3045d 9656- (void) saveState {
35f0a3b5 9657 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
fe8e721f
GP
9658 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9659 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9dd3045d 9660 Changed_ = true;
fe8e721f
GP
9661
9662 [self _saveConfig];
9663}
9664
9dd3045d
JF
9665- (void) applicationWillTerminate:(UIApplication *)application {
9666 [self saveState];
9667}
9668
6915b806
JF
9669- (void) setConfigurationData:(NSString *)data {
9670 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9671
9672 if (!conffile_r(data)) {
9673 lprintf("E:invalid conffile\n");
9674 return;
9675 }
9676
9677 NSString *ofile = conffile_r[1];
9678 //NSString *nfile = conffile_r[2];
9679
9680 UIAlertView *alert = [[[UIAlertView alloc]
9681 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9682 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9683 delegate:self
9684 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9685 otherButtonTitles:
9686 UCLocalize("ACCEPT_NEW_COPY"),
9687 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9688 nil
9689 ] autorelease];
9690
9691 [alert setContext:@"conffile"];
a08145a8 9692 [alert setNumberOfRows:2];
6915b806
JF
9693 [alert show];
9694}
9695
f3e11d24 9696- (void) addStashController {
2ef6faad 9697 [self lockSuspend];
7b33d201 9698 stash_ = [[[StashController alloc] init] autorelease];
f3e11d24
GP
9699 [window_ addSubview:[stash_ view]];
9700}
9701
9702- (void) removeStashController {
9703 [[stash_ view] removeFromSuperview];
7b33d201 9704 stash_ = nil;
2ef6faad 9705 [self unlockSuspend];
f3e11d24
GP
9706}
9707
9708- (void) stash {
9e1f1e91 9709 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
f3e11d24 9710 UpdateExternalStatus(1);
f3e11d24 9711 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
f3e11d24 9712 UpdateExternalStatus(0);
f3e11d24
GP
9713
9714 [self removeStashController];
9715
d99e3659
JF
9716 pid_t pid(ExecFork());
9717 if (pid == 0) {
f3e11d24
GP
9718 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9719 perror("launchctl stop");
d99e3659 9720
51c8106a
JF
9721 exit(0);
9722 } ReapZombie(pid);
f3e11d24
GP
9723}
9724
f6e13561 9725- (void) setupViewControllers {
5fe2bcc6 9726 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
851f4a99 9727
6445279b
JF
9728 NSMutableArray *items;
9729 if (kCFCoreFoundationVersionNumber < 800) {
9730 items = [NSMutableArray arrayWithObjects:
9731 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
55066b9e 9732 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
3ccd7d11 9733 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
55066b9e 9734 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
6445279b
JF
9735 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9736 nil];
851f4a99 9737 } else {
6445279b
JF
9738 items = [NSMutableArray arrayWithObjects:
9739 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
55066b9e 9740 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
3ccd7d11 9741 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
55066b9e 9742 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
6445279b
JF
9743 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9744 nil];
851f4a99
GP
9745 }
9746
9747 NSMutableArray *controllers([NSMutableArray array]);
851f4a99 9748 for (UITabBarItem *item in items) {
15f0d613 9749 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
851f4a99
GP
9750 [controller setTabBarItem:item];
9751 [controllers addObject:controller];
9752 }
851f4a99 9753 [tabbar_ setViewControllers:controllers];
4305896c 9754
f6e13561 9755 [tabbar_ setUpdateDelegate:self];
851f4a99
GP
9756}
9757
968afbcd 9758- (void) _sendMemoryWarningNotification {
85106ebe
JF
9759 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9760 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9761 else
9762 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
968afbcd
JF
9763}
9764
9765- (void) _sendMemoryWarningNotifications {
9766 while (true) {
9767 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
740f9f75
JF
9768 sleep(2);
9769 //usleep(2000000);
968afbcd
JF
9770 }
9771}
9772
9256a1ce
JF
9773- (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9774 NSLog(@"--");
9775 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9776}
9777
bd150f54 9778- (void) applicationDidFinishLaunching:(id)unused {
968afbcd
JF
9779 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9780
7e30ba6d 9781_trace();
1e94d48b
JF
9782 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9783 [self setApplicationSupportsShakeToEdit:NO];
9784
48f1762f
JF
9785 @synchronized (HostConfig_) {
9786 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9787 }
3171f7fe 9788
4058b165
JF
9789 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9790 initWithMemoryCapacity:524288
9791 diskCapacity:10485760
d1c7f1fd 9792 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
4058b165 9793 ] autorelease]];
71cc7be1 9794
a576488f 9795 [CydiaWebViewController _initialize];
ea173384 9796
bfc87a4d
JF
9797 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9798
793aee35
JF
9799 // this would disallow http{,s} URLs from accessing this data
9800 //[WebView registerURLSchemeAsLocal:@"cydia"];
9801
7b33d201
JF
9802 Font12_ = [UIFont systemFontOfSize:12];
9803 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9804 Font14_ = [UIFont systemFontOfSize:14];
2cdc6e57 9805 Font18_ = [UIFont systemFontOfSize:18];
7b33d201
JF
9806 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9807 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
f641a0e5 9808
7b33d201
JF
9809 essential_ = [NSMutableArray arrayWithCapacity:4];
9810 broken_ = [NSMutableArray arrayWithCapacity:4];
bd150f54 9811
4e89e880 9812 // XXX: I really need this thing... like, seriously... I'm sorry
29bb09d7 9813 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
4e89e880 9814
7b33d201 9815 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
f641a0e5
JF
9816 [window_ orderFront:self];
9817 [window_ makeKey:self];
c390d3ab 9818 [window_ setHidden:NO];
04fe1349 9819
96ed699d 9820 if (false) stash: {
f3e11d24 9821 [self addStashController];
3931b718
JF
9822 // XXX: this would be much cleaner as a yieldToSelector:
9823 // that way the removeStashController could happen right here inline
9824 // we also could no longer require the useless stash_ field anymore
f3e11d24
GP
9825 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9826 return;
9827 }
9828
2656fd54
JF
9829 struct stat root;
9830 int error(stat("/", &root));
9831 _assert(error != -1);
9832
96ed699d 9833 #define Stash_(path) do { \
2656fd54
JF
9834 struct stat folder; \
9835 int error(lstat((path), &folder)); \
9836 if (error != -1 && ( \
9837 folder.st_dev == root.st_dev && \
9838 S_ISDIR(folder.st_mode) \
9839 ) || error == -1 && ( \
9840 errno == ENOENT || \
9841 errno == ENOTDIR \
9842 )) goto stash; \
96ed699d
JF
9843 } while (false)
9844
9845 Stash_("/Applications");
9846 Stash_("/Library/Ringtones");
9847 Stash_("/Library/Wallpaper");
9848 //Stash_("/usr/bin");
9849 Stash_("/usr/include");
9850 Stash_("/usr/lib/pam");
96ed699d
JF
9851 Stash_("/usr/share");
9852 //Stash_("/var/lib");
9853
770f2a8e 9854 database_ = [Database sharedInstance];
6915b806 9855 [database_ setDelegate:self];
bfc87a4d 9856
89571a5b 9857 [window_ setUserInteractionEnabled:NO];
0be165c8 9858 [self setupViewControllers];
6915b806 9859
9549563e
JF
9860 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9861 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9862 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9863
9864 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9865 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9866 [emulated_ setSelectedIndex:0];
1c28763e
JF
9867
9868 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9869 [emulated_ concealTabBarSelection];
9549563e 9870
81628115
JF
9871 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9872 [window_ setRootViewController:emulated_];
237c3d1c
JF
9873 else
9874 [window_ addSubview:[emulated_ view]];
5ccb47d8 9875
fed0d010 9876 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
c626a63f 9877_trace();
fed0d010
JF
9878}
9879
d3a28a81
GP
9880- (NSArray *) defaultStartPages {
9881 NSMutableArray *standard = [NSMutableArray array];
9882 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
55066b9e 9883 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
d3a28a81 9884 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
55066b9e 9885 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
d3a28a81
GP
9886 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9887 return standard;
9888}
9889
fed0d010 9890- (void) loadData {
c626a63f 9891_trace();
4121c5e0
JF
9892 if ([emulated_ modalViewController] != nil)
9893 [emulated_ dismissModalViewControllerAnimated:YES];
9894 [window_ setUserInteractionEnabled:NO];
fed0d010 9895
2925cbba
JF
9896 [self reloadDataWithInvocation:nil];
9897 [self refreshIfPossible];
2e9123cb 9898 [self disemulate];
5ccb47d8 9899
d3a28a81 9900 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
0c4fe0f4 9901 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
d3a28a81
GP
9902 int standardIndex = 0;
9903 NSArray *standard = [self defaultStartPages];
fe8e721f 9904
d3a28a81
GP
9905 BOOL valid = YES;
9906
9907 if (saved == nil)
9908 valid = NO;
9909
9910 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9911 if (valid && closed != nil) {
fe8e721f 9912 NSTimeInterval interval([closed timeIntervalSinceNow]);
ade2267f
JF
9913 // XXX: Is 30 minutes the optimal time here?
9914 if (interval <= -(30*60))
d3a28a81 9915 valid = NO;
fe8e721f
GP
9916 }
9917
d3a28a81
GP
9918 if (valid && [saved count] != [standard count])
9919 valid = NO;
efa53fa9 9920
d3a28a81
GP
9921 if (valid) {
9922 for (unsigned int i = 0; i < [standard count]; i++) {
9923 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9924 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9925 // but it's good enough for now.
9926 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9927 valid = NO;
9928 break;
9929 }
fe8e721f 9930 }
fe8e721f
GP
9931 }
9932
d3a28a81
GP
9933 NSArray *items = nil;
9934 if (valid) {
9935 [tabbar_ setSelectedIndex:savedIndex];
9936 items = saved;
9937 } else {
9938 [tabbar_ setSelectedIndex:standardIndex];
9939 items = standard;
9940 }
9941
fe8e721f
GP
9942 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9943 NSArray *stack = [items objectAtIndex:tab];
15f0d613 9944 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
fe8e721f
GP
9945 NSMutableArray *current = [NSMutableArray array];
9946
9947 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9948 NSString *addr = [stack objectAtIndex:nav];
9949 NSURL *url = [NSURL URLWithString:addr];
f050e4d9 9950 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
fe8e721f
GP
9951 if (page != nil)
9952 [current addObject:page];
9953 }
9954
9955 [navigation setViewControllers:current];
9956 }
f6e13561 9957
89571a5b 9958 // (Try to) show the startup URL.
f6e13561 9959 if (starturl_ != nil) {
f14bba69 9960 [self openCydiaURL:starturl_ forExternal:YES];
f6e13561
GP
9961 starturl_ = nil;
9962 }
bd150f54
JF
9963}
9964
b5e7eebb 9965- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
674dce72 9966 if (item != nil && IsWildcat_) {
b5e7eebb 9967 [sheet showFromBarButtonItem:item animated:YES];
674dce72
GP
9968 } else {
9969 [sheet showInView:window_];
9970 }
36bb2ca2
JF
9971}
9972
6915b806
JF
9973- (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9974 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9975 [progress setTitle:task];
9976 [progress addProgressEvent:event];
9977}
9978
9979- (void) addProgressEventForTask:(NSArray *)data {
9980 CydiaProgressEvent *event([data objectAtIndex:0]);
9981 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9982 [self addProgressEvent:event forTask:task];
9983}
9984
9985- (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9986 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9987}
9988
dc5812ec
JF
9989@end
9990
b4d89997
JF
9991/*IMP alloc_;
9992id Alloc_(id self, SEL selector) {
9993 id object = alloc_(self, selector);
c390d3ab 9994 lprintf("[%s]A-%p\n", self->isa->name, object);
b4d89997
JF
9995 return object;
9996}*/
9997
36bb2ca2
JF
9998/*IMP dealloc_;
9999id Dealloc_(id self, SEL selector) {
10000 id object = dealloc_(self, selector);
c390d3ab 10001 lprintf("[%s]D-%p\n", self->isa->name, object);
36bb2ca2
JF
10002 return object;
10003}*/
b4d89997 10004
baf82ed4 10005static NSSet *MobilizedFiles_;
10d65752 10006
baf82ed4
JF
10007static NSURL *MobilizeURL(NSURL *url) {
10008 NSString *path([url path]);
10009 if ([path hasPrefix:@"/var/root/"]) {
10010 NSString *file([path substringFromIndex:10]);
10011 if ([MobilizedFiles_ containsObject:file])
10012 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10d65752 10013 }
79b42fd1 10014
baf82ed4
JF
10015 return url;
10016}
79b42fd1 10017
baf82ed4
JF
10018Class $CFXPreferencesPropertyListSource;
10019@class CFXPreferencesPropertyListSource;
79b42fd1 10020
baf82ed4
JF
10021MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10022 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10023 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
28d9b32a 10024
baf82ed4 10025 url = MobilizeURL(url);
28d9b32a
JF
10026 BOOL value; @try {
10027 value = _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd);
10028 //NSLog(@"CFX %@ %s", [url absoluteString], value ? "YES" : "NO");
10029 } @finally {
10030 url = old;
10031 }
10032
baf82ed4
JF
10033 [pool release];
10034 return value;
10035}
79b42fd1 10036
baf82ed4
JF
10037MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10038 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10039 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
28d9b32a 10040
baf82ed4 10041 url = MobilizeURL(url);
28d9b32a
JF
10042 void *value; @try {
10043 value = _CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd);
10044 //NSLog(@"CFX %@ %@", [url absoluteString], value);
10045 } @finally {
10046 url = old;
10047 }
10048
baf82ed4
JF
10049 [pool release];
10050 return value;
79b42fd1
GP
10051}
10052
30c5be06
JF
10053Class $NSURLConnection;
10054
10055MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
0c4fe0f4 10056 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
30c5be06
JF
10057
10058 NSURL *url([copy URL]);
5e845121 10059
30c5be06 10060 NSString *host([url host]);
e4b48f2f
JF
10061 NSString *scheme([[url scheme] lowercaseString]);
10062
10063 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
30c5be06 10064
48f1762f
JF
10065 @synchronized (HostConfig_) {
10066 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10067 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10068 [copy setHTTPShouldUsePipelining:YES];
5e845121
JF
10069
10070 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10071 if ([control isEqualToString:@"max-age=0"])
3a23d36e 10072 if ([CachedURLs_ containsObject:url]) {
5e845121 10073#if !ForRelease
3a23d36e 10074 NSLog(@"~~~: %@", url);
5e845121
JF
10075#endif
10076
10077 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10078
10079 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10080 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10081 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10082 }
48f1762f 10083 }
30c5be06
JF
10084
10085 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10086 } return self;
10087}
10088
b1497b56
JF
10089Class $WAKWindow;
10090
4cc9e99a 10091static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
b1497b56
JF
10092 CGSize size([[UIScreen mainScreen] bounds].size);
10093 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10094 if ([$WAKWindow hasLandscapeOrientation])
10095 std::swap(size.width, size.height);*/
10096 return size;
438d6708
JF
10097}
10098
29cbf4e5
JF
10099Class $NSUserDefaults;
10100
10101MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10102 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10103 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10104 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10105}
10106
d13edf44
JF
10107int main(int argc, char *argv[]) {
10108 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10109
d6dad1b4 10110 _trace();
f79a4512 10111
9a60abe5
JF
10112 UpdateExternalStatus(0);
10113
57e8b225
JF
10114 UIScreen *screen([UIScreen mainScreen]);
10115 if ([screen respondsToSelector:@selector(scale)])
10116 ScreenScale_ = [screen scale];
10117 else
10118 ScreenScale_ = 1;
10119
c138614d 10120 UIDevice *device([UIDevice currentDevice]);
08157100 10121 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
c138614d 10122 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
08157100
JF
10123 if (idiom == UIUserInterfaceIdiomPad)
10124 IsWildcat_ = true;
c138614d
JF
10125 }
10126
08157100
JF
10127 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10128
9a4a4754 10129 Pcre pattern("^([0-9]+\\.[0-9]+)");
fd825a2d 10130
9a4a4754
JF
10131 if (pattern([device systemVersion]))
10132 Firmware_ = pattern[1];
fd825a2d
JF
10133 if (pattern(Cydia_))
10134 Major_ = pattern[1];
9a4a4754 10135
7b33d201 10136 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
ef974f52 10137
7b33d201 10138 HostConfig_ = [[[NSObject alloc] init] autorelease];
48f1762f
JF
10139 @synchronized (HostConfig_) {
10140 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
247bedb6 10141 TokenHosts_ = [NSMutableSet setWithCapacity:4];
2e1652a9 10142 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
48f1762f 10143 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
5e845121 10144 CachedURLs_ = [NSMutableSet setWithCapacity:32];
48f1762f 10145 }
5df7ecfb 10146
de595d91
JF
10147 NSString *ui(@"ui/ios");
10148 if (Idiom_ != nil)
10149 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
fd825a2d 10150 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
de595d91 10151 UI_ = CydiaURL(ui);
57e8b225 10152
df213583 10153 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
677b8415 10154
baf82ed4 10155 MobilizedFiles_ = [NSMutableSet setWithObjects:
89821e07 10156 @"Library/Preferences/.GlobalPreferences.plist",
baf82ed4
JF
10157 @"Library/Preferences/com.apple.Accessibility.plist",
10158 @"Library/Preferences/com.apple.preferences.sounds.plist",
10159 nil];
10160
7376b55c
JF
10161 /* Library Hacks {{{ */
10162 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10163
b1497b56
JF
10164 $WAKWindow = objc_getClass("WAKWindow");
10165 if ($WAKWindow != NULL)
438d6708
JF
10166 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10167 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10168
7d700035
JF
10169 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSourceSynchronizer");
10170 if ($CFXPreferencesPropertyListSource == Nil)
10171 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
baf82ed4
JF
10172
10173 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10174 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10175 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10176 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10177 }
10178
10179 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10180 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10181 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10182 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10183 }
10184
30c5be06
JF
10185 $NSURLConnection = objc_getClass("NSURLConnection");
10186 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10187 if (NSURLConnection$init$ != NULL) {
10188 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10189 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10190 }
29cbf4e5
JF
10191
10192 $NSUserDefaults = objc_getClass("NSUserDefaults");
10193 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10194 if (NSUserDefaults$objectForKey$ != NULL) {
10195 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10196 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10197 }
7376b55c
JF
10198 /* }}} */
10199 /* Set Locale {{{ */
f79a4512 10200 Locale_ = CFLocaleCopyCurrent();
b1ce61ec 10201 Languages_ = [NSLocale preferredLanguages];
25fdc941 10202
b1ce61ec 10203 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
18876387 10204 //NSLog(@"%@", [Languages_ description]);
78430d06 10205
b1ce61ec 10206 const char *lang;
25fdc941
JF
10207 if (Locale_ != NULL)
10208 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
3caee0a4
JF
10209 else if (Languages_ != nil && [Languages_ count] != 0)
10210 lang = [[Languages_ objectAtIndex:0] UTF8String];
10211 else
78430d06 10212 // XXX: consider just setting to C and then falling through?
b1ce61ec 10213 lang = NULL;
3caee0a4
JF
10214
10215 if (lang != NULL) {
10216 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10217 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
78430d06
JF
10218 }
10219
b1ce61ec 10220 NSLog(@"Setting Language: %s", lang);
3caee0a4
JF
10221
10222 if (lang != NULL) {
10223 setenv("LANG", lang, true);
10224 std::setlocale(LC_ALL, lang);
10225 }
7376b55c 10226 /* }}} */
aeeb755b
JF
10227 /* Index Collation {{{ */
10228 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) {
10229 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10230 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10231 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10232 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
1c28763e 10233 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
aeeb755b
JF
10234
10235 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10236
10237 CollationThumbs_ = [collation sectionIndexTitles];
10238 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10239 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10240
10241 CollationTitles_ = [collation sectionTitles];
10242 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10243
22fd24dd
JF
10244 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10245 if (&transform != NULL && transform != nil) {
10246 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10247 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10248 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10249 UErrorCode code(U_ZERO_ERROR);
10250 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10251 if (!U_SUCCESS(code))
10252 NSLog(@"%s", u_errorName(code));
10253 }
aeeb755b
JF
10254 } else {
10255 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10256
10257 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];
10258 for (NSInteger offset(0); offset != 28; ++offset)
10259 CollationOffset_.push_back(offset);
10260
10261 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];
10262 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];
10263 }
10264 /* }}} */
f79a4512 10265
d791dce4 10266 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
f79a4512 10267
7376b55c 10268 /* Parse Arguments {{{ */
de3b1ab4
JF
10269 bool substrate(false);
10270
10271 if (argc != 0) {
10272 char **args(argv);
10273 int arge(1);
10274
10275 for (int argi(1); argi != argc; ++argi)
10276 if (strcmp(argv[argi], "--") == 0) {
10277 arge = argi;
10278 argv[argi] = argv[0];
10279 argv += argi;
10280 argc -= argi;
10281 break;
10282 }
10283
10284 for (int argi(1); argi != arge; ++argi)
d791dce4 10285 if (strcmp(args[argi], "--substrate") == 0)
de3b1ab4
JF
10286 substrate = true;
10287 else
10288 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10289 }
7376b55c 10290 /* }}} */
d73cede2 10291
7376b55c 10292 App_ = [[NSBundle mainBundle] bundlePath];
d791dce4 10293 Advanced_ = YES;
7376b55c 10294
b4d89997
JF
10295 setuid(0);
10296 setgid(0);
10297
57f0b05d
JF
10298 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10299 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
dc8b6681 10300
d1c7f1fd
JF
10301 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10302
b4d89997
JF
10303 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10304 alloc_ = alloc->method_imp;
10305 alloc->method_imp = (IMP) &Alloc_;*/
10306
36bb2ca2
JF
10307 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10308 dealloc_ = dealloc->method_imp;
10309 dealloc->method_imp = (IMP) &Dealloc_;*/
10310
7c80833f
JF
10311 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10312 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10313
d791dce4 10314 /* System Information {{{ */
3178d79b 10315 size_t size;
c390d3ab
JF
10316
10317 int maxproc;
10318 size = sizeof(maxproc);
10319 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10320 perror("sysctlbyname(\"kern.maxproc\", ?)");
10321 else if (maxproc < 64) {
10322 maxproc = 64;
10323 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10324 perror("sysctlbyname(\"kern.maxproc\", #)");
10325 }
10326
bfc87a4d
JF
10327 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10328 char *osversion = new char[size];
10329 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10330 perror("sysctlbyname(\"kern.osversion\", ?)");
10331 else
10332 System_ = [NSString stringWithUTF8String:osversion];
10333
3178d79b
JF
10334 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10335 char *machine = new char[size];
c390d3ab
JF
10336 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10337 perror("sysctlbyname(\"hw.machine\", ?)");
10338 else
10339 Machine_ = machine;
3178d79b 10340
8dcc32d4 10341 int64_t usermem(0);
ce1901de
JF
10342 size = sizeof(usermem);
10343 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10344 usermem = 0;
10345
c31d7cdc
JF
10346 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10347 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10348 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
59dbe296 10349
7c80833f 10350 UniqueID_ = UniqueIdentifier(device);
3178d79b 10351
3e9c9e85
JF
10352 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10353 Product_ = [info objectForKey:@"SafariProductVersion"];
10354 Safari_ = [info objectForKey:@"CFBundleVersion"];
10355 }
e967efd5 10356
dd58e110 10357 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
e967efd5
JF
10358
10359 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10360 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10361 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10362 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10363 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10364 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10365
10366 UserAgent_ = agent;
d791dce4 10367 /* }}} */
7376b55c 10368 /* Load Database {{{ */
d6dad1b4 10369 _trace();
f79a4512
JF
10370 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10371 _trace();
10372 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
d6dad1b4
JF
10373
10374 if (Metadata_ == NULL)
f79a4512 10375 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
6d9712c4 10376 else {
2bdd73bd 10377 Settings_ = [Metadata_ objectForKey:@"Settings"];
7b0ce2da 10378
b4d89997 10379 Packages_ = [Metadata_ objectForKey:@"Packages"];
b3c8e69c
JF
10380
10381 Values_ = [Metadata_ objectForKey:@"Values"];
6d9712c4 10382 Sections_ = [Metadata_ objectForKey:@"Sections"];
7b0ce2da 10383 Sources_ = [Metadata_ objectForKey:@"Sources"];
ef055c6c
JF
10384
10385 Token_ = [Metadata_ objectForKey:@"Token"];
33e30380
JF
10386
10387 Version_ = [Metadata_ objectForKey:@"Version"];
7b0ce2da
JF
10388 }
10389
b3c8e69c
JF
10390 if (Values_ == nil) {
10391 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10392 [Metadata_ setObject:Values_ forKey:@"Values"];
10393 }
10394
7b0ce2da
JF
10395 if (Sections_ == nil) {
10396 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10397 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10398 }
10399
10400 if (Sources_ == nil) {
10401 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10402 [Metadata_ setObject:Sources_ forKey:@"Sources"];
6d9712c4 10403 }
33e30380
JF
10404
10405 if (Version_ == nil) {
10406 Version_ = [NSNumber numberWithUnsignedInt:0];
10407 [Metadata_ setObject:Version_ forKey:@"Version"];
10408 }
10409
33e30380 10410 if ([Version_ unsignedIntValue] == 0) {
25c1dafb
JF
10411 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10412 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10413 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10414 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
33e30380
JF
10415
10416 Version_ = [NSNumber numberWithUnsignedInt:1];
10417 [Metadata_ setObject:Version_ forKey:@"Version"];
10418
a26ad329
JF
10419 [Metadata_ removeObjectForKey:@"LastUpdate"];
10420
33e30380
JF
10421 Changed_ = true;
10422 }
2595e4c3
JF
10423
10424 _H<NSMutableArray> broken([NSMutableArray array]);
10425 for (NSString *key in (id) Sources_)
10426 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10427 [broken addObject:key];
10428 if ([broken count] != 0) {
10429 for (NSString *key in (id) broken)
10430 [Sources_ removeObjectForKey:key];
10431 Changed_ = true;
10432 } broken = nil;
7376b55c 10433 /* }}} */
b4d89997 10434
25c1dafb 10435 CydiaWriteSources();
33e30380 10436
94b0b3e5
JF
10437 _trace();
10438 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10439 _trace();
10440
10441 if (Packages_ != nil) {
c65611b9
JF
10442 bool fail(false);
10443 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
94b0b3e5 10444 _trace();
c65611b9
JF
10445
10446 if (!fail) {
10447 [Metadata_ removeObjectForKey:@"Packages"];
10448 Packages_ = nil;
10449 Changed_ = true;
10450 }
94b0b3e5
JF
10451 }
10452
d791dce4
JF
10453 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10454
d71f3a07 10455#define MobileSubstrate_(name) \
d13577cf
JF
10456 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10457 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10458 if (handle == NULL) \
10459 NSLog(@"%s", dlerror()); \
10460 }
d71f3a07
JF
10461
10462 MobileSubstrate_(Activator)
10463 MobileSubstrate_(libstatusbar)
10464 MobileSubstrate_(SimulatedKeyEvents)
10465 MobileSubstrate_(WinterBoard)
10466
9dd60d81
JF
10467 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10468 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
dddbc481 10469
01d93940
JF
10470 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10471
5dcff401 10472 if (access("/User", F_OK) != 0 || version != 6) {
d6dad1b4 10473 _trace();
26c2dd8c 10474 system("/usr/libexec/cydia/firmware.sh");
d6dad1b4
JF
10475 _trace();
10476 }
9e98e020 10477
87f46a96
JF
10478 _assert([[NSFileManager defaultManager]
10479 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10480 withIntermediateDirectories:YES
10481 attributes:nil
10482 error:NULL
10483 ]);
10484
7376b55c
JF
10485 if (access("/tmp/cydia.chk", F_OK) == 0) {
10486 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10487 _assert(errno == ENOENT);
10488 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10489 _assert(errno == ENOENT);
10490 }
10491
59dbe296 10492 /* APT Initialization {{{ */
b1ce61ec
JF
10493 _assert(pkgInitConfig(*_config));
10494 _assert(pkgInitSystem(*_config, _system));
10495
10496 if (lang != NULL)
10497 _config->Set("APT::Acquire::Translation", lang);
cb94ff21
JF
10498
10499 // XXX: this timeout might be important :(
10500 //_config->Set("Acquire::http::Timeout", 15);
10501
ce1901de 10502 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
59dbe296 10503 /* }}} */
7376b55c 10504 /* Color Choices {{{ */
36bb2ca2
JF
10505 space_ = CGColorSpaceCreateDeviceRGB();
10506
f641a0e5 10507 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
77fcccaf 10508 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
36bb2ca2 10509 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
86a333c6 10510 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
baf80942 10511 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
36bb2ca2 10512 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
7b0ce2da 10513 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
3bd1c2a2
JF
10514 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10515 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10516 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
59dbe296 10517
dc63e78f
JF
10518 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10519 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
7376b55c 10520 /* }}}*/
7376b55c 10521 /* UIKit Configuration {{{ */
600d005d
JF
10522 // XXX: I have a feeling this was important
10523 //UIKeyboardDisableAutomaticAppearance();
7376b55c 10524 /* }}} */
87f46a96 10525
8a3b565c
JF
10526 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10527
b37b0a4a
JF
10528 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10529 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
c73d524b
JF
10530 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10531
c73d524b 10532 PulseInterval_ = fast ? 50000 : 500000;
8731fdb0 10533
670a0494 10534 Colon_ = UCLocalize("COLON_DELIMITED");
72fb3616 10535 Elision_ = UCLocalize("ELISION");
670a0494
JF
10536 Error_ = UCLocalize("ERROR");
10537 Warning_ = UCLocalize("WARNING");
10538
d6dad1b4 10539 _trace();
77df4f82 10540 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
36bb2ca2
JF
10541
10542 CGColorSpaceRelease(space_);
199d0ba5 10543 CFRelease(Locale_);
36bb2ca2 10544
d13edf44 10545 [pool release];
36bb2ca2 10546 return value;
6d166849 10547}