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