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