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