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