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