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