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