]>
Commit | Line | Data |
---|---|---|
1 | /* Cydia - iPhone UIKit Front-End for Debian APT | |
2 | * Copyright (C) 2008-2010 Jay Freeman (saurik) | |
3 | */ | |
4 | ||
5 | /* Modified BSD License {{{ */ | |
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 | */ | |
38 | /* }}} */ | |
39 | ||
40 | // XXX: wtf/FastMalloc.h... wtf? | |
41 | #define USE_SYSTEM_MALLOC 1 | |
42 | ||
43 | /* #include Directives {{{ */ | |
44 | #include "UICaboodle/UCPlatform.h" | |
45 | #include "UICaboodle/UCLocalize.h" | |
46 | ||
47 | #include <objc/objc.h> | |
48 | #include <objc/runtime.h> | |
49 | ||
50 | #include <CoreGraphics/CoreGraphics.h> | |
51 | #include <Foundation/Foundation.h> | |
52 | ||
53 | #if 0 | |
54 | #define DEPLOYMENT_TARGET_MACOSX 1 | |
55 | #define CF_BUILDING_CF 1 | |
56 | #include <CoreFoundation/CFInternal.h> | |
57 | #endif | |
58 | ||
59 | #include <CoreFoundation/CFPriv.h> | |
60 | #include <CoreFoundation/CFUniChar.h> | |
61 | ||
62 | #include <SystemConfiguration/SystemConfiguration.h> | |
63 | ||
64 | #include <UIKit/UIKit.h> | |
65 | #include "iPhonePrivate.h" | |
66 | ||
67 | #include <IOKit/IOKitLib.h> | |
68 | ||
69 | #include <WebCore/WebCoreThread.h> | |
70 | ||
71 | #include <algorithm> | |
72 | #include <iomanip> | |
73 | #include <sstream> | |
74 | #include <string> | |
75 | ||
76 | #include <ext/stdio_filebuf.h> | |
77 | ||
78 | #undef ABS | |
79 | ||
80 | #include <apt-pkg/acquire.h> | |
81 | #include <apt-pkg/acquire-item.h> | |
82 | #include <apt-pkg/algorithms.h> | |
83 | #include <apt-pkg/cachefile.h> | |
84 | #include <apt-pkg/clean.h> | |
85 | #include <apt-pkg/configuration.h> | |
86 | #include <apt-pkg/debindexfile.h> | |
87 | #include <apt-pkg/debmetaindex.h> | |
88 | #include <apt-pkg/error.h> | |
89 | #include <apt-pkg/init.h> | |
90 | #include <apt-pkg/mmap.h> | |
91 | #include <apt-pkg/pkgrecords.h> | |
92 | #include <apt-pkg/sha1.h> | |
93 | #include <apt-pkg/sourcelist.h> | |
94 | #include <apt-pkg/sptr.h> | |
95 | #include <apt-pkg/strutl.h> | |
96 | #include <apt-pkg/tagfile.h> | |
97 | ||
98 | #include <apr-1/apr_pools.h> | |
99 | ||
100 | #include <sys/types.h> | |
101 | #include <sys/stat.h> | |
102 | #include <sys/sysctl.h> | |
103 | #include <sys/param.h> | |
104 | #include <sys/mount.h> | |
105 | ||
106 | #include <fcntl.h> | |
107 | #include <notify.h> | |
108 | #include <dlfcn.h> | |
109 | ||
110 | extern "C" { | |
111 | #include <mach-o/nlist.h> | |
112 | } | |
113 | ||
114 | #include <cstdio> | |
115 | #include <cstdlib> | |
116 | #include <cstring> | |
117 | ||
118 | #include <errno.h> | |
119 | #include <pcre.h> | |
120 | ||
121 | #include <Cytore.hpp> | |
122 | ||
123 | #include "UICaboodle/BrowserView.h" | |
124 | #include "SDURLCache/SDURLCache.h" | |
125 | ||
126 | #include "substrate.h" | |
127 | /* }}} */ | |
128 | ||
129 | /* Profiler {{{ */ | |
130 | struct timeval _ltv; | |
131 | bool _itv; | |
132 | ||
133 | #define _timestamp ({ \ | |
134 | struct timeval tv; \ | |
135 | gettimeofday(&tv, NULL); \ | |
136 | tv.tv_sec * 1000000 + tv.tv_usec; \ | |
137 | }) | |
138 | ||
139 | typedef std::vector<class ProfileTime *> TimeList; | |
140 | TimeList times_; | |
141 | ||
142 | class ProfileTime { | |
143 | private: | |
144 | const char *name_; | |
145 | uint64_t total_; | |
146 | uint64_t count_; | |
147 | ||
148 | public: | |
149 | ProfileTime(const char *name) : | |
150 | name_(name), | |
151 | total_(0) | |
152 | { | |
153 | times_.push_back(this); | |
154 | } | |
155 | ||
156 | void AddTime(uint64_t time) { | |
157 | total_ += time; | |
158 | ++count_; | |
159 | } | |
160 | ||
161 | void Print() { | |
162 | if (total_ != 0) | |
163 | std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl; | |
164 | total_ = 0; | |
165 | count_ = 0; | |
166 | } | |
167 | }; | |
168 | ||
169 | class ProfileTimer { | |
170 | private: | |
171 | ProfileTime &time_; | |
172 | uint64_t start_; | |
173 | ||
174 | public: | |
175 | ProfileTimer(ProfileTime &time) : | |
176 | time_(time), | |
177 | start_(_timestamp) | |
178 | { | |
179 | } | |
180 | ||
181 | ~ProfileTimer() { | |
182 | time_.AddTime(_timestamp - start_); | |
183 | } | |
184 | }; | |
185 | ||
186 | void PrintTimes() { | |
187 | for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i) | |
188 | (*i)->Print(); | |
189 | std::cerr << "========" << std::endl; | |
190 | } | |
191 | ||
192 | #define _profile(name) { \ | |
193 | static ProfileTime name(#name); \ | |
194 | ProfileTimer _ ## name(name); | |
195 | ||
196 | #define _end } | |
197 | /* }}} */ | |
198 | ||
199 | #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true); | |
200 | ||
201 | #define CYPoolStart() \ | |
202 | NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \ | |
203 | do | |
204 | #define CYPoolEnd() \ | |
205 | while (false); \ | |
206 | [_pool release]; | |
207 | ||
208 | // Hash Functions/Structures {{{ | |
209 | extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0); | |
210 | ||
211 | union SplitHash { | |
212 | uint32_t u32; | |
213 | uint16_t u16[2]; | |
214 | }; | |
215 | // }}} | |
216 | ||
217 | static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); | |
218 | ||
219 | void NSLogPoint(const char *fix, const CGPoint &point) { | |
220 | NSLog(@"%s(%g,%g)", fix, point.x, point.y); | |
221 | } | |
222 | ||
223 | void NSLogRect(const char *fix, const CGRect &rect) { | |
224 | NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); | |
225 | } | |
226 | ||
227 | static _finline NSString *CydiaURL(NSString *path) { | |
228 | char page[25]; | |
229 | page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':'; | |
230 | page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd'; | |
231 | page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a'; | |
232 | page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.'; | |
233 | page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0'; | |
234 | return [[NSString stringWithUTF8String:page] stringByAppendingString:path]; | |
235 | } | |
236 | ||
237 | static _finline void UpdateExternalStatus(uint64_t newStatus) { | |
238 | int notify_token; | |
239 | if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) { | |
240 | notify_set_state(notify_token, newStatus); | |
241 | notify_cancel(notify_token); | |
242 | } | |
243 | notify_post("com.saurik.Cydia.status"); | |
244 | } | |
245 | ||
246 | /* [NSObject yieldToSelector:(withObject:)] {{{*/ | |
247 | @interface NSObject (Cydia) | |
248 | - (id) yieldToSelector:(SEL)selector withObject:(id)object; | |
249 | - (id) yieldToSelector:(SEL)selector; | |
250 | @end | |
251 | ||
252 | @implementation NSObject (Cydia) | |
253 | ||
254 | - (void) doNothing { | |
255 | } | |
256 | ||
257 | - (void) _yieldToContext:(NSMutableArray *)context { _pooled | |
258 | SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue])); | |
259 | id object([[context objectAtIndex:1] nonretainedObjectValue]); | |
260 | volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue])); | |
261 | ||
262 | /* XXX: deal with exceptions */ | |
263 | id value([self performSelector:selector withObject:object]); | |
264 | ||
265 | NSMethodSignature *signature([self methodSignatureForSelector:selector]); | |
266 | [context removeAllObjects]; | |
267 | if ([signature methodReturnLength] != 0 && value != nil) | |
268 | [context addObject:value]; | |
269 | ||
270 | stopped = true; | |
271 | ||
272 | [self | |
273 | performSelectorOnMainThread:@selector(doNothing) | |
274 | withObject:nil | |
275 | waitUntilDone:NO | |
276 | ]; | |
277 | } | |
278 | ||
279 | - (id) yieldToSelector:(SEL)selector withObject:(id)object { | |
280 | volatile bool stopped(false); | |
281 | ||
282 | NSMutableArray *context([NSMutableArray arrayWithObjects: | |
283 | [NSValue valueWithPointer:selector], | |
284 | [NSValue valueWithNonretainedObject:object], | |
285 | [NSValue valueWithPointer:const_cast<bool *>(&stopped)], | |
286 | nil]); | |
287 | ||
288 | NSThread *thread([[[NSThread alloc] | |
289 | initWithTarget:self | |
290 | selector:@selector(_yieldToContext:) | |
291 | object:context | |
292 | ] autorelease]); | |
293 | ||
294 | [thread start]; | |
295 | ||
296 | NSRunLoop *loop([NSRunLoop currentRunLoop]); | |
297 | NSDate *future([NSDate distantFuture]); | |
298 | ||
299 | while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]); | |
300 | ||
301 | return [context count] == 0 ? nil : [context objectAtIndex:0]; | |
302 | } | |
303 | ||
304 | - (id) yieldToSelector:(SEL)selector { | |
305 | return [self yieldToSelector:selector withObject:nil]; | |
306 | } | |
307 | ||
308 | @end | |
309 | /* }}} */ | |
310 | ||
311 | /* Cydia Action Sheet {{{ */ | |
312 | @interface CYActionSheet : UIAlertView { | |
313 | unsigned button_; | |
314 | } | |
315 | ||
316 | - (int) yieldToPopupAlertAnimated:(BOOL)animated; | |
317 | @end | |
318 | ||
319 | @implementation CYActionSheet | |
320 | ||
321 | - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index { | |
322 | if ((self = [super init])) { | |
323 | [self setTitle:title]; | |
324 | [self setDelegate:self]; | |
325 | for (NSString *button in buttons) [self addButtonWithTitle:button]; | |
326 | [self setCancelButtonIndex:index]; | |
327 | } return self; | |
328 | } | |
329 | ||
330 | - (void) _updateFrameForDisplay { | |
331 | [super _updateFrameForDisplay]; | |
332 | if ([self cancelButtonIndex] == -1) { | |
333 | NSArray *buttons = [self buttons]; | |
334 | if ([buttons count]) { | |
335 | UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0]; | |
336 | for (UIThreePartButton *button in buttons) | |
337 | [button setBackground:background forState:0]; | |
338 | } | |
339 | } | |
340 | } | |
341 | ||
342 | - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { | |
343 | button_ = buttonIndex + 1; | |
344 | } | |
345 | ||
346 | - (void) dismiss { | |
347 | [self dismissWithClickedButtonIndex:-1 animated:YES]; | |
348 | } | |
349 | ||
350 | - (int) yieldToPopupAlertAnimated:(BOOL)animated { | |
351 | [self setRunsModal:YES]; | |
352 | button_ = 0; | |
353 | [self show]; | |
354 | return button_; | |
355 | } | |
356 | ||
357 | @end | |
358 | /* }}} */ | |
359 | ||
360 | /* NSForcedOrderingSearch doesn't work on the iPhone */ | |
361 | static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch; | |
362 | static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch; | |
363 | static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering; | |
364 | ||
365 | /* Information Dictionaries {{{ */ | |
366 | @interface NSMutableArray (Cydia) | |
367 | - (void) addInfoDictionary:(NSDictionary *)info; | |
368 | @end | |
369 | ||
370 | @implementation NSMutableArray (Cydia) | |
371 | ||
372 | - (void) addInfoDictionary:(NSDictionary *)info { | |
373 | [self addObject:info]; | |
374 | } | |
375 | ||
376 | @end | |
377 | ||
378 | @interface NSMutableDictionary (Cydia) | |
379 | - (void) addInfoDictionary:(NSDictionary *)info; | |
380 | @end | |
381 | ||
382 | @implementation NSMutableDictionary (Cydia) | |
383 | ||
384 | - (void) addInfoDictionary:(NSDictionary *)info { | |
385 | [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]]; | |
386 | } | |
387 | ||
388 | @end | |
389 | /* }}} */ | |
390 | ||
391 | #define lprintf(args...) fprintf(stderr, args) | |
392 | ||
393 | #define ForRelease 1 | |
394 | #define TraceLogging (1 && !ForRelease) | |
395 | #define HistogramInsertionSort (!ForRelease ? 0 : 0) | |
396 | #define ProfileTimes (0 && !ForRelease) | |
397 | #define ForSaurik (0 && !ForRelease) | |
398 | #define LogBrowser (0 && !ForRelease) | |
399 | #define TrackResize (0 && !ForRelease) | |
400 | #define ManualRefresh (1 && !ForRelease) | |
401 | #define ShowInternals (0 && !ForRelease) | |
402 | #define IgnoreInstall (0 && !ForRelease) | |
403 | #define AlwaysReload (0 && !ForRelease) | |
404 | ||
405 | #if !TraceLogging | |
406 | #undef _trace | |
407 | #define _trace(args...) | |
408 | #endif | |
409 | ||
410 | #if !ProfileTimes | |
411 | #undef _profile | |
412 | #define _profile(name) { | |
413 | #undef _end | |
414 | #define _end } | |
415 | #define PrintTimes() do {} while (false) | |
416 | #endif | |
417 | ||
418 | /* Radix Sort {{{ */ | |
419 | typedef uint32_t (*SKRadixFunction)(id, void *); | |
420 | ||
421 | @interface NSMutableArray (Radix) | |
422 | - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument; | |
423 | @end | |
424 | ||
425 | struct RadixItem_ { | |
426 | size_t index; | |
427 | uint32_t key; | |
428 | }; | |
429 | ||
430 | @implementation NSMutableArray (Radix) | |
431 | ||
432 | - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument { | |
433 | size_t count([self count]); | |
434 | struct RadixItem_ *swap(new RadixItem_[count * 2]); | |
435 | ||
436 | for (size_t i(0); i != count; ++i) { | |
437 | RadixItem_ &item(swap[i]); | |
438 | item.index = i; | |
439 | ||
440 | id object([self objectAtIndex:i]); | |
441 | item.key = function(object, argument); | |
442 | } | |
443 | ||
444 | struct RadixItem_ *lhs(swap), *rhs(swap + count); | |
445 | ||
446 | static const size_t width = 32; | |
447 | static const size_t bits = 11; | |
448 | static const size_t slots = 1 << bits; | |
449 | static const size_t passes = (width + (bits - 1)) / bits; | |
450 | ||
451 | size_t *hist(new size_t[slots]); | |
452 | ||
453 | for (size_t pass(0); pass != passes; ++pass) { | |
454 | memset(hist, 0, sizeof(size_t) * slots); | |
455 | ||
456 | for (size_t i(0); i != count; ++i) { | |
457 | uint32_t key(lhs[i].key); | |
458 | key >>= pass * bits; | |
459 | key &= _not(uint32_t) >> width - bits; | |
460 | ++hist[key]; | |
461 | } | |
462 | ||
463 | size_t offset(0); | |
464 | for (size_t i(0); i != slots; ++i) { | |
465 | size_t local(offset); | |
466 | offset += hist[i]; | |
467 | hist[i] = local; | |
468 | } | |
469 | ||
470 | for (size_t i(0); i != count; ++i) { | |
471 | uint32_t key(lhs[i].key); | |
472 | key >>= pass * bits; | |
473 | key &= _not(uint32_t) >> width - bits; | |
474 | rhs[hist[key]++] = lhs[i]; | |
475 | } | |
476 | ||
477 | RadixItem_ *tmp(lhs); | |
478 | lhs = rhs; | |
479 | rhs = tmp; | |
480 | } | |
481 | ||
482 | delete [] hist; | |
483 | ||
484 | const void **values(new const void *[count]); | |
485 | for (size_t i(0); i != count; ++i) | |
486 | values[i] = [self objectAtIndex:lhs[i].index]; | |
487 | CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count); | |
488 | delete [] values; | |
489 | ||
490 | delete [] swap; | |
491 | } | |
492 | ||
493 | @end | |
494 | /* }}} */ | |
495 | /* Insertion Sort {{{ */ | |
496 | ||
497 | CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) { | |
498 | const char *ptr = (const char *)list; | |
499 | while (0 < count) { | |
500 | CFIndex half = count / 2; | |
501 | const char *probe = ptr + elementSize * half; | |
502 | CFComparisonResult cr = comparator(element, probe, context); | |
503 | if (0 == cr) return (probe - (const char *)list) / elementSize; | |
504 | ptr = (cr < 0) ? ptr : probe + elementSize; | |
505 | count = (cr < 0) ? half : (half + (count & 1) - 1); | |
506 | } | |
507 | return (ptr - (const char *)list) / elementSize; | |
508 | } | |
509 | ||
510 | CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) { | |
511 | const char *ptr = (const char *)list; | |
512 | while (0 < count) { | |
513 | CFIndex half = count / 2; | |
514 | const char *probe = ptr + elementSize * half; | |
515 | CFComparisonResult cr = comparator(element, probe, context); | |
516 | if (0 == cr) return (probe - (const char *)list) / elementSize; | |
517 | ptr = (cr < 0) ? ptr : probe + elementSize; | |
518 | count = (cr < 0) ? half : (half + (count & 1) - 1); | |
519 | } | |
520 | return (ptr - (const char *)list) / elementSize; | |
521 | } | |
522 | ||
523 | void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) { | |
524 | if (range.length == 0) | |
525 | return; | |
526 | const void **values(new const void *[range.length]); | |
527 | CFArrayGetValues(array, range, values); | |
528 | ||
529 | #if HistogramInsertionSort > 0 | |
530 | uint32_t total(0), *offsets(new uint32_t[range.length]); | |
531 | #endif | |
532 | ||
533 | for (CFIndex index(1); index != range.length; ++index) { | |
534 | const void *value(values[index]); | |
535 | //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context)); | |
536 | CFIndex correct(index); | |
537 | while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) { | |
538 | #if HistogramInsertionSort > 1 | |
539 | NSLog(@"%@ < %@", value, values[correct - 1]); | |
540 | #endif | |
541 | if (--correct == 0) | |
542 | break; | |
543 | } | |
544 | if (correct != index) { | |
545 | size_t offset(index - correct); | |
546 | #if HistogramInsertionSort | |
547 | total += offset; | |
548 | ++offsets[offset]; | |
549 | if (offset > 10) | |
550 | NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value); | |
551 | #endif | |
552 | memmove(values + correct + 1, values + correct, sizeof(const void *) * offset); | |
553 | values[correct] = value; | |
554 | } | |
555 | } | |
556 | ||
557 | CFArrayReplaceValues(array, range, values, range.length); | |
558 | delete [] values; | |
559 | ||
560 | #if HistogramInsertionSort > 0 | |
561 | for (CFIndex index(0); index != range.length; ++index) | |
562 | if (offsets[index] != 0) | |
563 | NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]); | |
564 | NSLog(@"Average Insertion Displacement: %f", double(total) / range.length); | |
565 | delete [] offsets; | |
566 | #endif | |
567 | } | |
568 | ||
569 | /* }}} */ | |
570 | ||
571 | /* Apple Bug Fixes {{{ */ | |
572 | @implementation UIWebDocumentView (Cydia) | |
573 | ||
574 | - (void) _setScrollerOffset:(CGPoint)offset { | |
575 | UIScroller *scroller([self _scroller]); | |
576 | ||
577 | CGSize size([scroller contentSize]); | |
578 | CGSize bounds([scroller bounds].size); | |
579 | ||
580 | CGPoint max; | |
581 | max.x = size.width - bounds.width; | |
582 | max.y = size.height - bounds.height; | |
583 | ||
584 | // wtf Apple?! | |
585 | if (max.x < 0) | |
586 | max.x = 0; | |
587 | if (max.y < 0) | |
588 | max.y = 0; | |
589 | ||
590 | offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x; | |
591 | offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y; | |
592 | ||
593 | [scroller setOffset:offset]; | |
594 | } | |
595 | ||
596 | @end | |
597 | /* }}} */ | |
598 | ||
599 | @implementation WebScriptObject (NSFastEnumeration) | |
600 | ||
601 | - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count { | |
602 | size_t length([self count] - state->state); | |
603 | if (length <= 0) | |
604 | return 0; | |
605 | else if (length > count) | |
606 | length = count; | |
607 | for (size_t i(0); i != length; ++i) | |
608 | objects[i] = [self objectAtIndex:state->state++]; | |
609 | state->itemsPtr = objects; | |
610 | state->mutationsPtr = (unsigned long *) self; | |
611 | return length; | |
612 | } | |
613 | ||
614 | @end | |
615 | ||
616 | NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) { | |
617 | size_t length([self length] - state->state); | |
618 | if (length <= 0) | |
619 | return 0; | |
620 | else if (length > count) | |
621 | length = count; | |
622 | for (size_t i(0); i != length; ++i) | |
623 | objects[i] = [self item:state->state++]; | |
624 | state->itemsPtr = objects; | |
625 | state->mutationsPtr = (unsigned long *) self; | |
626 | return length; | |
627 | } | |
628 | ||
629 | /* Cydia NSString Additions {{{ */ | |
630 | @interface NSString (Cydia) | |
631 | + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length; | |
632 | + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool; | |
633 | + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length; | |
634 | - (NSComparisonResult) compareByPath:(NSString *)other; | |
635 | - (NSString *) stringByCachingURLWithCurrentCDN; | |
636 | - (NSString *) stringByAddingPercentEscapesIncludingReserved; | |
637 | @end | |
638 | ||
639 | @implementation NSString (Cydia) | |
640 | ||
641 | + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length { | |
642 | return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease]; | |
643 | } | |
644 | ||
645 | + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool { | |
646 | char *data(reinterpret_cast<char *>(apr_palloc(pool, length))); | |
647 | memcpy(data, bytes, length); | |
648 | return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease]; | |
649 | } | |
650 | ||
651 | + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length { | |
652 | return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease]; | |
653 | } | |
654 | ||
655 | - (NSComparisonResult) compareByPath:(NSString *)other { | |
656 | NSString *prefix = [self commonPrefixWithString:other options:0]; | |
657 | size_t length = [prefix length]; | |
658 | ||
659 | NSRange lrange = NSMakeRange(length, [self length] - length); | |
660 | NSRange rrange = NSMakeRange(length, [other length] - length); | |
661 | ||
662 | lrange = [self rangeOfString:@"/" options:0 range:lrange]; | |
663 | rrange = [other rangeOfString:@"/" options:0 range:rrange]; | |
664 | ||
665 | NSComparisonResult value; | |
666 | ||
667 | if (lrange.location == NSNotFound && rrange.location == NSNotFound) | |
668 | value = NSOrderedSame; | |
669 | else if (lrange.location == NSNotFound) | |
670 | value = NSOrderedAscending; | |
671 | else if (rrange.location == NSNotFound) | |
672 | value = NSOrderedDescending; | |
673 | else | |
674 | value = NSOrderedSame; | |
675 | ||
676 | NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] : | |
677 | [self substringWithRange:NSMakeRange(length, lrange.location - length)]; | |
678 | NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] : | |
679 | [other substringWithRange:NSMakeRange(length, rrange.location - length)]; | |
680 | ||
681 | NSComparisonResult result = [lpath compare:rpath]; | |
682 | return result == NSOrderedSame ? value : result; | |
683 | } | |
684 | ||
685 | - (NSString *) stringByCachingURLWithCurrentCDN { | |
686 | return [self | |
687 | stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/" | |
688 | withString:@"://cache.cydia.saurik.com/" | |
689 | ]; | |
690 | } | |
691 | ||
692 | - (NSString *) stringByAddingPercentEscapesIncludingReserved { | |
693 | return [(id)CFURLCreateStringByAddingPercentEscapes( | |
694 | kCFAllocatorDefault, | |
695 | (CFStringRef) self, | |
696 | NULL, | |
697 | CFSTR(";/?:@&=+$,"), | |
698 | kCFStringEncodingUTF8 | |
699 | ) autorelease]; | |
700 | } | |
701 | ||
702 | @end | |
703 | /* }}} */ | |
704 | ||
705 | /* C++ NSString Wrapper Cache {{{ */ | |
706 | static _finline CFStringRef CYStringCreate(const char *data, size_t size) { | |
707 | return size == 0 ? NULL : | |
708 | CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?: | |
709 | CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull); | |
710 | } | |
711 | ||
712 | static _finline CFStringRef CYStringCreate(const char *data) { | |
713 | return CYStringCreate(data, strlen(data)); | |
714 | } | |
715 | ||
716 | class CYString { | |
717 | private: | |
718 | char *data_; | |
719 | size_t size_; | |
720 | CFStringRef cache_; | |
721 | ||
722 | _finline void clear_() { | |
723 | if (cache_ != NULL) { | |
724 | CFRelease(cache_); | |
725 | cache_ = NULL; | |
726 | } | |
727 | } | |
728 | ||
729 | public: | |
730 | _finline bool empty() const { | |
731 | return size_ == 0; | |
732 | } | |
733 | ||
734 | _finline size_t size() const { | |
735 | return size_; | |
736 | } | |
737 | ||
738 | _finline char *data() const { | |
739 | return data_; | |
740 | } | |
741 | ||
742 | _finline void clear() { | |
743 | size_ = 0; | |
744 | clear_(); | |
745 | } | |
746 | ||
747 | _finline CYString() : | |
748 | data_(0), | |
749 | size_(0), | |
750 | cache_(NULL) | |
751 | { | |
752 | } | |
753 | ||
754 | _finline ~CYString() { | |
755 | clear_(); | |
756 | } | |
757 | ||
758 | void operator =(const CYString &rhs) { | |
759 | data_ = rhs.data_; | |
760 | size_ = rhs.size_; | |
761 | ||
762 | if (rhs.cache_ == nil) | |
763 | cache_ = NULL; | |
764 | else | |
765 | cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_)); | |
766 | } | |
767 | ||
768 | void copy(apr_pool_t *pool) { | |
769 | char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1))); | |
770 | memcpy(temp, data_, size_); | |
771 | temp[size_] = '\0'; | |
772 | data_ = temp; | |
773 | } | |
774 | ||
775 | void set(apr_pool_t *pool, const char *data, size_t size) { | |
776 | if (size == 0) | |
777 | clear(); | |
778 | else { | |
779 | clear_(); | |
780 | ||
781 | data_ = const_cast<char *>(data); | |
782 | size_ = size; | |
783 | ||
784 | if (pool != NULL) | |
785 | copy(pool); | |
786 | } | |
787 | } | |
788 | ||
789 | _finline void set(apr_pool_t *pool, const char *data) { | |
790 | set(pool, data, data == NULL ? 0 : strlen(data)); | |
791 | } | |
792 | ||
793 | _finline void set(apr_pool_t *pool, const std::string &rhs) { | |
794 | set(pool, rhs.data(), rhs.size()); | |
795 | } | |
796 | ||
797 | bool operator ==(const CYString &rhs) const { | |
798 | return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0; | |
799 | } | |
800 | ||
801 | _finline operator CFStringRef() { | |
802 | if (cache_ == NULL) | |
803 | cache_ = CYStringCreate(data_, size_); | |
804 | return cache_; | |
805 | } | |
806 | ||
807 | _finline operator id() { | |
808 | return (NSString *) static_cast<CFStringRef>(*this); | |
809 | } | |
810 | ||
811 | _finline operator const char *() { | |
812 | return reinterpret_cast<const char *>(data_); | |
813 | } | |
814 | }; | |
815 | /* }}} */ | |
816 | /* C++ NSString Algorithm Adapters {{{ */ | |
817 | extern "C" { | |
818 | CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str); | |
819 | } | |
820 | ||
821 | struct NSStringMapHash : | |
822 | std::unary_function<NSString *, size_t> | |
823 | { | |
824 | _finline size_t operator ()(NSString *value) const { | |
825 | return CFStringHashNSString((CFStringRef) value); | |
826 | } | |
827 | }; | |
828 | ||
829 | struct NSStringMapLess : | |
830 | std::binary_function<NSString *, NSString *, bool> | |
831 | { | |
832 | _finline bool operator ()(NSString *lhs, NSString *rhs) const { | |
833 | return [lhs compare:rhs] == NSOrderedAscending; | |
834 | } | |
835 | }; | |
836 | ||
837 | struct NSStringMapEqual : | |
838 | std::binary_function<NSString *, NSString *, bool> | |
839 | { | |
840 | _finline bool operator ()(NSString *lhs, NSString *rhs) const { | |
841 | return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo; | |
842 | //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs); | |
843 | //[lhs isEqualToString:rhs]; | |
844 | } | |
845 | }; | |
846 | /* }}} */ | |
847 | ||
848 | /* Perl-Compatible RegEx {{{ */ | |
849 | class Pcre { | |
850 | private: | |
851 | pcre *code_; | |
852 | pcre_extra *study_; | |
853 | int capture_; | |
854 | int *matches_; | |
855 | const char *data_; | |
856 | ||
857 | public: | |
858 | Pcre(const char *regex) : | |
859 | study_(NULL) | |
860 | { | |
861 | const char *error; | |
862 | int offset; | |
863 | code_ = pcre_compile(regex, 0, &error, &offset, NULL); | |
864 | ||
865 | if (code_ == NULL) { | |
866 | lprintf("%d:%s\n", offset, error); | |
867 | _assert(false); | |
868 | } | |
869 | ||
870 | pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_); | |
871 | matches_ = new int[(capture_ + 1) * 3]; | |
872 | } | |
873 | ||
874 | ~Pcre() { | |
875 | pcre_free(code_); | |
876 | delete matches_; | |
877 | } | |
878 | ||
879 | NSString *operator [](size_t match) { | |
880 | return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])]; | |
881 | } | |
882 | ||
883 | bool operator ()(NSString *data) { | |
884 | // XXX: length is for characters, not for bytes | |
885 | return operator ()([data UTF8String], [data length]); | |
886 | } | |
887 | ||
888 | bool operator ()(const char *data, size_t size) { | |
889 | data_ = data; | |
890 | return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0; | |
891 | } | |
892 | }; | |
893 | /* }}} */ | |
894 | /* Mime Addresses {{{ */ | |
895 | @interface Address : NSObject { | |
896 | NSString *name_; | |
897 | NSString *address_; | |
898 | } | |
899 | ||
900 | - (NSString *) name; | |
901 | - (NSString *) address; | |
902 | ||
903 | - (void) setAddress:(NSString *)address; | |
904 | ||
905 | + (Address *) addressWithString:(NSString *)string; | |
906 | - (Address *) initWithString:(NSString *)string; | |
907 | @end | |
908 | ||
909 | @implementation Address | |
910 | ||
911 | - (void) dealloc { | |
912 | [name_ release]; | |
913 | if (address_ != nil) | |
914 | [address_ release]; | |
915 | [super dealloc]; | |
916 | } | |
917 | ||
918 | - (NSString *) name { | |
919 | return name_; | |
920 | } | |
921 | ||
922 | - (NSString *) address { | |
923 | return address_; | |
924 | } | |
925 | ||
926 | - (void) setAddress:(NSString *)address { | |
927 | if (address_ != nil) | |
928 | [address_ autorelease]; | |
929 | if (address == nil) | |
930 | address_ = nil; | |
931 | else | |
932 | address_ = [address retain]; | |
933 | } | |
934 | ||
935 | + (Address *) addressWithString:(NSString *)string { | |
936 | return [[[Address alloc] initWithString:string] autorelease]; | |
937 | } | |
938 | ||
939 | + (NSArray *) _attributeKeys { | |
940 | return [NSArray arrayWithObjects:@"address", @"name", nil]; | |
941 | } | |
942 | ||
943 | - (NSArray *) attributeKeys { | |
944 | return [[self class] _attributeKeys]; | |
945 | } | |
946 | ||
947 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
948 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
949 | } | |
950 | ||
951 | - (Address *) initWithString:(NSString *)string { | |
952 | if ((self = [super init]) != nil) { | |
953 | const char *data = [string UTF8String]; | |
954 | size_t size = [string length]; | |
955 | ||
956 | static Pcre address_r("^\"?(.*)\"? <([^>]*)>$"); | |
957 | ||
958 | if (address_r(data, size)) { | |
959 | name_ = [address_r[1] retain]; | |
960 | address_ = [address_r[2] retain]; | |
961 | } else { | |
962 | name_ = [string retain]; | |
963 | address_ = nil; | |
964 | } | |
965 | } return self; | |
966 | } | |
967 | ||
968 | @end | |
969 | /* }}} */ | |
970 | /* CoreGraphics Primitives {{{ */ | |
971 | class CYColor { | |
972 | private: | |
973 | CGColorRef color_; | |
974 | ||
975 | static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) { | |
976 | CGFloat color[] = {red, green, blue, alpha}; | |
977 | return CGColorCreate(space, color); | |
978 | } | |
979 | ||
980 | public: | |
981 | CYColor() : | |
982 | color_(NULL) | |
983 | { | |
984 | } | |
985 | ||
986 | CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) : | |
987 | color_(Create_(space, red, green, blue, alpha)) | |
988 | { | |
989 | Set(space, red, green, blue, alpha); | |
990 | } | |
991 | ||
992 | void Clear() { | |
993 | if (color_ != NULL) | |
994 | CGColorRelease(color_); | |
995 | } | |
996 | ||
997 | ~CYColor() { | |
998 | Clear(); | |
999 | } | |
1000 | ||
1001 | void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) { | |
1002 | Clear(); | |
1003 | color_ = Create_(space, red, green, blue, alpha); | |
1004 | } | |
1005 | ||
1006 | operator CGColorRef() { | |
1007 | return color_; | |
1008 | } | |
1009 | }; | |
1010 | /* }}} */ | |
1011 | ||
1012 | /* Random Global Variables {{{ */ | |
1013 | static const int PulseInterval_ = 50000; | |
1014 | static const int ButtonBarWidth_ = 60; | |
1015 | static const int ButtonBarHeight_ = 48; | |
1016 | static const float KeyboardTime_ = 0.3f; | |
1017 | ||
1018 | static int Finish_; | |
1019 | static NSArray *Finishes_; | |
1020 | ||
1021 | #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist" | |
1022 | #define NotifyConfig_ "/etc/notify.conf" | |
1023 | ||
1024 | static bool Queuing_; | |
1025 | ||
1026 | static CYColor Blue_; | |
1027 | static CYColor Blueish_; | |
1028 | static CYColor Black_; | |
1029 | static CYColor Off_; | |
1030 | static CYColor White_; | |
1031 | static CYColor Gray_; | |
1032 | static CYColor Green_; | |
1033 | static CYColor Purple_; | |
1034 | static CYColor Purplish_; | |
1035 | ||
1036 | static UIColor *InstallingColor_; | |
1037 | static UIColor *RemovingColor_; | |
1038 | ||
1039 | static NSString *App_; | |
1040 | static NSString *Home_; | |
1041 | ||
1042 | static BOOL Advanced_; | |
1043 | static BOOL Ignored_; | |
1044 | ||
1045 | static UIFont *Font12_; | |
1046 | static UIFont *Font12Bold_; | |
1047 | static UIFont *Font14_; | |
1048 | static UIFont *Font18Bold_; | |
1049 | static UIFont *Font22Bold_; | |
1050 | ||
1051 | static const char *Machine_ = NULL; | |
1052 | static NSString *System_ = nil; | |
1053 | static NSString *SerialNumber_ = nil; | |
1054 | static NSString *ChipID_ = nil; | |
1055 | static NSString *Token_ = nil; | |
1056 | static NSString *UniqueID_ = nil; | |
1057 | static NSString *PLMN_ = nil; | |
1058 | static NSString *Build_ = nil; | |
1059 | static NSString *Product_ = nil; | |
1060 | static NSString *Safari_ = nil; | |
1061 | ||
1062 | static CFLocaleRef Locale_; | |
1063 | static NSArray *Languages_; | |
1064 | static CGColorSpaceRef space_; | |
1065 | ||
1066 | static NSDictionary *SectionMap_; | |
1067 | static NSMutableDictionary *Metadata_; | |
1068 | static _transient NSMutableDictionary *Settings_; | |
1069 | static _transient NSString *Role_; | |
1070 | static _transient NSMutableDictionary *Packages_; | |
1071 | static _transient NSMutableDictionary *Sections_; | |
1072 | static _transient NSMutableDictionary *Sources_; | |
1073 | static bool Changed_; | |
1074 | static time_t now_; | |
1075 | ||
1076 | static bool IsWildcat_; | |
1077 | /* }}} */ | |
1078 | ||
1079 | /* Display Helpers {{{ */ | |
1080 | inline float Interpolate(float begin, float end, float fraction) { | |
1081 | return (end - begin) * fraction + begin; | |
1082 | } | |
1083 | ||
1084 | /* XXX: localize this! */ | |
1085 | NSString *SizeString(double size) { | |
1086 | bool negative = size < 0; | |
1087 | if (negative) | |
1088 | size = -size; | |
1089 | ||
1090 | unsigned power = 0; | |
1091 | while (size > 1024) { | |
1092 | size /= 1024; | |
1093 | ++power; | |
1094 | } | |
1095 | ||
1096 | static const char *powers_[] = {"B", "kB", "MB", "GB"}; | |
1097 | ||
1098 | return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]]; | |
1099 | } | |
1100 | ||
1101 | static _finline const char *StripVersion_(const char *version) { | |
1102 | const char *colon(strchr(version, ':')); | |
1103 | return colon == NULL ? version : colon + 1; | |
1104 | } | |
1105 | ||
1106 | NSString *LocalizeSection(NSString *section) { | |
1107 | static Pcre title_r("^(.*?) \\((.*)\\)$"); | |
1108 | if (title_r(section)) { | |
1109 | NSString *parent(title_r[1]); | |
1110 | NSString *child(title_r[2]); | |
1111 | ||
1112 | return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), | |
1113 | LocalizeSection(parent), | |
1114 | LocalizeSection(child) | |
1115 | ]; | |
1116 | } | |
1117 | ||
1118 | return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"]; | |
1119 | } | |
1120 | ||
1121 | NSString *Simplify(NSString *title) { | |
1122 | const char *data = [title UTF8String]; | |
1123 | size_t size = [title length]; | |
1124 | ||
1125 | static Pcre square_r("^\\[(.*)\\]$"); | |
1126 | if (square_r(data, size)) | |
1127 | return Simplify(square_r[1]); | |
1128 | ||
1129 | static Pcre paren_r("^\\((.*)\\)$"); | |
1130 | if (paren_r(data, size)) | |
1131 | return Simplify(paren_r[1]); | |
1132 | ||
1133 | static Pcre title_r("^(.*?) \\((.*)\\)$"); | |
1134 | if (title_r(data, size)) | |
1135 | return Simplify(title_r[1]); | |
1136 | ||
1137 | return title; | |
1138 | } | |
1139 | /* }}} */ | |
1140 | ||
1141 | NSString *GetLastUpdate() { | |
1142 | NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]; | |
1143 | ||
1144 | if (update == nil) | |
1145 | return UCLocalize("NEVER_OR_UNKNOWN"); | |
1146 | ||
1147 | CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle); | |
1148 | CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update); | |
1149 | ||
1150 | CFRelease(formatter); | |
1151 | ||
1152 | return [(NSString *) formatted autorelease]; | |
1153 | } | |
1154 | ||
1155 | bool isSectionVisible(NSString *section) { | |
1156 | NSDictionary *metadata([Sections_ objectForKey:section]); | |
1157 | NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]); | |
1158 | return hidden == nil || ![hidden boolValue]; | |
1159 | } | |
1160 | ||
1161 | @class Cydia; | |
1162 | ||
1163 | /* Delegate Prototypes {{{ */ | |
1164 | @class Package; | |
1165 | @class Source; | |
1166 | ||
1167 | @interface NSObject (ProgressDelegate) | |
1168 | @end | |
1169 | ||
1170 | @protocol ProgressDelegate | |
1171 | - (void) setProgressError:(NSString *)error withTitle:(NSString *)id; | |
1172 | - (void) setProgressTitle:(NSString *)title; | |
1173 | - (void) setProgressPercent:(float)percent; | |
1174 | - (void) startProgress; | |
1175 | - (void) addProgressOutput:(NSString *)output; | |
1176 | - (bool) isCancelling:(size_t)received; | |
1177 | @end | |
1178 | ||
1179 | @protocol ConfigurationDelegate | |
1180 | - (void) repairWithSelector:(SEL)selector; | |
1181 | - (void) setConfigurationData:(NSString *)data; | |
1182 | @end | |
1183 | ||
1184 | @class PackageController; | |
1185 | ||
1186 | @protocol CydiaDelegate | |
1187 | - (void) setPackageController:(PackageController *)view; | |
1188 | - (void) clearPackage:(Package *)package; | |
1189 | - (void) installPackage:(Package *)package; | |
1190 | - (void) installPackages:(NSArray *)packages; | |
1191 | - (void) removePackage:(Package *)package; | |
1192 | - (void) beginUpdate; | |
1193 | - (BOOL) updating; | |
1194 | - (void) distUpgrade; | |
1195 | - (void) loadData; | |
1196 | - (void) updateData; | |
1197 | - (void) syncData; | |
1198 | - (void) showSettings; | |
1199 | - (UIProgressHUD *) addProgressHUD; | |
1200 | - (BOOL) hudIsShowing; | |
1201 | - (void) removeProgressHUD:(UIProgressHUD *)hud; | |
1202 | - (CYViewController *) pageForPackage:(NSString *)name; | |
1203 | - (PackageController *) packageController; | |
1204 | - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item; | |
1205 | @end | |
1206 | /* }}} */ | |
1207 | ||
1208 | /* Status Delegation {{{ */ | |
1209 | class Status : | |
1210 | public pkgAcquireStatus | |
1211 | { | |
1212 | private: | |
1213 | _transient NSObject<ProgressDelegate> *delegate_; | |
1214 | ||
1215 | public: | |
1216 | Status() : | |
1217 | delegate_(nil) | |
1218 | { | |
1219 | } | |
1220 | ||
1221 | void setDelegate(id delegate) { | |
1222 | delegate_ = delegate; | |
1223 | } | |
1224 | ||
1225 | NSObject<ProgressDelegate> *getDelegate() const { | |
1226 | return delegate_; | |
1227 | } | |
1228 | ||
1229 | virtual bool MediaChange(std::string media, std::string drive) { | |
1230 | return false; | |
1231 | } | |
1232 | ||
1233 | virtual void IMSHit(pkgAcquire::ItemDesc &item) { | |
1234 | } | |
1235 | ||
1236 | virtual void Fetch(pkgAcquire::ItemDesc &item) { | |
1237 | //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]); | |
1238 | [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]]; | |
1239 | } | |
1240 | ||
1241 | virtual void Done(pkgAcquire::ItemDesc &item) { | |
1242 | } | |
1243 | ||
1244 | virtual void Fail(pkgAcquire::ItemDesc &item) { | |
1245 | if ( | |
1246 | item.Owner->Status == pkgAcquire::Item::StatIdle || | |
1247 | item.Owner->Status == pkgAcquire::Item::StatDone | |
1248 | ) | |
1249 | return; | |
1250 | ||
1251 | std::string &error(item.Owner->ErrorText); | |
1252 | if (error.empty()) | |
1253 | return; | |
1254 | ||
1255 | NSString *description([NSString stringWithUTF8String:item.Description.c_str()]); | |
1256 | NSArray *fields([description componentsSeparatedByString:@" "]); | |
1257 | NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]); | |
1258 | ||
1259 | [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:) | |
1260 | withObject:[NSArray arrayWithObjects: | |
1261 | [NSString stringWithUTF8String:error.c_str()], | |
1262 | source, | |
1263 | nil] | |
1264 | waitUntilDone:YES | |
1265 | ]; | |
1266 | } | |
1267 | ||
1268 | virtual bool Pulse(pkgAcquire *Owner) { | |
1269 | bool value = pkgAcquireStatus::Pulse(Owner); | |
1270 | ||
1271 | float percent( | |
1272 | double(CurrentBytes + CurrentItems) / | |
1273 | double(TotalBytes + TotalItems) | |
1274 | ); | |
1275 | ||
1276 | [delegate_ setProgressPercent:percent]; | |
1277 | return [delegate_ isCancelling:CurrentBytes] ? false : value; | |
1278 | } | |
1279 | ||
1280 | virtual void Start() { | |
1281 | [delegate_ startProgress]; | |
1282 | } | |
1283 | ||
1284 | virtual void Stop() { | |
1285 | } | |
1286 | }; | |
1287 | /* }}} */ | |
1288 | /* Progress Delegation {{{ */ | |
1289 | class Progress : | |
1290 | public OpProgress | |
1291 | { | |
1292 | private: | |
1293 | _transient id<ProgressDelegate> delegate_; | |
1294 | float percent_; | |
1295 | ||
1296 | protected: | |
1297 | virtual void Update() { | |
1298 | /*if (abs(Percent - percent_) > 2) | |
1299 | //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent); | |
1300 | percent_ = Percent; | |
1301 | }*/ | |
1302 | ||
1303 | /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]]; | |
1304 | [delegate_ setProgressPercent:(Percent / 100)];*/ | |
1305 | } | |
1306 | ||
1307 | public: | |
1308 | Progress() : | |
1309 | delegate_(nil), | |
1310 | percent_(0) | |
1311 | { | |
1312 | } | |
1313 | ||
1314 | void setDelegate(id delegate) { | |
1315 | delegate_ = delegate; | |
1316 | } | |
1317 | ||
1318 | id getDelegate() const { | |
1319 | return delegate_; | |
1320 | } | |
1321 | ||
1322 | virtual void Done() { | |
1323 | //NSLog(@"DONE"); | |
1324 | //[delegate_ setProgressPercent:1]; | |
1325 | } | |
1326 | }; | |
1327 | /* }}} */ | |
1328 | ||
1329 | /* Database Interface {{{ */ | |
1330 | typedef std::map< unsigned long, _H<Source> > SourceMap; | |
1331 | ||
1332 | @interface Database : NSObject { | |
1333 | NSZone *zone_; | |
1334 | apr_pool_t *pool_; | |
1335 | ||
1336 | unsigned era_; | |
1337 | ||
1338 | pkgCacheFile cache_; | |
1339 | pkgDepCache::Policy *policy_; | |
1340 | pkgRecords *records_; | |
1341 | pkgProblemResolver *resolver_; | |
1342 | pkgAcquire *fetcher_; | |
1343 | FileFd *lock_; | |
1344 | SPtr<pkgPackageManager> manager_; | |
1345 | pkgSourceList *list_; | |
1346 | ||
1347 | SourceMap sources_; | |
1348 | CFMutableArrayRef packages_; | |
1349 | ||
1350 | _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_; | |
1351 | Status status_; | |
1352 | Progress progress_; | |
1353 | ||
1354 | int cydiafd_; | |
1355 | int statusfd_; | |
1356 | FILE *input_; | |
1357 | } | |
1358 | ||
1359 | + (Database *) sharedInstance; | |
1360 | - (unsigned) era; | |
1361 | ||
1362 | - (void) _readCydia:(NSNumber *)fd; | |
1363 | - (void) _readStatus:(NSNumber *)fd; | |
1364 | - (void) _readOutput:(NSNumber *)fd; | |
1365 | ||
1366 | - (FILE *) input; | |
1367 | ||
1368 | - (Package *) packageWithName:(NSString *)name; | |
1369 | ||
1370 | - (pkgCacheFile &) cache; | |
1371 | - (pkgDepCache::Policy *) policy; | |
1372 | - (pkgRecords *) records; | |
1373 | - (pkgProblemResolver *) resolver; | |
1374 | - (pkgAcquire &) fetcher; | |
1375 | - (pkgSourceList &) list; | |
1376 | - (NSArray *) packages; | |
1377 | - (NSArray *) sources; | |
1378 | - (void) reloadData; | |
1379 | ||
1380 | - (void) configure; | |
1381 | - (bool) prepare; | |
1382 | - (void) perform; | |
1383 | - (bool) upgrade; | |
1384 | - (void) update; | |
1385 | ||
1386 | - (void) updateWithStatus:(Status &)status; | |
1387 | ||
1388 | - (void) setDelegate:(id)delegate; | |
1389 | - (Source *) getSource:(pkgCache::PkgFileIterator)file; | |
1390 | @end | |
1391 | /* }}} */ | |
1392 | /* Delegate Helpers {{{ */ | |
1393 | @implementation NSObject (ProgressDelegate) | |
1394 | ||
1395 | - (void) _setProgressErrorPackage:(NSArray *)args { | |
1396 | [self performSelector:@selector(setProgressError:forPackage:) | |
1397 | withObject:[args objectAtIndex:0] | |
1398 | withObject:([args count] == 1 ? nil : [args objectAtIndex:1]) | |
1399 | ]; | |
1400 | } | |
1401 | ||
1402 | - (void) _setProgressErrorTitle:(NSArray *)args { | |
1403 | [self performSelector:@selector(setProgressError:withTitle:) | |
1404 | withObject:[args objectAtIndex:0] | |
1405 | withObject:([args count] == 1 ? nil : [args objectAtIndex:1]) | |
1406 | ]; | |
1407 | } | |
1408 | ||
1409 | - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title { | |
1410 | [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:) | |
1411 | withObject:[NSArray arrayWithObjects:error, title, nil] | |
1412 | waitUntilDone:YES | |
1413 | ]; | |
1414 | } | |
1415 | ||
1416 | - (void) setProgressError:(NSString *)error forPackage:(NSString *)id { | |
1417 | Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id]; | |
1418 | ||
1419 | [self performSelector:@selector(setProgressError:withTitle:) | |
1420 | withObject:error | |
1421 | withObject:(package == nil ? id : [package name]) | |
1422 | ]; | |
1423 | } | |
1424 | ||
1425 | @end | |
1426 | /* }}} */ | |
1427 | ||
1428 | // Cytore Definitions {{{ | |
1429 | struct PackageValue : | |
1430 | Cytore::Block | |
1431 | { | |
1432 | Cytore::Offset<PackageValue> next_; | |
1433 | ||
1434 | uint32_t index_ : 23; | |
1435 | uint32_t subscribed_ : 1; | |
1436 | uint32_t : 8; | |
1437 | ||
1438 | int32_t first_; | |
1439 | int32_t last_; | |
1440 | ||
1441 | uint16_t vhash_; | |
1442 | uint16_t nhash_; | |
1443 | ||
1444 | char version_[8]; | |
1445 | char name_[]; | |
1446 | }; | |
1447 | ||
1448 | struct MetaValue : | |
1449 | Cytore::Block | |
1450 | { | |
1451 | uint32_t active_; | |
1452 | Cytore::Offset<PackageValue> packages_[1 << 16]; | |
1453 | }; | |
1454 | ||
1455 | static Cytore::File<MetaValue> MetaFile_; | |
1456 | // }}} | |
1457 | // Cytore Helper Functions {{{ | |
1458 | static PackageValue *PackageFind(const char *name, size_t length) { | |
1459 | SplitHash nhash = { hashlittle(name, length) }; | |
1460 | ||
1461 | PackageValue *metadata; | |
1462 | ||
1463 | Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]); | |
1464 | offset: if (offset->IsNull()) { | |
1465 | *offset = MetaFile_.New<PackageValue>(length + 1); | |
1466 | metadata = &MetaFile_.Get(*offset); | |
1467 | ||
1468 | memcpy(metadata->name_, name, length + 1); | |
1469 | metadata->nhash_ = nhash.u16[1]; | |
1470 | } else { | |
1471 | metadata = &MetaFile_.Get(*offset); | |
1472 | ||
1473 | if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) { | |
1474 | offset = &metadata->next_; | |
1475 | goto offset; | |
1476 | } | |
1477 | } | |
1478 | ||
1479 | return metadata; | |
1480 | } | |
1481 | ||
1482 | static void PackageImport(const void *key, const void *value, void *context) { | |
1483 | char buffer[1024]; | |
1484 | if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) { | |
1485 | NSLog(@"failed to import package %@", key); | |
1486 | return; | |
1487 | } | |
1488 | ||
1489 | PackageValue *metadata(PackageFind(buffer, strlen(buffer))); | |
1490 | NSDictionary *package((NSDictionary *) value); | |
1491 | ||
1492 | if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"]) | |
1493 | if ([subscribed boolValue]) | |
1494 | metadata->subscribed_ = true; | |
1495 | ||
1496 | if (NSDate *date = [package objectForKey:@"FirstSeen"]) { | |
1497 | time_t time([date timeIntervalSince1970]); | |
1498 | if (metadata->first_ > time || metadata->first_ == 0) | |
1499 | metadata->first_ = time; | |
1500 | } | |
1501 | ||
1502 | bool versioned(false); | |
1503 | ||
1504 | if (NSDate *date = [package objectForKey:@"LastSeen"]) { | |
1505 | time_t time([date timeIntervalSince1970]); | |
1506 | if (metadata->last_ < time || metadata->last_ == 0) { | |
1507 | metadata->last_ = time; | |
1508 | versioned = true; | |
1509 | } | |
1510 | } else if (metadata->last_ == 0) { | |
1511 | metadata->last_ = metadata->first_; | |
1512 | if (metadata->version_[0] == '\0') | |
1513 | versioned = true; | |
1514 | } | |
1515 | ||
1516 | if (versioned) | |
1517 | if (NSString *version = [package objectForKey:@"LastVersion"]) | |
1518 | if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) { | |
1519 | size_t length(strlen(buffer)); | |
1520 | uint16_t vhash(hashlittle(buffer, length)); | |
1521 | ||
1522 | size_t capped(std::min<size_t>(8, length)); | |
1523 | char *latest(buffer + length - capped); | |
1524 | ||
1525 | strncpy(metadata->version_, latest, sizeof(metadata->version_)); | |
1526 | metadata->vhash_ = vhash; | |
1527 | } | |
1528 | } | |
1529 | // }}} | |
1530 | ||
1531 | /* Source Class {{{ */ | |
1532 | @interface Source : NSObject { | |
1533 | CYString depiction_; | |
1534 | CYString description_; | |
1535 | CYString label_; | |
1536 | CYString origin_; | |
1537 | CYString support_; | |
1538 | ||
1539 | CYString uri_; | |
1540 | CYString distribution_; | |
1541 | CYString type_; | |
1542 | CYString version_; | |
1543 | ||
1544 | NSString *host_; | |
1545 | NSString *authority_; | |
1546 | ||
1547 | CYString defaultIcon_; | |
1548 | ||
1549 | NSDictionary *record_; | |
1550 | BOOL trusted_; | |
1551 | } | |
1552 | ||
1553 | - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool; | |
1554 | ||
1555 | - (NSComparisonResult) compareByNameAndType:(Source *)source; | |
1556 | ||
1557 | - (NSString *) depictionForPackage:(NSString *)package; | |
1558 | - (NSString *) supportForPackage:(NSString *)package; | |
1559 | ||
1560 | - (NSDictionary *) record; | |
1561 | - (BOOL) trusted; | |
1562 | ||
1563 | - (NSString *) uri; | |
1564 | - (NSString *) distribution; | |
1565 | - (NSString *) type; | |
1566 | - (NSString *) key; | |
1567 | - (NSString *) host; | |
1568 | ||
1569 | - (NSString *) name; | |
1570 | - (NSString *) description; | |
1571 | - (NSString *) label; | |
1572 | - (NSString *) origin; | |
1573 | - (NSString *) version; | |
1574 | ||
1575 | - (NSString *) defaultIcon; | |
1576 | ||
1577 | @end | |
1578 | ||
1579 | @implementation Source | |
1580 | ||
1581 | - (void) _clear { | |
1582 | uri_.clear(); | |
1583 | distribution_.clear(); | |
1584 | type_.clear(); | |
1585 | ||
1586 | description_.clear(); | |
1587 | label_.clear(); | |
1588 | origin_.clear(); | |
1589 | depiction_.clear(); | |
1590 | support_.clear(); | |
1591 | version_.clear(); | |
1592 | defaultIcon_.clear(); | |
1593 | ||
1594 | if (record_ != nil) { | |
1595 | [record_ release]; | |
1596 | record_ = nil; | |
1597 | } | |
1598 | ||
1599 | if (host_ != nil) { | |
1600 | [host_ release]; | |
1601 | host_ = nil; | |
1602 | } | |
1603 | ||
1604 | if (authority_ != nil) { | |
1605 | [authority_ release]; | |
1606 | authority_ = nil; | |
1607 | } | |
1608 | } | |
1609 | ||
1610 | - (void) dealloc { | |
1611 | // XXX: this is a very inefficient way to call these deconstructors | |
1612 | [self _clear]; | |
1613 | [super dealloc]; | |
1614 | } | |
1615 | ||
1616 | + (NSArray *) _attributeKeys { | |
1617 | return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil]; | |
1618 | } | |
1619 | ||
1620 | - (NSArray *) attributeKeys { | |
1621 | return [[self class] _attributeKeys]; | |
1622 | } | |
1623 | ||
1624 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
1625 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
1626 | } | |
1627 | ||
1628 | - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool { | |
1629 | [self _clear]; | |
1630 | ||
1631 | trusted_ = index->IsTrusted(); | |
1632 | ||
1633 | uri_.set(pool, index->GetURI()); | |
1634 | distribution_.set(pool, index->GetDist()); | |
1635 | type_.set(pool, index->GetType()); | |
1636 | ||
1637 | debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index)); | |
1638 | if (dindex != NULL) { | |
1639 | FileFd fd; | |
1640 | if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) | |
1641 | _error->Discard(); | |
1642 | else { | |
1643 | pkgTagFile tags(&fd); | |
1644 | ||
1645 | pkgTagSection section; | |
1646 | tags.Step(section); | |
1647 | ||
1648 | struct { | |
1649 | const char *name_; | |
1650 | CYString *value_; | |
1651 | } names[] = { | |
1652 | {"default-icon", &defaultIcon_}, | |
1653 | {"depiction", &depiction_}, | |
1654 | {"description", &description_}, | |
1655 | {"label", &label_}, | |
1656 | {"origin", &origin_}, | |
1657 | {"support", &support_}, | |
1658 | {"version", &version_}, | |
1659 | }; | |
1660 | ||
1661 | for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) { | |
1662 | const char *start, *end; | |
1663 | ||
1664 | if (section.Find(names[i].name_, start, end)) { | |
1665 | CYString &value(*names[i].value_); | |
1666 | value.set(pool, start, end - start); | |
1667 | } | |
1668 | } | |
1669 | } | |
1670 | } | |
1671 | ||
1672 | record_ = [Sources_ objectForKey:[self key]]; | |
1673 | if (record_ != nil) | |
1674 | record_ = [record_ retain]; | |
1675 | ||
1676 | NSURL *url([NSURL URLWithString:uri_]); | |
1677 | ||
1678 | host_ = [url host]; | |
1679 | if (host_ != nil) | |
1680 | host_ = [[host_ lowercaseString] retain]; | |
1681 | ||
1682 | if (host_ != nil) | |
1683 | authority_ = host_; | |
1684 | else | |
1685 | authority_ = [url path]; | |
1686 | ||
1687 | if (authority_ != nil) | |
1688 | authority_ = [authority_ retain]; | |
1689 | } | |
1690 | ||
1691 | - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool { | |
1692 | if ((self = [super init]) != nil) { | |
1693 | [self setMetaIndex:index inPool:pool]; | |
1694 | } return self; | |
1695 | } | |
1696 | ||
1697 | - (NSComparisonResult) compareByNameAndType:(Source *)source { | |
1698 | NSDictionary *lhr = [self record]; | |
1699 | NSDictionary *rhr = [source record]; | |
1700 | ||
1701 | if (lhr != rhr) | |
1702 | return lhr == nil ? NSOrderedDescending : NSOrderedAscending; | |
1703 | ||
1704 | NSString *lhs = [self name]; | |
1705 | NSString *rhs = [source name]; | |
1706 | ||
1707 | if ([lhs length] != 0 && [rhs length] != 0) { | |
1708 | unichar lhc = [lhs characterAtIndex:0]; | |
1709 | unichar rhc = [rhs characterAtIndex:0]; | |
1710 | ||
1711 | if (isalpha(lhc) && !isalpha(rhc)) | |
1712 | return NSOrderedAscending; | |
1713 | else if (!isalpha(lhc) && isalpha(rhc)) | |
1714 | return NSOrderedDescending; | |
1715 | } | |
1716 | ||
1717 | return [lhs compare:rhs options:LaxCompareOptions_]; | |
1718 | } | |
1719 | ||
1720 | - (NSString *) depictionForPackage:(NSString *)package { | |
1721 | return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package]; | |
1722 | } | |
1723 | ||
1724 | - (NSString *) supportForPackage:(NSString *)package { | |
1725 | return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package]; | |
1726 | } | |
1727 | ||
1728 | - (NSDictionary *) record { | |
1729 | return record_; | |
1730 | } | |
1731 | ||
1732 | - (BOOL) trusted { | |
1733 | return trusted_; | |
1734 | } | |
1735 | ||
1736 | - (NSString *) uri { | |
1737 | return uri_; | |
1738 | } | |
1739 | ||
1740 | - (NSString *) distribution { | |
1741 | return distribution_; | |
1742 | } | |
1743 | ||
1744 | - (NSString *) type { | |
1745 | return type_; | |
1746 | } | |
1747 | ||
1748 | - (NSString *) key { | |
1749 | return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_]; | |
1750 | } | |
1751 | ||
1752 | - (NSString *) host { | |
1753 | return host_; | |
1754 | } | |
1755 | ||
1756 | - (NSString *) name { | |
1757 | return origin_.empty() ? authority_ : origin_; | |
1758 | } | |
1759 | ||
1760 | - (NSString *) description { | |
1761 | return description_; | |
1762 | } | |
1763 | ||
1764 | - (NSString *) label { | |
1765 | return label_.empty() ? authority_ : label_; | |
1766 | } | |
1767 | ||
1768 | - (NSString *) origin { | |
1769 | return origin_; | |
1770 | } | |
1771 | ||
1772 | - (NSString *) version { | |
1773 | return version_; | |
1774 | } | |
1775 | ||
1776 | - (NSString *) defaultIcon { | |
1777 | return defaultIcon_; | |
1778 | } | |
1779 | ||
1780 | @end | |
1781 | /* }}} */ | |
1782 | /* Relationship Class {{{ */ | |
1783 | @interface Relationship : NSObject { | |
1784 | NSString *type_; | |
1785 | NSString *id_; | |
1786 | } | |
1787 | ||
1788 | - (NSString *) type; | |
1789 | - (NSString *) id; | |
1790 | - (NSString *) name; | |
1791 | ||
1792 | @end | |
1793 | ||
1794 | @implementation Relationship | |
1795 | ||
1796 | - (void) dealloc { | |
1797 | [type_ release]; | |
1798 | [id_ release]; | |
1799 | [super dealloc]; | |
1800 | } | |
1801 | ||
1802 | - (NSString *) type { | |
1803 | return type_; | |
1804 | } | |
1805 | ||
1806 | - (NSString *) id { | |
1807 | return id_; | |
1808 | } | |
1809 | ||
1810 | - (NSString *) name { | |
1811 | _assert(false); | |
1812 | return nil; | |
1813 | } | |
1814 | ||
1815 | @end | |
1816 | /* }}} */ | |
1817 | /* Package Class {{{ */ | |
1818 | struct ParsedPackage { | |
1819 | CYString tagline_; | |
1820 | ||
1821 | CYString icon_; | |
1822 | ||
1823 | CYString depiction_; | |
1824 | CYString homepage_; | |
1825 | ||
1826 | CYString sponsor_; | |
1827 | CYString author_; | |
1828 | ||
1829 | CYString bugs_; | |
1830 | CYString support_; | |
1831 | }; | |
1832 | ||
1833 | @interface Package : NSObject { | |
1834 | uint32_t era_ : 29; | |
1835 | uint32_t essential_ : 1; | |
1836 | uint32_t obsolete_ : 1; | |
1837 | uint32_t ignored_ : 1; | |
1838 | ||
1839 | apr_pool_t *pool_; | |
1840 | ||
1841 | _transient Database *database_; | |
1842 | ||
1843 | pkgCache::VerIterator version_; | |
1844 | pkgCache::PkgIterator iterator_; | |
1845 | pkgCache::VerFileIterator file_; | |
1846 | ||
1847 | CYString id_; | |
1848 | CYString name_; | |
1849 | ||
1850 | CYString latest_; | |
1851 | CYString installed_; | |
1852 | ||
1853 | CYString section_; | |
1854 | _transient NSString *section$_; | |
1855 | ||
1856 | Source *source_; | |
1857 | ||
1858 | PackageValue *metadata_; | |
1859 | ParsedPackage *parsed_; | |
1860 | ||
1861 | NSMutableArray *tags_; | |
1862 | NSString *role_; | |
1863 | } | |
1864 | ||
1865 | - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database; | |
1866 | + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database; | |
1867 | ||
1868 | - (pkgCache::PkgIterator) iterator; | |
1869 | - (void) parse; | |
1870 | ||
1871 | - (NSString *) section; | |
1872 | - (NSString *) simpleSection; | |
1873 | ||
1874 | - (NSString *) longSection; | |
1875 | - (NSString *) shortSection; | |
1876 | ||
1877 | - (NSString *) uri; | |
1878 | ||
1879 | - (Address *) maintainer; | |
1880 | - (size_t) size; | |
1881 | - (NSString *) longDescription; | |
1882 | - (NSString *) shortDescription; | |
1883 | - (unichar) index; | |
1884 | ||
1885 | - (PackageValue *) metadata; | |
1886 | - (time_t) seen; | |
1887 | ||
1888 | - (bool) subscribed; | |
1889 | - (bool) setSubscribed:(bool)subscribed; | |
1890 | ||
1891 | - (BOOL) ignored; | |
1892 | ||
1893 | - (NSString *) latest; | |
1894 | - (NSString *) installed; | |
1895 | - (BOOL) uninstalled; | |
1896 | ||
1897 | - (BOOL) valid; | |
1898 | - (BOOL) upgradableAndEssential:(BOOL)essential; | |
1899 | - (BOOL) essential; | |
1900 | - (BOOL) broken; | |
1901 | - (BOOL) unfiltered; | |
1902 | - (BOOL) visible; | |
1903 | ||
1904 | - (BOOL) half; | |
1905 | - (BOOL) halfConfigured; | |
1906 | - (BOOL) halfInstalled; | |
1907 | - (BOOL) hasMode; | |
1908 | - (NSString *) mode; | |
1909 | ||
1910 | - (NSString *) id; | |
1911 | - (NSString *) name; | |
1912 | - (UIImage *) icon; | |
1913 | - (NSString *) homepage; | |
1914 | - (NSString *) depiction; | |
1915 | - (Address *) author; | |
1916 | ||
1917 | - (NSString *) support; | |
1918 | ||
1919 | - (NSArray *) files; | |
1920 | - (NSArray *) warnings; | |
1921 | - (NSArray *) applications; | |
1922 | ||
1923 | - (Source *) source; | |
1924 | - (NSString *) role; | |
1925 | ||
1926 | - (BOOL) matches:(NSString *)text; | |
1927 | ||
1928 | - (bool) hasSupportingRole; | |
1929 | - (BOOL) hasTag:(NSString *)tag; | |
1930 | - (NSString *) primaryPurpose; | |
1931 | - (NSArray *) purposes; | |
1932 | - (bool) isCommercial; | |
1933 | ||
1934 | - (void) setIndex:(size_t)index; | |
1935 | ||
1936 | - (CYString &) cyname; | |
1937 | ||
1938 | - (uint32_t) compareBySection:(NSArray *)sections; | |
1939 | ||
1940 | - (void) install; | |
1941 | - (void) remove; | |
1942 | ||
1943 | - (bool) isUnfilteredAndSearchedForBy:(NSString *)search; | |
1944 | - (bool) isUnfilteredAndSelectedForBy:(NSString *)search; | |
1945 | - (bool) isInstalledAndUnfiltered:(NSNumber *)number; | |
1946 | - (bool) isVisibleInSection:(NSString *)section; | |
1947 | - (bool) isVisibleInSource:(Source *)source; | |
1948 | ||
1949 | @end | |
1950 | ||
1951 | uint32_t PackageChangesRadix(Package *self, void *) { | |
1952 | union { | |
1953 | uint32_t key; | |
1954 | ||
1955 | struct { | |
1956 | uint32_t timestamp : 30; | |
1957 | uint32_t ignored : 1; | |
1958 | uint32_t upgradable : 1; | |
1959 | } bits; | |
1960 | } value; | |
1961 | ||
1962 | bool upgradable([self upgradableAndEssential:YES]); | |
1963 | value.bits.upgradable = upgradable ? 1 : 0; | |
1964 | ||
1965 | if (upgradable) { | |
1966 | value.bits.timestamp = 0; | |
1967 | value.bits.ignored = [self ignored] ? 0 : 1; | |
1968 | value.bits.upgradable = 1; | |
1969 | } else { | |
1970 | value.bits.timestamp = [self seen] >> 2; | |
1971 | value.bits.ignored = 0; | |
1972 | value.bits.upgradable = 0; | |
1973 | } | |
1974 | ||
1975 | return _not(uint32_t) - value.key; | |
1976 | } | |
1977 | ||
1978 | uint32_t PackagePrefixRadix(Package *self, void *context) { | |
1979 | size_t offset(reinterpret_cast<size_t>(context)); | |
1980 | CYString &name([self cyname]); | |
1981 | ||
1982 | size_t size(name.size()); | |
1983 | if (size == 0) | |
1984 | return 0; | |
1985 | char *text(name.data()); | |
1986 | ||
1987 | size_t zeros; | |
1988 | if (!isdigit(text[0])) | |
1989 | zeros = 0; | |
1990 | else { | |
1991 | size_t digits(1); | |
1992 | while (size != digits && isdigit(text[digits])) | |
1993 | if (++digits == 4) | |
1994 | break; | |
1995 | zeros = 4 - digits; | |
1996 | } | |
1997 | ||
1998 | uint8_t data[4]; | |
1999 | ||
2000 | if (offset == 0 && zeros != 0) { | |
2001 | memset(data, '0', zeros); | |
2002 | memcpy(data + zeros, text, 4 - zeros); | |
2003 | } else { | |
2004 | /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */ | |
2005 | if (size <= offset - zeros) | |
2006 | return 0; | |
2007 | ||
2008 | text += offset - zeros; | |
2009 | size -= offset - zeros; | |
2010 | ||
2011 | if (size >= 4) | |
2012 | memcpy(data, text, 4); | |
2013 | else { | |
2014 | memcpy(data, text, size); | |
2015 | memset(data + size, 0, 4 - size); | |
2016 | } | |
2017 | ||
2018 | for (size_t i(0); i != 4; ++i) | |
2019 | if (isalpha(data[i])) | |
2020 | data[i] |= 0x20; | |
2021 | } | |
2022 | ||
2023 | if (offset == 0) | |
2024 | if (data[0] == '@') | |
2025 | data[0] = 0x7f; | |
2026 | else | |
2027 | data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6]; | |
2028 | ||
2029 | /* XXX: ntohl may be more honest */ | |
2030 | return OSSwapInt32(*reinterpret_cast<uint32_t *>(data)); | |
2031 | } | |
2032 | ||
2033 | CYString &(*PackageName)(Package *self, SEL sel); | |
2034 | ||
2035 | CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) { | |
2036 | _profile(PackageNameCompare) | |
2037 | CYString &lhi(PackageName(lhs, @selector(cyname))); | |
2038 | CYString &rhi(PackageName(rhs, @selector(cyname))); | |
2039 | CFStringRef lhn(lhi), rhn(rhi); | |
2040 | ||
2041 | if (lhn == NULL) | |
2042 | return rhn == NULL ? NSOrderedSame : NSOrderedAscending; | |
2043 | else if (rhn == NULL) | |
2044 | return NSOrderedDescending; | |
2045 | ||
2046 | _profile(PackageNameCompare$NumbersLast) | |
2047 | if (!lhi.empty() && !rhi.empty()) { | |
2048 | UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0)); | |
2049 | UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0)); | |
2050 | bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet)); | |
2051 | if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet)) | |
2052 | return lha ? NSOrderedAscending : NSOrderedDescending; | |
2053 | } | |
2054 | _end | |
2055 | ||
2056 | CFIndex length = CFStringGetLength(lhn); | |
2057 | ||
2058 | _profile(PackageNameCompare$Compare) | |
2059 | return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_); | |
2060 | _end | |
2061 | _end | |
2062 | } | |
2063 | ||
2064 | CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) { | |
2065 | return PackageNameCompare(*lhs, *rhs, context); | |
2066 | } | |
2067 | ||
2068 | struct PackageNameOrdering : | |
2069 | std::binary_function<Package *, Package *, bool> | |
2070 | { | |
2071 | _finline bool operator ()(Package *lhs, Package *rhs) const { | |
2072 | return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending; | |
2073 | } | |
2074 | }; | |
2075 | ||
2076 | @implementation Package | |
2077 | ||
2078 | - (NSString *) description { | |
2079 | return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)]; | |
2080 | } | |
2081 | ||
2082 | - (void) dealloc { | |
2083 | if (parsed_ != NULL) | |
2084 | delete parsed_; | |
2085 | ||
2086 | if (source_ != nil) | |
2087 | [source_ release]; | |
2088 | ||
2089 | if (tags_ != nil) | |
2090 | [tags_ release]; | |
2091 | if (role_ != nil) | |
2092 | [role_ release]; | |
2093 | ||
2094 | [super dealloc]; | |
2095 | } | |
2096 | ||
2097 | + (NSString *) webScriptNameForSelector:(SEL)selector { | |
2098 | if (selector == @selector(hasTag:)) | |
2099 | return @"hasTag"; | |
2100 | else | |
2101 | return nil; | |
2102 | } | |
2103 | ||
2104 | + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector { | |
2105 | return [self webScriptNameForSelector:selector] == nil; | |
2106 | } | |
2107 | ||
2108 | + (NSArray *) _attributeKeys { | |
2109 | return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil]; | |
2110 | } | |
2111 | ||
2112 | - (NSArray *) attributeKeys { | |
2113 | return [[self class] _attributeKeys]; | |
2114 | } | |
2115 | ||
2116 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
2117 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
2118 | } | |
2119 | ||
2120 | - (void) parse { | |
2121 | if (parsed_ != NULL) | |
2122 | return; | |
2123 | @synchronized (database_) { | |
2124 | if ([database_ era] != era_ || file_.end()) | |
2125 | return; | |
2126 | ||
2127 | ParsedPackage *parsed(new ParsedPackage); | |
2128 | parsed_ = parsed; | |
2129 | ||
2130 | _profile(Package$parse) | |
2131 | pkgRecords::Parser *parser; | |
2132 | ||
2133 | _profile(Package$parse$Lookup) | |
2134 | parser = &[database_ records]->Lookup(file_); | |
2135 | _end | |
2136 | ||
2137 | CYString website; | |
2138 | ||
2139 | _profile(Package$parse$Find) | |
2140 | struct { | |
2141 | const char *name_; | |
2142 | CYString *value_; | |
2143 | } names[] = { | |
2144 | {"icon", &parsed->icon_}, | |
2145 | {"depiction", &parsed->depiction_}, | |
2146 | {"homepage", &parsed->homepage_}, | |
2147 | {"website", &website}, | |
2148 | {"bugs", &parsed->bugs_}, | |
2149 | {"support", &parsed->support_}, | |
2150 | {"sponsor", &parsed->sponsor_}, | |
2151 | {"author", &parsed->author_}, | |
2152 | }; | |
2153 | ||
2154 | for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) { | |
2155 | const char *start, *end; | |
2156 | ||
2157 | if (parser->Find(names[i].name_, start, end)) { | |
2158 | CYString &value(*names[i].value_); | |
2159 | _profile(Package$parse$Value) | |
2160 | value.set(pool_, start, end - start); | |
2161 | _end | |
2162 | } | |
2163 | } | |
2164 | _end | |
2165 | ||
2166 | _profile(Package$parse$Tagline) | |
2167 | const char *start, *end; | |
2168 | if (parser->ShortDesc(start, end)) { | |
2169 | const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start))); | |
2170 | if (stop == NULL) | |
2171 | stop = end; | |
2172 | while (stop != start && stop[-1] == '\r') | |
2173 | --stop; | |
2174 | parsed->tagline_.set(pool_, start, stop - start); | |
2175 | } | |
2176 | _end | |
2177 | ||
2178 | _profile(Package$parse$Retain) | |
2179 | if (parsed->homepage_.empty()) | |
2180 | parsed->homepage_ = website; | |
2181 | if (parsed->homepage_ == parsed->depiction_) | |
2182 | parsed->homepage_.clear(); | |
2183 | _end | |
2184 | _end | |
2185 | } } | |
2186 | ||
2187 | - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database { | |
2188 | if ((self = [super init]) != nil) { | |
2189 | _profile(Package$initWithVersion) | |
2190 | pool_ = pool; | |
2191 | ||
2192 | database_ = database; | |
2193 | era_ = [database era]; | |
2194 | ||
2195 | version_ = version; | |
2196 | ||
2197 | pkgCache::PkgIterator iterator(version.ParentPkg()); | |
2198 | iterator_ = iterator; | |
2199 | ||
2200 | _profile(Package$initWithVersion$Version) | |
2201 | if (!version_.end()) | |
2202 | file_ = version_.FileList(); | |
2203 | else { | |
2204 | pkgCache &cache([database_ cache]); | |
2205 | file_ = pkgCache::VerFileIterator(cache, cache.VerFileP); | |
2206 | } | |
2207 | _end | |
2208 | ||
2209 | _profile(Package$initWithVersion$Cache) | |
2210 | name_.set(NULL, iterator.Display()); | |
2211 | ||
2212 | latest_.set(NULL, StripVersion_(version_.VerStr())); | |
2213 | ||
2214 | pkgCache::VerIterator current(iterator.CurrentVer()); | |
2215 | if (!current.end()) | |
2216 | installed_.set(NULL, StripVersion_(current.VerStr())); | |
2217 | _end | |
2218 | ||
2219 | _profile(Package$initWithVersion$Tags) | |
2220 | pkgCache::TagIterator tag(iterator.TagList()); | |
2221 | if (!tag.end()) { | |
2222 | tags_ = [[NSMutableArray alloc] initWithCapacity:8]; | |
2223 | do { | |
2224 | const char *name(tag.Name()); | |
2225 | [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]]; | |
2226 | ||
2227 | if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) | |
2228 | role_ = (NSString *) CYStringCreate(name + 6); | |
2229 | ||
2230 | if (strncmp(name, "cydia::", 7) == 0) { | |
2231 | if (strcmp(name + 7, "essential") == 0) | |
2232 | essential_ = true; | |
2233 | else if (strcmp(name + 7, "obsolete") == 0) | |
2234 | obsolete_ = true; | |
2235 | } | |
2236 | ||
2237 | ++tag; | |
2238 | } while (!tag.end()); | |
2239 | } | |
2240 | _end | |
2241 | ||
2242 | _profile(Package$initWithVersion$Metadata) | |
2243 | const char *mixed(iterator.Name()); | |
2244 | size_t size(strlen(mixed)); | |
2245 | char lower[size + 1]; | |
2246 | ||
2247 | for (size_t i(0); i != size; ++i) | |
2248 | lower[i] = mixed[i] | 0x20; | |
2249 | lower[size] = '\0'; | |
2250 | ||
2251 | PackageValue *metadata(PackageFind(lower, size)); | |
2252 | metadata_ = metadata; | |
2253 | ||
2254 | id_.set(NULL, metadata->name_, size); | |
2255 | ||
2256 | const char *latest(version_.VerStr()); | |
2257 | size_t length(strlen(latest)); | |
2258 | ||
2259 | uint16_t vhash(hashlittle(latest, length)); | |
2260 | ||
2261 | size_t capped(std::min<size_t>(8, length)); | |
2262 | latest = latest + length - capped; | |
2263 | ||
2264 | if (metadata->first_ == 0) | |
2265 | metadata->first_ = now_; | |
2266 | ||
2267 | if (metadata->last_ == 0) | |
2268 | metadata->last_ = metadata->first_; | |
2269 | ||
2270 | if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) { | |
2271 | if (metadata->version_[0] != '\0') | |
2272 | metadata->last_ = now_; | |
2273 | strncpy(metadata->version_, latest, sizeof(metadata->version_)); | |
2274 | metadata->vhash_ = vhash; | |
2275 | } | |
2276 | _end | |
2277 | ||
2278 | _profile(Package$initWithVersion$Section) | |
2279 | section_.set(NULL, iterator.Section()); | |
2280 | _end | |
2281 | ||
2282 | _profile(Package$initWithVersion$Flags) | |
2283 | essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES); | |
2284 | ignored_ = iterator->SelectedState == pkgCache::State::Hold; | |
2285 | _end | |
2286 | _end } return self; | |
2287 | } | |
2288 | ||
2289 | + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database { | |
2290 | pkgCache::VerIterator version; | |
2291 | ||
2292 | _profile(Package$packageWithIterator$GetCandidateVer) | |
2293 | version = [database policy]->GetCandidateVer(iterator); | |
2294 | _end | |
2295 | ||
2296 | if (version.end()) | |
2297 | return nil; | |
2298 | ||
2299 | Package *package; | |
2300 | ||
2301 | _profile(Package$packageWithIterator$Allocate) | |
2302 | package = [Package allocWithZone:zone]; | |
2303 | _end | |
2304 | ||
2305 | _profile(Package$packageWithIterator$Initialize) | |
2306 | package = [package | |
2307 | initWithVersion:version | |
2308 | withZone:zone | |
2309 | inPool:pool | |
2310 | database:database | |
2311 | ]; | |
2312 | _end | |
2313 | ||
2314 | _profile(Package$packageWithIterator$Autorelease) | |
2315 | package = [package autorelease]; | |
2316 | _end | |
2317 | ||
2318 | return package; | |
2319 | } | |
2320 | ||
2321 | - (pkgCache::PkgIterator) iterator { | |
2322 | return iterator_; | |
2323 | } | |
2324 | ||
2325 | - (NSString *) section { | |
2326 | if (section$_ == nil) { | |
2327 | if (section_.empty()) | |
2328 | return nil; | |
2329 | ||
2330 | _profile(Package$section) | |
2331 | std::replace(section_.data(), section_.data() + section_.size(), '_', ' '); | |
2332 | NSString *name(section_); | |
2333 | section$_ = [SectionMap_ objectForKey:name] ?: name; | |
2334 | _end | |
2335 | } return section$_; | |
2336 | } | |
2337 | ||
2338 | - (NSString *) simpleSection { | |
2339 | if (NSString *section = [self section]) | |
2340 | return Simplify(section); | |
2341 | else | |
2342 | return nil; | |
2343 | } | |
2344 | ||
2345 | - (NSString *) longSection { | |
2346 | return LocalizeSection([self section]); | |
2347 | } | |
2348 | ||
2349 | - (NSString *) shortSection { | |
2350 | return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"]; | |
2351 | } | |
2352 | ||
2353 | - (NSString *) uri { | |
2354 | return nil; | |
2355 | #if 0 | |
2356 | pkgIndexFile *index; | |
2357 | pkgCache::PkgFileIterator file(file_.File()); | |
2358 | if (![database_ list].FindIndex(file, index)) | |
2359 | return nil; | |
2360 | return [NSString stringWithUTF8String:iterator_->Path]; | |
2361 | //return [NSString stringWithUTF8String:file.Site()]; | |
2362 | //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()]; | |
2363 | #endif | |
2364 | } | |
2365 | ||
2366 | - (Address *) maintainer { | |
2367 | @synchronized (database_) { | |
2368 | if ([database_ era] != era_ || file_.end()) | |
2369 | return nil; | |
2370 | ||
2371 | pkgRecords::Parser *parser = &[database_ records]->Lookup(file_); | |
2372 | const std::string &maintainer(parser->Maintainer()); | |
2373 | return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]]; | |
2374 | } } | |
2375 | ||
2376 | - (size_t) size { | |
2377 | @synchronized (database_) { | |
2378 | if ([database_ era] != era_ || version_.end()) | |
2379 | return 0; | |
2380 | ||
2381 | return version_->InstalledSize; | |
2382 | } } | |
2383 | ||
2384 | - (NSString *) longDescription { | |
2385 | @synchronized (database_) { | |
2386 | if ([database_ era] != era_ || file_.end()) | |
2387 | return nil; | |
2388 | ||
2389 | pkgRecords::Parser *parser = &[database_ records]->Lookup(file_); | |
2390 | NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]); | |
2391 | ||
2392 | NSArray *lines = [description componentsSeparatedByString:@"\n"]; | |
2393 | NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)]; | |
2394 | if ([lines count] < 2) | |
2395 | return nil; | |
2396 | ||
2397 | NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet]; | |
2398 | for (size_t i(1), e([lines count]); i != e; ++i) { | |
2399 | NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace]; | |
2400 | [trimmed addObject:trim]; | |
2401 | } | |
2402 | ||
2403 | return [trimmed componentsJoinedByString:@"\n"]; | |
2404 | } } | |
2405 | ||
2406 | - (NSString *) shortDescription { | |
2407 | return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_); | |
2408 | } | |
2409 | ||
2410 | - (unichar) index { | |
2411 | _profile(Package$index) | |
2412 | CFStringRef name((CFStringRef) [self name]); | |
2413 | if (CFStringGetLength(name) == 0) | |
2414 | return '#'; | |
2415 | UniChar character(CFStringGetCharacterAtIndex(name, 0)); | |
2416 | if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet)) | |
2417 | return '#'; | |
2418 | return toupper(character); | |
2419 | _end | |
2420 | } | |
2421 | ||
2422 | - (PackageValue *) metadata { | |
2423 | return metadata_; | |
2424 | } | |
2425 | ||
2426 | - (time_t) seen { | |
2427 | PackageValue *metadata([self metadata]); | |
2428 | return metadata->subscribed_ ? metadata->last_ : metadata->first_; | |
2429 | } | |
2430 | ||
2431 | - (bool) subscribed { | |
2432 | return [self metadata]->subscribed_; | |
2433 | } | |
2434 | ||
2435 | - (bool) setSubscribed:(bool)subscribed { | |
2436 | PackageValue *metadata([self metadata]); | |
2437 | if (metadata->subscribed_ == subscribed) | |
2438 | return false; | |
2439 | metadata->subscribed_ = subscribed; | |
2440 | return true; | |
2441 | } | |
2442 | ||
2443 | - (BOOL) ignored { | |
2444 | return ignored_; | |
2445 | } | |
2446 | ||
2447 | - (NSString *) latest { | |
2448 | return latest_; | |
2449 | } | |
2450 | ||
2451 | - (NSString *) installed { | |
2452 | return installed_; | |
2453 | } | |
2454 | ||
2455 | - (BOOL) uninstalled { | |
2456 | return installed_.empty(); | |
2457 | } | |
2458 | ||
2459 | - (BOOL) valid { | |
2460 | return !version_.end(); | |
2461 | } | |
2462 | ||
2463 | - (BOOL) upgradableAndEssential:(BOOL)essential { | |
2464 | _profile(Package$upgradableAndEssential) | |
2465 | pkgCache::VerIterator current(iterator_.CurrentVer()); | |
2466 | if (current.end()) | |
2467 | return essential && essential_; | |
2468 | else | |
2469 | return !version_.end() && version_ != current; | |
2470 | _end | |
2471 | } | |
2472 | ||
2473 | - (BOOL) essential { | |
2474 | return essential_; | |
2475 | } | |
2476 | ||
2477 | - (BOOL) broken { | |
2478 | return [database_ cache][iterator_].InstBroken(); | |
2479 | } | |
2480 | ||
2481 | - (BOOL) unfiltered { | |
2482 | _profile(Package$unfiltered$obsolete) | |
2483 | if (obsolete_) | |
2484 | return false; | |
2485 | _end | |
2486 | ||
2487 | _profile(Package$unfiltered$hasSupportingRole) | |
2488 | if (![self hasSupportingRole]) | |
2489 | return false; | |
2490 | _end | |
2491 | ||
2492 | return true; | |
2493 | } | |
2494 | ||
2495 | - (BOOL) visible { | |
2496 | if (![self unfiltered]) | |
2497 | return false; | |
2498 | ||
2499 | NSString *section([self section]); | |
2500 | ||
2501 | _profile(Package$visible$isSectionVisible) | |
2502 | if (section != nil && !isSectionVisible(section)) | |
2503 | return false; | |
2504 | _end | |
2505 | ||
2506 | return true; | |
2507 | } | |
2508 | ||
2509 | - (BOOL) half { | |
2510 | unsigned char current(iterator_->CurrentState); | |
2511 | return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled; | |
2512 | } | |
2513 | ||
2514 | - (BOOL) halfConfigured { | |
2515 | return iterator_->CurrentState == pkgCache::State::HalfConfigured; | |
2516 | } | |
2517 | ||
2518 | - (BOOL) halfInstalled { | |
2519 | return iterator_->CurrentState == pkgCache::State::HalfInstalled; | |
2520 | } | |
2521 | ||
2522 | - (BOOL) hasMode { | |
2523 | pkgDepCache::StateCache &state([database_ cache][iterator_]); | |
2524 | return state.Mode != pkgDepCache::ModeKeep; | |
2525 | } | |
2526 | ||
2527 | - (NSString *) mode { | |
2528 | pkgDepCache::StateCache &state([database_ cache][iterator_]); | |
2529 | ||
2530 | switch (state.Mode) { | |
2531 | case pkgDepCache::ModeDelete: | |
2532 | if ((state.iFlags & pkgDepCache::Purge) != 0) | |
2533 | return @"PURGE"; | |
2534 | else | |
2535 | return @"REMOVE"; | |
2536 | case pkgDepCache::ModeKeep: | |
2537 | if ((state.iFlags & pkgDepCache::ReInstall) != 0) | |
2538 | return @"REINSTALL"; | |
2539 | /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0) | |
2540 | return nil;*/ | |
2541 | else | |
2542 | return nil; | |
2543 | case pkgDepCache::ModeInstall: | |
2544 | /*if ((state.iFlags & pkgDepCache::ReInstall) != 0) | |
2545 | return @"REINSTALL"; | |
2546 | else*/ switch (state.Status) { | |
2547 | case -1: | |
2548 | return @"DOWNGRADE"; | |
2549 | case 0: | |
2550 | return @"INSTALL"; | |
2551 | case 1: | |
2552 | return @"UPGRADE"; | |
2553 | case 2: | |
2554 | return @"NEW_INSTALL"; | |
2555 | _nodefault | |
2556 | } | |
2557 | _nodefault | |
2558 | } | |
2559 | } | |
2560 | ||
2561 | - (NSString *) id { | |
2562 | return id_; | |
2563 | } | |
2564 | ||
2565 | - (NSString *) name { | |
2566 | return name_.empty() ? id_ : name_; | |
2567 | } | |
2568 | ||
2569 | - (UIImage *) icon { | |
2570 | NSString *section = [self simpleSection]; | |
2571 | ||
2572 | UIImage *icon(nil); | |
2573 | if (parsed_ != NULL) | |
2574 | if (NSString *href = parsed_->icon_) | |
2575 | if ([href hasPrefix:@"file:///"]) | |
2576 | // XXX: correct escaping | |
2577 | icon = [UIImage imageAtPath:[href substringFromIndex:7]]; | |
2578 | if (icon == nil) if (section != nil) | |
2579 | icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]; | |
2580 | if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon]) | |
2581 | if ([dicon hasPrefix:@"file:///"]) | |
2582 | // XXX: correct escaping | |
2583 | icon = [UIImage imageAtPath:[dicon substringFromIndex:7]]; | |
2584 | if (icon == nil) | |
2585 | icon = [UIImage applicationImageNamed:@"unknown.png"]; | |
2586 | return icon; | |
2587 | } | |
2588 | ||
2589 | - (NSString *) homepage { | |
2590 | return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_); | |
2591 | } | |
2592 | ||
2593 | - (NSString *) depiction { | |
2594 | return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_]; | |
2595 | } | |
2596 | ||
2597 | - (Address *) sponsor { | |
2598 | return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_]; | |
2599 | } | |
2600 | ||
2601 | - (Address *) author { | |
2602 | return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_]; | |
2603 | } | |
2604 | ||
2605 | - (NSString *) support { | |
2606 | return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_]; | |
2607 | } | |
2608 | ||
2609 | - (NSArray *) files { | |
2610 | NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)]; | |
2611 | NSMutableArray *files = [NSMutableArray arrayWithCapacity:128]; | |
2612 | ||
2613 | std::ifstream fin; | |
2614 | fin.open([path UTF8String]); | |
2615 | if (!fin.is_open()) | |
2616 | return nil; | |
2617 | ||
2618 | std::string line; | |
2619 | while (std::getline(fin, line)) | |
2620 | [files addObject:[NSString stringWithUTF8String:line.c_str()]]; | |
2621 | ||
2622 | return files; | |
2623 | } | |
2624 | ||
2625 | - (NSArray *) warnings { | |
2626 | NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]); | |
2627 | const char *name(iterator_.Name()); | |
2628 | ||
2629 | size_t length(strlen(name)); | |
2630 | if (length < 2) invalid: | |
2631 | [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")]; | |
2632 | else for (size_t i(0); i != length; ++i) | |
2633 | if ( | |
2634 | /* XXX: technically this is not allowed */ | |
2635 | (name[i] < 'A' || name[i] > 'Z') && | |
2636 | (name[i] < 'a' || name[i] > 'z') && | |
2637 | (name[i] < '0' || name[i] > '9') && | |
2638 | (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.') | |
2639 | ) goto invalid; | |
2640 | ||
2641 | if (strcmp(name, "cydia") != 0) { | |
2642 | bool cydia = false; | |
2643 | bool user = false; | |
2644 | bool _private = false; | |
2645 | bool stash = false; | |
2646 | ||
2647 | bool repository = [[self section] isEqualToString:@"Repositories"]; | |
2648 | ||
2649 | if (NSArray *files = [self files]) | |
2650 | for (NSString *file in files) | |
2651 | if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"]) | |
2652 | cydia = true; | |
2653 | else if (!user && [file isEqualToString:@"/User"]) | |
2654 | user = true; | |
2655 | else if (!_private && [file isEqualToString:@"/private"]) | |
2656 | _private = true; | |
2657 | else if (!stash && [file isEqualToString:@"/var/stash"]) | |
2658 | stash = true; | |
2659 | ||
2660 | /* XXX: this is not sensitive enough. only some folders are valid. */ | |
2661 | if (cydia && !repository) | |
2662 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]]; | |
2663 | if (user) | |
2664 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]]; | |
2665 | if (_private) | |
2666 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]]; | |
2667 | if (stash) | |
2668 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]]; | |
2669 | } | |
2670 | ||
2671 | return [warnings count] == 0 ? nil : warnings; | |
2672 | } | |
2673 | ||
2674 | - (NSArray *) applications { | |
2675 | NSString *me([[NSBundle mainBundle] bundleIdentifier]); | |
2676 | ||
2677 | NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]); | |
2678 | ||
2679 | static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$"); | |
2680 | if (NSArray *files = [self files]) | |
2681 | for (NSString *file in files) | |
2682 | if (application_r(file)) { | |
2683 | NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]); | |
2684 | NSString *id([info objectForKey:@"CFBundleIdentifier"]); | |
2685 | if ([id isEqualToString:me]) | |
2686 | continue; | |
2687 | ||
2688 | NSString *display([info objectForKey:@"CFBundleDisplayName"]); | |
2689 | if (display == nil) | |
2690 | display = application_r[1]; | |
2691 | ||
2692 | NSString *bundle([file stringByDeletingLastPathComponent]); | |
2693 | NSString *icon([info objectForKey:@"CFBundleIconFile"]); | |
2694 | if (icon == nil || [icon length] == 0) | |
2695 | icon = @"icon.png"; | |
2696 | NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]); | |
2697 | ||
2698 | NSMutableArray *application([NSMutableArray arrayWithCapacity:2]); | |
2699 | [applications addObject:application]; | |
2700 | ||
2701 | [application addObject:id]; | |
2702 | [application addObject:display]; | |
2703 | [application addObject:url]; | |
2704 | } | |
2705 | ||
2706 | return [applications count] == 0 ? nil : applications; | |
2707 | } | |
2708 | ||
2709 | - (Source *) source { | |
2710 | if (source_ == nil) { | |
2711 | @synchronized (database_) { | |
2712 | if ([database_ era] != era_ || file_.end()) | |
2713 | source_ = (Source *) [NSNull null]; | |
2714 | else | |
2715 | source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain]; | |
2716 | } | |
2717 | } | |
2718 | ||
2719 | return source_ == (Source *) [NSNull null] ? nil : source_; | |
2720 | } | |
2721 | ||
2722 | - (NSString *) role { | |
2723 | return role_; | |
2724 | } | |
2725 | ||
2726 | - (BOOL) matches:(NSString *)text { | |
2727 | if (text == nil) | |
2728 | return NO; | |
2729 | ||
2730 | NSRange range; | |
2731 | ||
2732 | range = [[self id] rangeOfString:text options:MatchCompareOptions_]; | |
2733 | if (range.location != NSNotFound) | |
2734 | return YES; | |
2735 | ||
2736 | range = [[self name] rangeOfString:text options:MatchCompareOptions_]; | |
2737 | if (range.location != NSNotFound) | |
2738 | return YES; | |
2739 | ||
2740 | range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_]; | |
2741 | if (range.location != NSNotFound) | |
2742 | return YES; | |
2743 | ||
2744 | return NO; | |
2745 | } | |
2746 | ||
2747 | - (bool) hasSupportingRole { | |
2748 | if (role_ == nil) | |
2749 | return true; | |
2750 | if ([role_ isEqualToString:@"enduser"]) | |
2751 | return true; | |
2752 | if ([Role_ isEqualToString:@"User"]) | |
2753 | return false; | |
2754 | if ([role_ isEqualToString:@"hacker"]) | |
2755 | return true; | |
2756 | if ([Role_ isEqualToString:@"Hacker"]) | |
2757 | return false; | |
2758 | if ([role_ isEqualToString:@"developer"]) | |
2759 | return true; | |
2760 | if ([Role_ isEqualToString:@"Developer"]) | |
2761 | return false; | |
2762 | _assert(false); | |
2763 | } | |
2764 | ||
2765 | - (BOOL) hasTag:(NSString *)tag { | |
2766 | return tags_ == nil ? NO : [tags_ containsObject:tag]; | |
2767 | } | |
2768 | ||
2769 | - (NSString *) primaryPurpose { | |
2770 | for (NSString *tag in tags_) | |
2771 | if ([tag hasPrefix:@"purpose::"]) | |
2772 | return [tag substringFromIndex:9]; | |
2773 | return nil; | |
2774 | } | |
2775 | ||
2776 | - (NSArray *) purposes { | |
2777 | NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]); | |
2778 | for (NSString *tag in tags_) | |
2779 | if ([tag hasPrefix:@"purpose::"]) | |
2780 | [purposes addObject:[tag substringFromIndex:9]]; | |
2781 | return [purposes count] == 0 ? nil : purposes; | |
2782 | } | |
2783 | ||
2784 | - (bool) isCommercial { | |
2785 | return [self hasTag:@"cydia::commercial"]; | |
2786 | } | |
2787 | ||
2788 | - (void) setIndex:(size_t)index { | |
2789 | if (metadata_->index_ != index) | |
2790 | metadata_->index_ = index; | |
2791 | } | |
2792 | ||
2793 | - (CYString &) cyname { | |
2794 | return name_.empty() ? id_ : name_; | |
2795 | } | |
2796 | ||
2797 | - (uint32_t) compareBySection:(NSArray *)sections { | |
2798 | NSString *section([self section]); | |
2799 | for (size_t i(0), e([sections count]); i != e; ++i) { | |
2800 | if ([section isEqualToString:[[sections objectAtIndex:i] name]]) | |
2801 | return i; | |
2802 | } | |
2803 | ||
2804 | return _not(uint32_t); | |
2805 | } | |
2806 | ||
2807 | - (void) clear { | |
2808 | @synchronized (database_) { | |
2809 | pkgProblemResolver *resolver = [database_ resolver]; | |
2810 | resolver->Clear(iterator_); | |
2811 | ||
2812 | pkgCacheFile &cache([database_ cache]); | |
2813 | cache->SetReInstall(iterator_, false); | |
2814 | cache->MarkKeep(iterator_, false); | |
2815 | } } | |
2816 | ||
2817 | - (void) install { | |
2818 | @synchronized (database_) { | |
2819 | pkgProblemResolver *resolver = [database_ resolver]; | |
2820 | resolver->Clear(iterator_); | |
2821 | resolver->Protect(iterator_); | |
2822 | ||
2823 | pkgCacheFile &cache([database_ cache]); | |
2824 | cache->SetReInstall(iterator_, false); | |
2825 | cache->MarkInstall(iterator_, false); | |
2826 | ||
2827 | pkgDepCache::StateCache &state((*cache)[iterator_]); | |
2828 | if (!state.Install()) | |
2829 | cache->SetReInstall(iterator_, true); | |
2830 | } } | |
2831 | ||
2832 | - (void) remove { | |
2833 | @synchronized (database_) { | |
2834 | pkgProblemResolver *resolver = [database_ resolver]; | |
2835 | resolver->Clear(iterator_); | |
2836 | resolver->Remove(iterator_); | |
2837 | resolver->Protect(iterator_); | |
2838 | ||
2839 | pkgCacheFile &cache([database_ cache]); | |
2840 | cache->SetReInstall(iterator_, false); | |
2841 | cache->MarkDelete(iterator_, true); | |
2842 | } } | |
2843 | ||
2844 | - (bool) isUnfilteredAndSearchedForBy:(NSString *)search { | |
2845 | _profile(Package$isUnfilteredAndSearchedForBy) | |
2846 | bool value(true); | |
2847 | ||
2848 | _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered) | |
2849 | value &= [self unfiltered]; | |
2850 | _end | |
2851 | ||
2852 | _profile(Package$isUnfilteredAndSearchedForBy$Match) | |
2853 | value &= [self matches:search]; | |
2854 | _end | |
2855 | ||
2856 | return value; | |
2857 | _end | |
2858 | } | |
2859 | ||
2860 | - (bool) isUnfilteredAndSelectedForBy:(NSString *)search { | |
2861 | if ([search length] == 0) | |
2862 | return false; | |
2863 | ||
2864 | _profile(Package$isUnfilteredAndSelectedForBy) | |
2865 | bool value(true); | |
2866 | ||
2867 | _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered) | |
2868 | value &= [self unfiltered]; | |
2869 | _end | |
2870 | ||
2871 | _profile(Package$isUnfilteredAndSelectedForBy$Match) | |
2872 | value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame; | |
2873 | _end | |
2874 | ||
2875 | return value; | |
2876 | _end | |
2877 | } | |
2878 | ||
2879 | - (bool) isInstalledAndUnfiltered:(NSNumber *)number { | |
2880 | return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]); | |
2881 | } | |
2882 | ||
2883 | - (bool) isVisibleInSection:(NSString *)name { | |
2884 | NSString *section([self section]); | |
2885 | ||
2886 | return ( | |
2887 | name == nil || | |
2888 | section == nil && [name length] == 0 || | |
2889 | [name isEqualToString:section] | |
2890 | ) && [self visible]; | |
2891 | } | |
2892 | ||
2893 | - (bool) isVisibleInSource:(Source *)source { | |
2894 | return [self source] == source && [self visible]; | |
2895 | } | |
2896 | ||
2897 | @end | |
2898 | /* }}} */ | |
2899 | /* Section Class {{{ */ | |
2900 | @interface Section : NSObject { | |
2901 | NSString *name_; | |
2902 | unichar index_; | |
2903 | size_t row_; | |
2904 | size_t count_; | |
2905 | NSString *localized_; | |
2906 | } | |
2907 | ||
2908 | - (NSComparisonResult) compareByLocalized:(Section *)section; | |
2909 | - (Section *) initWithName:(NSString *)name localized:(NSString *)localized; | |
2910 | - (Section *) initWithName:(NSString *)name localize:(BOOL)localize; | |
2911 | - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize; | |
2912 | - (Section *) initWithIndex:(unichar)index row:(size_t)row; | |
2913 | - (NSString *) name; | |
2914 | - (unichar) index; | |
2915 | ||
2916 | - (size_t) row; | |
2917 | - (size_t) count; | |
2918 | ||
2919 | - (void) addToRow; | |
2920 | - (void) addToCount; | |
2921 | ||
2922 | - (void) setCount:(size_t)count; | |
2923 | - (NSString *) localized; | |
2924 | ||
2925 | @end | |
2926 | ||
2927 | @implementation Section | |
2928 | ||
2929 | - (void) dealloc { | |
2930 | [name_ release]; | |
2931 | if (localized_ != nil) | |
2932 | [localized_ release]; | |
2933 | [super dealloc]; | |
2934 | } | |
2935 | ||
2936 | - (NSComparisonResult) compareByLocalized:(Section *)section { | |
2937 | NSString *lhs(localized_); | |
2938 | NSString *rhs([section localized]); | |
2939 | ||
2940 | /*if ([lhs length] != 0 && [rhs length] != 0) { | |
2941 | unichar lhc = [lhs characterAtIndex:0]; | |
2942 | unichar rhc = [rhs characterAtIndex:0]; | |
2943 | ||
2944 | if (isalpha(lhc) && !isalpha(rhc)) | |
2945 | return NSOrderedAscending; | |
2946 | else if (!isalpha(lhc) && isalpha(rhc)) | |
2947 | return NSOrderedDescending; | |
2948 | }*/ | |
2949 | ||
2950 | return [lhs compare:rhs options:LaxCompareOptions_]; | |
2951 | } | |
2952 | ||
2953 | - (Section *) initWithName:(NSString *)name localized:(NSString *)localized { | |
2954 | if ((self = [self initWithName:name localize:NO]) != nil) { | |
2955 | if (localized != nil) | |
2956 | localized_ = [localized retain]; | |
2957 | } return self; | |
2958 | } | |
2959 | ||
2960 | - (Section *) initWithName:(NSString *)name localize:(BOOL)localize { | |
2961 | return [self initWithName:name row:0 localize:localize]; | |
2962 | } | |
2963 | ||
2964 | - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize { | |
2965 | if ((self = [super init]) != nil) { | |
2966 | name_ = [name retain]; | |
2967 | index_ = '\0'; | |
2968 | row_ = row; | |
2969 | if (localize) | |
2970 | localized_ = [LocalizeSection(name_) retain]; | |
2971 | } return self; | |
2972 | } | |
2973 | ||
2974 | /* XXX: localize the index thingees */ | |
2975 | - (Section *) initWithIndex:(unichar)index row:(size_t)row { | |
2976 | if ((self = [super init]) != nil) { | |
2977 | name_ = [[NSString stringWithCharacters:&index length:1] retain]; | |
2978 | index_ = index; | |
2979 | row_ = row; | |
2980 | } return self; | |
2981 | } | |
2982 | ||
2983 | - (NSString *) name { | |
2984 | return name_; | |
2985 | } | |
2986 | ||
2987 | - (unichar) index { | |
2988 | return index_; | |
2989 | } | |
2990 | ||
2991 | - (size_t) row { | |
2992 | return row_; | |
2993 | } | |
2994 | ||
2995 | - (size_t) count { | |
2996 | return count_; | |
2997 | } | |
2998 | ||
2999 | - (void) addToRow { | |
3000 | ++row_; | |
3001 | } | |
3002 | ||
3003 | - (void) addToCount { | |
3004 | ++count_; | |
3005 | } | |
3006 | ||
3007 | - (void) setCount:(size_t)count { | |
3008 | count_ = count; | |
3009 | } | |
3010 | ||
3011 | - (NSString *) localized { | |
3012 | return localized_; | |
3013 | } | |
3014 | ||
3015 | @end | |
3016 | /* }}} */ | |
3017 | ||
3018 | static NSString *Colon_; | |
3019 | static NSString *Elision_; | |
3020 | static NSString *Error_; | |
3021 | static NSString *Warning_; | |
3022 | ||
3023 | /* Database Implementation {{{ */ | |
3024 | @implementation Database | |
3025 | ||
3026 | + (Database *) sharedInstance { | |
3027 | static Database *instance; | |
3028 | if (instance == nil) | |
3029 | instance = [[Database alloc] init]; | |
3030 | return instance; | |
3031 | } | |
3032 | ||
3033 | - (unsigned) era { | |
3034 | return era_; | |
3035 | } | |
3036 | ||
3037 | - (void) releasePackages { | |
3038 | CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL); | |
3039 | CFArrayRemoveAllValues(packages_); | |
3040 | } | |
3041 | ||
3042 | - (void) dealloc { | |
3043 | // XXX: actually implement this thing | |
3044 | _assert(false); | |
3045 | [self releasePackages]; | |
3046 | apr_pool_destroy(pool_); | |
3047 | NSRecycleZone(zone_); | |
3048 | [super dealloc]; | |
3049 | } | |
3050 | ||
3051 | - (void) _readCydia:(NSNumber *)fd { _pooled | |
3052 | __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in); | |
3053 | std::istream is(&ib); | |
3054 | std::string line; | |
3055 | ||
3056 | static Pcre finish_r("^finish:([^:]*)$"); | |
3057 | ||
3058 | while (std::getline(is, line)) { | |
3059 | const char *data(line.c_str()); | |
3060 | size_t size = line.size(); | |
3061 | lprintf("C:%s\n", data); | |
3062 | ||
3063 | if (finish_r(data, size)) { | |
3064 | NSString *finish = finish_r[1]; | |
3065 | int index = [Finishes_ indexOfObject:finish]; | |
3066 | if (index != INT_MAX && index > Finish_) | |
3067 | Finish_ = index; | |
3068 | } | |
3069 | } | |
3070 | ||
3071 | _assume(false); | |
3072 | } | |
3073 | ||
3074 | - (void) _readStatus:(NSNumber *)fd { _pooled | |
3075 | __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in); | |
3076 | std::istream is(&ib); | |
3077 | std::string line; | |
3078 | ||
3079 | static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$"); | |
3080 | static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$"); | |
3081 | ||
3082 | while (std::getline(is, line)) { | |
3083 | const char *data(line.c_str()); | |
3084 | size_t size(line.size()); | |
3085 | lprintf("S:%s\n", data); | |
3086 | ||
3087 | if (conffile_r(data, size)) { | |
3088 | [delegate_ setConfigurationData:conffile_r[1]]; | |
3089 | } else if (strncmp(data, "status: ", 8) == 0) { | |
3090 | NSString *string = [NSString stringWithUTF8String:(data + 8)]; | |
3091 | [delegate_ setProgressTitle:string]; | |
3092 | } else if (pmstatus_r(data, size)) { | |
3093 | std::string type([pmstatus_r[1] UTF8String]); | |
3094 | NSString *id = pmstatus_r[2]; | |
3095 | ||
3096 | float percent([pmstatus_r[3] floatValue]); | |
3097 | [delegate_ setProgressPercent:(percent / 100)]; | |
3098 | ||
3099 | NSString *string = pmstatus_r[4]; | |
3100 | ||
3101 | if (type == "pmerror") | |
3102 | [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:) | |
3103 | withObject:[NSArray arrayWithObjects:string, id, nil] | |
3104 | waitUntilDone:YES | |
3105 | ]; | |
3106 | else if (type == "pmstatus") { | |
3107 | [delegate_ setProgressTitle:string]; | |
3108 | } else if (type == "pmconffile") | |
3109 | [delegate_ setConfigurationData:string]; | |
3110 | else | |
3111 | lprintf("E:unknown pmstatus\n"); | |
3112 | } else | |
3113 | lprintf("E:unknown status\n"); | |
3114 | } | |
3115 | ||
3116 | _assume(false); | |
3117 | } | |
3118 | ||
3119 | - (void) _readOutput:(NSNumber *)fd { _pooled | |
3120 | __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in); | |
3121 | std::istream is(&ib); | |
3122 | std::string line; | |
3123 | ||
3124 | while (std::getline(is, line)) { | |
3125 | lprintf("O:%s\n", line.c_str()); | |
3126 | [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]]; | |
3127 | } | |
3128 | ||
3129 | _assume(false); | |
3130 | } | |
3131 | ||
3132 | - (FILE *) input { | |
3133 | return input_; | |
3134 | } | |
3135 | ||
3136 | - (Package *) packageWithName:(NSString *)name { | |
3137 | @synchronized (self) { | |
3138 | if (static_cast<pkgDepCache *>(cache_) == NULL) | |
3139 | return nil; | |
3140 | pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String])); | |
3141 | return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self]; | |
3142 | } } | |
3143 | ||
3144 | - (id) init { | |
3145 | if ((self = [super init]) != nil) { | |
3146 | policy_ = NULL; | |
3147 | records_ = NULL; | |
3148 | resolver_ = NULL; | |
3149 | fetcher_ = NULL; | |
3150 | lock_ = NULL; | |
3151 | ||
3152 | zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO); | |
3153 | apr_pool_create(&pool_, NULL); | |
3154 | ||
3155 | size_t capacity(MetaFile_->active_); | |
3156 | if (capacity == 0) | |
3157 | capacity = 16384; | |
3158 | else | |
3159 | capacity += 1024; | |
3160 | ||
3161 | packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL); | |
3162 | ||
3163 | int fds[2]; | |
3164 | ||
3165 | _assert(pipe(fds) != -1); | |
3166 | cydiafd_ = fds[1]; | |
3167 | ||
3168 | _config->Set("APT::Keep-Fds::", cydiafd_); | |
3169 | setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int)); | |
3170 | ||
3171 | [NSThread | |
3172 | detachNewThreadSelector:@selector(_readCydia:) | |
3173 | toTarget:self | |
3174 | withObject:[NSNumber numberWithInt:fds[0]] | |
3175 | ]; | |
3176 | ||
3177 | _assert(pipe(fds) != -1); | |
3178 | statusfd_ = fds[1]; | |
3179 | ||
3180 | [NSThread | |
3181 | detachNewThreadSelector:@selector(_readStatus:) | |
3182 | toTarget:self | |
3183 | withObject:[NSNumber numberWithInt:fds[0]] | |
3184 | ]; | |
3185 | ||
3186 | _assert(pipe(fds) != -1); | |
3187 | _assert(dup2(fds[0], 0) != -1); | |
3188 | _assert(close(fds[0]) != -1); | |
3189 | ||
3190 | input_ = fdopen(fds[1], "a"); | |
3191 | ||
3192 | _assert(pipe(fds) != -1); | |
3193 | _assert(dup2(fds[1], 1) != -1); | |
3194 | _assert(close(fds[1]) != -1); | |
3195 | ||
3196 | [NSThread | |
3197 | detachNewThreadSelector:@selector(_readOutput:) | |
3198 | toTarget:self | |
3199 | withObject:[NSNumber numberWithInt:fds[0]] | |
3200 | ]; | |
3201 | } return self; | |
3202 | } | |
3203 | ||
3204 | - (pkgCacheFile &) cache { | |
3205 | return cache_; | |
3206 | } | |
3207 | ||
3208 | - (pkgDepCache::Policy *) policy { | |
3209 | return policy_; | |
3210 | } | |
3211 | ||
3212 | - (pkgRecords *) records { | |
3213 | return records_; | |
3214 | } | |
3215 | ||
3216 | - (pkgProblemResolver *) resolver { | |
3217 | return resolver_; | |
3218 | } | |
3219 | ||
3220 | - (pkgAcquire &) fetcher { | |
3221 | return *fetcher_; | |
3222 | } | |
3223 | ||
3224 | - (pkgSourceList &) list { | |
3225 | return *list_; | |
3226 | } | |
3227 | ||
3228 | - (NSArray *) packages { | |
3229 | return (NSArray *) packages_; | |
3230 | } | |
3231 | ||
3232 | - (NSArray *) sources { | |
3233 | NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]); | |
3234 | for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i) | |
3235 | [sources addObject:i->second]; | |
3236 | return sources; | |
3237 | } | |
3238 | ||
3239 | - (NSArray *) issues { | |
3240 | if (cache_->BrokenCount() == 0) | |
3241 | return nil; | |
3242 | ||
3243 | NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]); | |
3244 | ||
3245 | for (Package *package in [self packages]) { | |
3246 | if (![package broken]) | |
3247 | continue; | |
3248 | pkgCache::PkgIterator pkg([package iterator]); | |
3249 | ||
3250 | NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]); | |
3251 | [entry addObject:[package name]]; | |
3252 | [issues addObject:entry]; | |
3253 | ||
3254 | pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_)); | |
3255 | if (ver.end()) | |
3256 | continue; | |
3257 | ||
3258 | for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) { | |
3259 | pkgCache::DepIterator start; | |
3260 | pkgCache::DepIterator end; | |
3261 | dep.GlobOr(start, end); // ++dep | |
3262 | ||
3263 | if (!cache_->IsImportantDep(end)) | |
3264 | continue; | |
3265 | if ((cache_[end] & pkgDepCache::DepGInstall) != 0) | |
3266 | continue; | |
3267 | ||
3268 | NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]); | |
3269 | [entry addObject:failure]; | |
3270 | [failure addObject:[NSString stringWithUTF8String:start.DepType()]]; | |
3271 | ||
3272 | NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]); | |
3273 | if (Package *package = [self packageWithName:name]) | |
3274 | name = [package name]; | |
3275 | [failure addObject:name]; | |
3276 | ||
3277 | pkgCache::PkgIterator target(start.TargetPkg()); | |
3278 | if (target->ProvidesList != 0) | |
3279 | [failure addObject:@"?"]; | |
3280 | else { | |
3281 | pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_)); | |
3282 | if (!ver.end()) | |
3283 | [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]]; | |
3284 | else if (!cache_[target].CandidateVerIter(cache_).end()) | |
3285 | [failure addObject:@"-"]; | |
3286 | else if (target->ProvidesList == 0) | |
3287 | [failure addObject:@"!"]; | |
3288 | else | |
3289 | [failure addObject:@"%"]; | |
3290 | } | |
3291 | ||
3292 | _forever { | |
3293 | if (start.TargetVer() != 0) | |
3294 | [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]]; | |
3295 | if (start == end) | |
3296 | break; | |
3297 | ++start; | |
3298 | } | |
3299 | } | |
3300 | } | |
3301 | ||
3302 | return issues; | |
3303 | } | |
3304 | ||
3305 | - (bool) popErrorWithTitle:(NSString *)title { | |
3306 | bool fatal(false); | |
3307 | std::string message; | |
3308 | ||
3309 | while (!_error->empty()) { | |
3310 | std::string error; | |
3311 | bool warning(!_error->PopMessage(error)); | |
3312 | if (!warning) | |
3313 | fatal = true; | |
3314 | for (;;) { | |
3315 | size_t size(error.size()); | |
3316 | if (size == 0 || error[size - 1] != '\n') | |
3317 | break; | |
3318 | error.resize(size - 1); | |
3319 | } | |
3320 | lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str()); | |
3321 | ||
3322 | if (!message.empty()) | |
3323 | message += "\n\n"; | |
3324 | message += error; | |
3325 | } | |
3326 | ||
3327 | if (fatal && !message.empty()) | |
3328 | [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]]; | |
3329 | ||
3330 | return fatal; | |
3331 | } | |
3332 | ||
3333 | - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success { | |
3334 | return [self popErrorWithTitle:title] || !success; | |
3335 | } | |
3336 | ||
3337 | - (void) reloadData { CYPoolStart() { | |
3338 | @synchronized (self) { | |
3339 | ++era_; | |
3340 | ||
3341 | [self releasePackages]; | |
3342 | sources_.clear(); | |
3343 | ||
3344 | _error->Discard(); | |
3345 | ||
3346 | delete list_; | |
3347 | list_ = NULL; | |
3348 | manager_ = NULL; | |
3349 | delete lock_; | |
3350 | lock_ = NULL; | |
3351 | delete fetcher_; | |
3352 | fetcher_ = NULL; | |
3353 | delete resolver_; | |
3354 | resolver_ = NULL; | |
3355 | delete records_; | |
3356 | records_ = NULL; | |
3357 | delete policy_; | |
3358 | policy_ = NULL; | |
3359 | ||
3360 | cache_.Close(); | |
3361 | ||
3362 | apr_pool_clear(pool_); | |
3363 | ||
3364 | NSRecycleZone(zone_); | |
3365 | zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO); | |
3366 | ||
3367 | int chk(creat("/tmp/cydia.chk", 0644)); | |
3368 | if (chk != -1) | |
3369 | close(chk); | |
3370 | ||
3371 | NSString *title(UCLocalize("DATABASE")); | |
3372 | ||
3373 | _trace(); | |
3374 | if (!cache_.Open(progress_, true)) { pop: | |
3375 | std::string error; | |
3376 | bool warning(!_error->PopMessage(error)); | |
3377 | lprintf("cache_.Open():[%s]\n", error.c_str()); | |
3378 | ||
3379 | if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ") | |
3380 | [delegate_ repairWithSelector:@selector(configure)]; | |
3381 | else if (error == "The package lists or status file could not be parsed or opened.") | |
3382 | [delegate_ repairWithSelector:@selector(update)]; | |
3383 | // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)") | |
3384 | // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)") | |
3385 | // else if (error == "The list of sources could not be read.") | |
3386 | else | |
3387 | [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]]; | |
3388 | ||
3389 | if (warning) | |
3390 | goto pop; | |
3391 | _error->Discard(); | |
3392 | return; | |
3393 | } | |
3394 | _trace(); | |
3395 | ||
3396 | unlink("/tmp/cydia.chk"); | |
3397 | ||
3398 | now_ = [[NSDate date] timeIntervalSince1970]; | |
3399 | ||
3400 | policy_ = new pkgDepCache::Policy(); | |
3401 | records_ = new pkgRecords(cache_); | |
3402 | resolver_ = new pkgProblemResolver(cache_); | |
3403 | fetcher_ = new pkgAcquire(&status_); | |
3404 | lock_ = NULL; | |
3405 | ||
3406 | list_ = new pkgSourceList(); | |
3407 | if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()]) | |
3408 | return; | |
3409 | ||
3410 | if (cache_->DelCount() != 0 || cache_->InstCount() != 0) { | |
3411 | [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title]; | |
3412 | return; | |
3413 | } | |
3414 | ||
3415 | if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)]) | |
3416 | return; | |
3417 | ||
3418 | if (cache_->BrokenCount() != 0) { | |
3419 | if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)]) | |
3420 | return; | |
3421 | ||
3422 | if (cache_->BrokenCount() != 0) { | |
3423 | [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title]; | |
3424 | return; | |
3425 | } | |
3426 | ||
3427 | if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)]) | |
3428 | return; | |
3429 | } | |
3430 | ||
3431 | for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) { | |
3432 | std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles(); | |
3433 | for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index) | |
3434 | // XXX: this could be more intelligent | |
3435 | if (dynamic_cast<debPackagesIndex *>(*index) != NULL) { | |
3436 | pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_)); | |
3437 | if (!cached.end()) | |
3438 | sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]; | |
3439 | } | |
3440 | } | |
3441 | ||
3442 | { | |
3443 | /*std::vector<Package *> packages; | |
3444 | packages.reserve(std::max(10000U, [packages_ count] + 1000)); | |
3445 | [packages_ release]; | |
3446 | packages_ = nil;*/ | |
3447 | ||
3448 | _trace(); | |
3449 | ||
3450 | for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator) | |
3451 | if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self]) | |
3452 | //packages.push_back(package); | |
3453 | CFArrayAppendValue(packages_, [package retain]); | |
3454 | ||
3455 | _trace(); | |
3456 | ||
3457 | /*if (packages.empty()) | |
3458 | packages_ = [[NSArray alloc] init]; | |
3459 | else | |
3460 | packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()]; | |
3461 | _trace();*/ | |
3462 | ||
3463 | [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)]; | |
3464 | [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)]; | |
3465 | [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)]; | |
3466 | ||
3467 | /*_trace(); | |
3468 | PrintTimes(); | |
3469 | _trace();*/ | |
3470 | ||
3471 | _trace(); | |
3472 | ||
3473 | /*if (!packages.empty()) | |
3474 | CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/ | |
3475 | //std::sort(packages.begin(), packages.end(), PackageNameOrdering()); | |
3476 | ||
3477 | //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL); | |
3478 | ||
3479 | CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL); | |
3480 | ||
3481 | //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL]; | |
3482 | ||
3483 | _trace(); | |
3484 | ||
3485 | size_t count(CFArrayGetCount(packages_)); | |
3486 | MetaFile_->active_ = count; | |
3487 | ||
3488 | for (size_t index(0); index != count; ++index) | |
3489 | [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index]; | |
3490 | ||
3491 | _trace(); | |
3492 | } | |
3493 | } } CYPoolEnd() _trace(); } | |
3494 | ||
3495 | - (void) clear { | |
3496 | @synchronized (self) { | |
3497 | delete resolver_; | |
3498 | resolver_ = new pkgProblemResolver(cache_); | |
3499 | ||
3500 | for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) { | |
3501 | if (!cache_[iterator].Keep()) { | |
3502 | cache_->MarkKeep(iterator, false); | |
3503 | cache_->SetReInstall(iterator, false); | |
3504 | } | |
3505 | } | |
3506 | } } | |
3507 | ||
3508 | - (void) configure { | |
3509 | NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_]; | |
3510 | system([dpkg UTF8String]); | |
3511 | } | |
3512 | ||
3513 | - (bool) clean { | |
3514 | // XXX: I don't remember this condition | |
3515 | if (lock_ != NULL) | |
3516 | return false; | |
3517 | ||
3518 | FileFd Lock; | |
3519 | Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock")); | |
3520 | ||
3521 | NSString *title(UCLocalize("CLEAN_ARCHIVES")); | |
3522 | ||
3523 | if ([self popErrorWithTitle:title]) | |
3524 | return false; | |
3525 | ||
3526 | pkgAcquire fetcher; | |
3527 | fetcher.Clean(_config->FindDir("Dir::Cache::Archives")); | |
3528 | ||
3529 | class LogCleaner : | |
3530 | public pkgArchiveCleaner | |
3531 | { | |
3532 | protected: | |
3533 | virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) { | |
3534 | unlink(File); | |
3535 | } | |
3536 | } cleaner; | |
3537 | ||
3538 | if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)]) | |
3539 | return false; | |
3540 | ||
3541 | return true; | |
3542 | } | |
3543 | ||
3544 | - (bool) prepare { | |
3545 | fetcher_->Shutdown(); | |
3546 | ||
3547 | pkgRecords records(cache_); | |
3548 | ||
3549 | lock_ = new FileFd(); | |
3550 | lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock")); | |
3551 | ||
3552 | NSString *title(UCLocalize("PREPARE_ARCHIVES")); | |
3553 | ||
3554 | if ([self popErrorWithTitle:title]) | |
3555 | return false; | |
3556 | ||
3557 | pkgSourceList list; | |
3558 | if ([self popErrorWithTitle:title forOperation:list.ReadMainList()]) | |
3559 | return false; | |
3560 | ||
3561 | manager_ = (_system->CreatePM(cache_)); | |
3562 | if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)]) | |
3563 | return false; | |
3564 | ||
3565 | return true; | |
3566 | } | |
3567 | ||
3568 | - (void) perform { | |
3569 | NSString *title(UCLocalize("PERFORM_SELECTIONS")); | |
3570 | ||
3571 | NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; { | |
3572 | pkgSourceList list; | |
3573 | if ([self popErrorWithTitle:title forOperation:list.ReadMainList()]) | |
3574 | return; | |
3575 | for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source) | |
3576 | [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]]; | |
3577 | } | |
3578 | ||
3579 | if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) { | |
3580 | _trace(); | |
3581 | return; | |
3582 | } | |
3583 | ||
3584 | bool failed = false; | |
3585 | for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) { | |
3586 | if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete) | |
3587 | continue; | |
3588 | if ((*item)->Status == pkgAcquire::Item::StatIdle) | |
3589 | continue; | |
3590 | ||
3591 | std::string uri = (*item)->DescURI(); | |
3592 | std::string error = (*item)->ErrorText; | |
3593 | ||
3594 | lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str()); | |
3595 | failed = true; | |
3596 | ||
3597 | [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:) | |
3598 | withObject:[NSArray arrayWithObjects: | |
3599 | [NSString stringWithUTF8String:error.c_str()], | |
3600 | nil] | |
3601 | waitUntilDone:YES | |
3602 | ]; | |
3603 | } | |
3604 | ||
3605 | if (failed) { | |
3606 | _trace(); | |
3607 | return; | |
3608 | } | |
3609 | ||
3610 | _system->UnLock(); | |
3611 | pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_); | |
3612 | ||
3613 | if (_error->PendingError()) { | |
3614 | _trace(); | |
3615 | return; | |
3616 | } | |
3617 | ||
3618 | if (result == pkgPackageManager::Failed) { | |
3619 | _trace(); | |
3620 | return; | |
3621 | } | |
3622 | ||
3623 | if (result != pkgPackageManager::Completed) { | |
3624 | _trace(); | |
3625 | return; | |
3626 | } | |
3627 | ||
3628 | NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; { | |
3629 | pkgSourceList list; | |
3630 | if ([self popErrorWithTitle:title forOperation:list.ReadMainList()]) | |
3631 | return; | |
3632 | for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source) | |
3633 | [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]]; | |
3634 | } | |
3635 | ||
3636 | if (![before isEqualToArray:after]) | |
3637 | [self update]; | |
3638 | } | |
3639 | ||
3640 | - (bool) upgrade { | |
3641 | NSString *title(UCLocalize("UPGRADE")); | |
3642 | if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)]) | |
3643 | return false; | |
3644 | return true; | |
3645 | } | |
3646 | ||
3647 | - (void) update { | |
3648 | [self updateWithStatus:status_]; | |
3649 | } | |
3650 | ||
3651 | - (void) updateWithStatus:(Status &)status { | |
3652 | _transient NSObject<ProgressDelegate> *delegate(status.getDelegate()); | |
3653 | NSString *title(UCLocalize("REFRESHING_DATA")); | |
3654 | ||
3655 | pkgSourceList list; | |
3656 | if (!list.ReadMainList()) | |
3657 | [delegate _setProgressError:@"Unable to read source list." withTitle:title]; | |
3658 | ||
3659 | FileFd lock; | |
3660 | lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock")); | |
3661 | if ([self popErrorWithTitle:title]) | |
3662 | return; | |
3663 | ||
3664 | if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)]) | |
3665 | /* XXX: ignore this because users suck and don't understand why refreshing is important: return */ | |
3666 | /* XXX: why the hell is an empty if statement a clang error? */ (void) 0; | |
3667 | ||
3668 | [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"]; | |
3669 | Changed_ = true; | |
3670 | } | |
3671 | ||
3672 | - (void) setDelegate:(id)delegate { | |
3673 | delegate_ = delegate; | |
3674 | status_.setDelegate(delegate); | |
3675 | progress_.setDelegate(delegate); | |
3676 | } | |
3677 | ||
3678 | - (Source *) getSource:(pkgCache::PkgFileIterator)file { | |
3679 | SourceMap::const_iterator i(sources_.find(file->ID)); | |
3680 | return i == sources_.end() ? nil : i->second; | |
3681 | } | |
3682 | ||
3683 | @end | |
3684 | /* }}} */ | |
3685 | ||
3686 | /* Confirmation Controller {{{ */ | |
3687 | bool DepSubstrate(const pkgCache::VerIterator &iterator) { | |
3688 | if (!iterator.end()) | |
3689 | for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) { | |
3690 | if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends) | |
3691 | continue; | |
3692 | pkgCache::PkgIterator package(dep.TargetPkg()); | |
3693 | if (package.end()) | |
3694 | continue; | |
3695 | if (strcmp(package.Name(), "mobilesubstrate") == 0) | |
3696 | return true; | |
3697 | } | |
3698 | ||
3699 | return false; | |
3700 | } | |
3701 | /* }}} */ | |
3702 | ||
3703 | /* Web Scripting {{{ */ | |
3704 | @interface CydiaObject : NSObject { | |
3705 | id indirect_; | |
3706 | _transient id delegate_; | |
3707 | } | |
3708 | ||
3709 | - (id) initWithDelegate:(IndirectDelegate *)indirect; | |
3710 | @end | |
3711 | ||
3712 | @implementation CydiaObject | |
3713 | ||
3714 | - (void) dealloc { | |
3715 | [indirect_ release]; | |
3716 | [super dealloc]; | |
3717 | } | |
3718 | ||
3719 | - (id) initWithDelegate:(IndirectDelegate *)indirect { | |
3720 | if ((self = [super init]) != nil) { | |
3721 | indirect_ = [indirect retain]; | |
3722 | } return self; | |
3723 | } | |
3724 | ||
3725 | - (void) setDelegate:(id)delegate { | |
3726 | delegate_ = delegate; | |
3727 | } | |
3728 | ||
3729 | + (NSArray *) _attributeKeys { | |
3730 | return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil]; | |
3731 | } | |
3732 | ||
3733 | - (NSArray *) attributeKeys { | |
3734 | return [[self class] _attributeKeys]; | |
3735 | } | |
3736 | ||
3737 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
3738 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
3739 | } | |
3740 | ||
3741 | - (NSString *) device { | |
3742 | return [[UIDevice currentDevice] uniqueIdentifier]; | |
3743 | } | |
3744 | ||
3745 | #if 0 // XXX: implement! | |
3746 | - (NSString *) mac { | |
3747 | if (![indirect_ promptForSensitive:@"Mac Address"]) | |
3748 | return nil; | |
3749 | } | |
3750 | ||
3751 | - (NSString *) serial { | |
3752 | if (![indirect_ promptForSensitive:@"Serial #"]) | |
3753 | return nil; | |
3754 | } | |
3755 | ||
3756 | - (NSString *) firewire { | |
3757 | if (![indirect_ promptForSensitive:@"Firewire GUID"]) | |
3758 | return nil; | |
3759 | } | |
3760 | ||
3761 | - (NSString *) imei { | |
3762 | if (![indirect_ promptForSensitive:@"IMEI"]) | |
3763 | return nil; | |
3764 | } | |
3765 | #endif | |
3766 | ||
3767 | + (NSString *) webScriptNameForSelector:(SEL)selector { | |
3768 | if (selector == @selector(close)) | |
3769 | return @"close"; | |
3770 | else if (selector == @selector(getInstalledPackages)) | |
3771 | return @"getInstalledPackages"; | |
3772 | else if (selector == @selector(getPackageById:)) | |
3773 | return @"getPackageById"; | |
3774 | else if (selector == @selector(installPackages:)) | |
3775 | return @"installPackages"; | |
3776 | else if (selector == @selector(setButtonImage:withStyle:toFunction:)) | |
3777 | return @"setButtonImage"; | |
3778 | else if (selector == @selector(setButtonTitle:withStyle:toFunction:)) | |
3779 | return @"setButtonTitle"; | |
3780 | else if (selector == @selector(setPopupHook:)) | |
3781 | return @"setPopupHook"; | |
3782 | else if (selector == @selector(setSpecial:)) | |
3783 | return @"setSpecial"; | |
3784 | else if (selector == @selector(setToken:)) | |
3785 | return @"setToken"; | |
3786 | else if (selector == @selector(setViewportWidth:)) | |
3787 | return @"setViewportWidth"; | |
3788 | else if (selector == @selector(supports:)) | |
3789 | return @"supports"; | |
3790 | else if (selector == @selector(stringWithFormat:arguments:)) | |
3791 | return @"format"; | |
3792 | else if (selector == @selector(localizedStringForKey:value:table:)) | |
3793 | return @"localize"; | |
3794 | else if (selector == @selector(du:)) | |
3795 | return @"du"; | |
3796 | else if (selector == @selector(statfs:)) | |
3797 | return @"statfs"; | |
3798 | else | |
3799 | return nil; | |
3800 | } | |
3801 | ||
3802 | + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector { | |
3803 | return [self webScriptNameForSelector:selector] == nil; | |
3804 | } | |
3805 | ||
3806 | - (BOOL) supports:(NSString *)feature { | |
3807 | return [feature isEqualToString:@"window.open"]; | |
3808 | } | |
3809 | ||
3810 | - (NSArray *) getInstalledPackages { | |
3811 | NSArray *packages([[Database sharedInstance] packages]); | |
3812 | NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]); | |
3813 | for (Package *package in packages) | |
3814 | if ([package installed] != nil) | |
3815 | [installed addObject:package]; | |
3816 | return installed; | |
3817 | } | |
3818 | ||
3819 | - (Package *) getPackageById:(NSString *)id { | |
3820 | Package *package([[Database sharedInstance] packageWithName:id]); | |
3821 | [package parse]; | |
3822 | return package; | |
3823 | } | |
3824 | ||
3825 | - (NSArray *) statfs:(NSString *)path { | |
3826 | struct statfs stat; | |
3827 | ||
3828 | if (path == nil || statfs([path UTF8String], &stat) == -1) | |
3829 | return nil; | |
3830 | ||
3831 | return [NSArray arrayWithObjects: | |
3832 | [NSNumber numberWithUnsignedLong:stat.f_bsize], | |
3833 | [NSNumber numberWithUnsignedLong:stat.f_blocks], | |
3834 | [NSNumber numberWithUnsignedLong:stat.f_bfree], | |
3835 | nil]; | |
3836 | } | |
3837 | ||
3838 | - (NSNumber *) du:(NSString *)path { | |
3839 | NSNumber *value(nil); | |
3840 | ||
3841 | int fds[2]; | |
3842 | _assert(pipe(fds) != -1); | |
3843 | ||
3844 | pid_t pid(ExecFork()); | |
3845 | if (pid == 0) { | |
3846 | _assert(dup2(fds[1], 1) != -1); | |
3847 | _assert(close(fds[0]) != -1); | |
3848 | _assert(close(fds[1]) != -1); | |
3849 | /* XXX: this should probably not use du */ | |
3850 | execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL); | |
3851 | exit(1); | |
3852 | _assert(false); | |
3853 | } | |
3854 | ||
3855 | _assert(close(fds[1]) != -1); | |
3856 | ||
3857 | if (FILE *du = fdopen(fds[0], "r")) { | |
3858 | char line[1024]; | |
3859 | while (fgets(line, sizeof(line), du) != NULL) { | |
3860 | size_t length(strlen(line)); | |
3861 | while (length != 0 && line[length - 1] == '\n') | |
3862 | line[--length] = '\0'; | |
3863 | if (char *tab = strchr(line, '\t')) { | |
3864 | *tab = '\0'; | |
3865 | value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)]; | |
3866 | } | |
3867 | } | |
3868 | ||
3869 | fclose(du); | |
3870 | } else _assert(close(fds[0])); | |
3871 | ||
3872 | int status; | |
3873 | wait: | |
3874 | if (waitpid(pid, &status, 0) == -1) | |
3875 | if (errno == EINTR) | |
3876 | goto wait; | |
3877 | else _assert(false); | |
3878 | ||
3879 | return value; | |
3880 | } | |
3881 | ||
3882 | - (void) close { | |
3883 | [indirect_ close]; | |
3884 | } | |
3885 | ||
3886 | - (void) installPackages:(NSArray *)packages { | |
3887 | [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO]; | |
3888 | } | |
3889 | ||
3890 | - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function { | |
3891 | [indirect_ setButtonImage:button withStyle:style toFunction:function]; | |
3892 | } | |
3893 | ||
3894 | - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function { | |
3895 | [indirect_ setButtonTitle:button withStyle:style toFunction:function]; | |
3896 | } | |
3897 | ||
3898 | - (void) setSpecial:(id)function { | |
3899 | [indirect_ setSpecial:function]; | |
3900 | } | |
3901 | ||
3902 | - (void) setToken:(NSString *)token { | |
3903 | if (Token_ != nil) | |
3904 | [Token_ release]; | |
3905 | Token_ = [token retain]; | |
3906 | ||
3907 | [Metadata_ setObject:Token_ forKey:@"Token"]; | |
3908 | Changed_ = true; | |
3909 | } | |
3910 | ||
3911 | - (void) setPopupHook:(id)function { | |
3912 | [indirect_ setPopupHook:function]; | |
3913 | } | |
3914 | ||
3915 | - (void) setViewportWidth:(float)width { | |
3916 | [indirect_ setViewportWidth:width]; | |
3917 | } | |
3918 | ||
3919 | - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments { | |
3920 | //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]); | |
3921 | unsigned count([arguments count]); | |
3922 | id values[count]; | |
3923 | for (unsigned i(0); i != count; ++i) | |
3924 | values[i] = [arguments objectAtIndex:i]; | |
3925 | return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease]; | |
3926 | } | |
3927 | ||
3928 | - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table { | |
3929 | if (reinterpret_cast<id>(value) == [WebUndefined undefined]) | |
3930 | value = nil; | |
3931 | if (reinterpret_cast<id>(table) == [WebUndefined undefined]) | |
3932 | table = nil; | |
3933 | return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table]; | |
3934 | } | |
3935 | ||
3936 | @end | |
3937 | /* }}} */ | |
3938 | ||
3939 | /* Cydia Browser Controller {{{ */ | |
3940 | @interface CYBrowserController : BrowserController { | |
3941 | CydiaObject *cydia_; | |
3942 | } | |
3943 | ||
3944 | @end | |
3945 | ||
3946 | @implementation CYBrowserController | |
3947 | ||
3948 | - (void) dealloc { | |
3949 | [cydia_ release]; | |
3950 | [super dealloc]; | |
3951 | } | |
3952 | ||
3953 | - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host { | |
3954 | } | |
3955 | ||
3956 | - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame { | |
3957 | [super webView:view didClearWindowObject:window forFrame:frame]; | |
3958 | ||
3959 | WebDataSource *source([frame dataSource]); | |
3960 | NSURLResponse *response([source response]); | |
3961 | NSURL *url([response URL]); | |
3962 | NSString *scheme([url scheme]); | |
3963 | ||
3964 | NSHTTPURLResponse *http; | |
3965 | if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"])) | |
3966 | http = (NSHTTPURLResponse *) response; | |
3967 | else | |
3968 | http = nil; | |
3969 | ||
3970 | NSDictionary *headers([http allHeaderFields]); | |
3971 | NSString *host([url host]); | |
3972 | [self setHeaders:headers forHost:host]; | |
3973 | ||
3974 | if ( | |
3975 | [host isEqualToString:@"cydia.saurik.com"] || | |
3976 | [host hasSuffix:@".cydia.saurik.com"] || | |
3977 | [scheme isEqualToString:@"file"] | |
3978 | ) | |
3979 | [window setValue:cydia_ forKey:@"cydia"]; | |
3980 | } | |
3981 | ||
3982 | - (void) _setMoreHeaders:(NSMutableURLRequest *)request { | |
3983 | if (System_ != NULL) | |
3984 | [request setValue:System_ forHTTPHeaderField:@"X-System"]; | |
3985 | if (Machine_ != NULL) | |
3986 | [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"]; | |
3987 | if (Token_ != nil) | |
3988 | [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"]; | |
3989 | if (Role_ != nil) | |
3990 | [request setValue:Role_ forHTTPHeaderField:@"X-Role"]; | |
3991 | } | |
3992 | ||
3993 | - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source { | |
3994 | NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]); | |
3995 | [self _setMoreHeaders:copy]; | |
3996 | return copy; | |
3997 | } | |
3998 | ||
3999 | - (void) setDelegate:(id)delegate { | |
4000 | [super setDelegate:delegate]; | |
4001 | [cydia_ setDelegate:delegate]; | |
4002 | } | |
4003 | ||
4004 | - (id) init { | |
4005 | if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) { | |
4006 | cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_]; | |
4007 | ||
4008 | WebView *webview([[webview_ _documentView] webView]); | |
4009 | ||
4010 | Package *package([[Database sharedInstance] packageWithName:@"cydia"]); | |
4011 | ||
4012 | NSString *application = package == nil ? @"Cydia" : [NSString | |
4013 | stringWithFormat:@"Cydia/%@", | |
4014 | [package installed] | |
4015 | ]; | |
4016 | ||
4017 | if (Safari_ != nil) | |
4018 | application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application]; | |
4019 | if (Build_ != nil) | |
4020 | application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application]; | |
4021 | if (Product_ != nil) | |
4022 | application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application]; | |
4023 | ||
4024 | [webview setApplicationNameForUserAgent:application]; | |
4025 | } return self; | |
4026 | } | |
4027 | ||
4028 | @end | |
4029 | /* }}} */ | |
4030 | ||
4031 | /* Confirmation {{{ */ | |
4032 | @protocol ConfirmationControllerDelegate | |
4033 | - (void) cancelAndClear:(bool)clear; | |
4034 | - (void) confirmWithNavigationController:(UINavigationController *)navigation; | |
4035 | - (void) queue; | |
4036 | @end | |
4037 | ||
4038 | @interface ConfirmationController : CYBrowserController { | |
4039 | _transient Database *database_; | |
4040 | UIAlertView *essential_; | |
4041 | NSArray *changes_; | |
4042 | NSArray *issues_; | |
4043 | NSArray *sizes_; | |
4044 | BOOL substrate_; | |
4045 | } | |
4046 | ||
4047 | - (id) initWithDatabase:(Database *)database; | |
4048 | ||
4049 | @end | |
4050 | ||
4051 | @implementation ConfirmationController | |
4052 | ||
4053 | - (void) dealloc { | |
4054 | [changes_ release]; | |
4055 | if (issues_ != nil) | |
4056 | [issues_ release]; | |
4057 | [sizes_ release]; | |
4058 | if (essential_ != nil) | |
4059 | [essential_ release]; | |
4060 | [super dealloc]; | |
4061 | } | |
4062 | ||
4063 | - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { | |
4064 | NSString *context([alert context]); | |
4065 | ||
4066 | if ([context isEqualToString:@"remove"]) { | |
4067 | if (button == [alert cancelButtonIndex]) { | |
4068 | [self dismissModalViewControllerAnimated:YES]; | |
4069 | } else if (button == [alert firstOtherButtonIndex]) { | |
4070 | if (substrate_) | |
4071 | Finish_ = 2; | |
4072 | [delegate_ confirmWithNavigationController:[self navigationController]]; | |
4073 | } | |
4074 | ||
4075 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
4076 | } else if ([context isEqualToString:@"unable"]) { | |
4077 | [self dismissModalViewControllerAnimated:YES]; | |
4078 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
4079 | } else { | |
4080 | [super alertView:alert clickedButtonAtIndex:button]; | |
4081 | } | |
4082 | } | |
4083 | ||
4084 | - (void) _doContinue { | |
4085 | [self dismissModalViewControllerAnimated:YES]; | |
4086 | [delegate_ cancelAndClear:NO]; | |
4087 | } | |
4088 | ||
4089 | - (id) invokeDefaultMethodWithArguments:(NSArray *)args { | |
4090 | [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO]; | |
4091 | return nil; | |
4092 | } | |
4093 | ||
4094 | - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame { | |
4095 | [super webView:view didClearWindowObject:window forFrame:frame]; | |
4096 | [window setValue:changes_ forKey:@"changes"]; | |
4097 | [window setValue:issues_ forKey:@"issues"]; | |
4098 | [window setValue:sizes_ forKey:@"sizes"]; | |
4099 | [window setValue:self forKey:@"queue"]; | |
4100 | } | |
4101 | ||
4102 | - (id) initWithDatabase:(Database *)database { | |
4103 | if ((self = [super init]) != nil) { | |
4104 | database_ = database; | |
4105 | ||
4106 | [[self navigationItem] setTitle:UCLocalize("CONFIRM")]; | |
4107 | ||
4108 | NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16]; | |
4109 | NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16]; | |
4110 | NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16]; | |
4111 | NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16]; | |
4112 | NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16]; | |
4113 | ||
4114 | bool remove(false); | |
4115 | ||
4116 | pkgDepCache::Policy *policy([database_ policy]); | |
4117 | ||
4118 | pkgCacheFile &cache([database_ cache]); | |
4119 | NSArray *packages = [database_ packages]; | |
4120 | for (Package *package in packages) { | |
4121 | pkgCache::PkgIterator iterator = [package iterator]; | |
4122 | pkgDepCache::StateCache &state(cache[iterator]); | |
4123 | ||
4124 | NSString *name([package name]); | |
4125 | ||
4126 | if (state.NewInstall()) | |
4127 | [installing addObject:name]; | |
4128 | else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall) | |
4129 | [reinstalling addObject:name]; | |
4130 | else if (state.Upgrade()) | |
4131 | [upgrading addObject:name]; | |
4132 | else if (state.Downgrade()) | |
4133 | [downgrading addObject:name]; | |
4134 | else if (state.Delete()) { | |
4135 | if ([package essential]) | |
4136 | remove = true; | |
4137 | [removing addObject:name]; | |
4138 | } else continue; | |
4139 | ||
4140 | substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator)); | |
4141 | substrate_ |= DepSubstrate(iterator.CurrentVer()); | |
4142 | } | |
4143 | ||
4144 | if (!remove) | |
4145 | essential_ = nil; | |
4146 | else if (Advanced_) { | |
4147 | NSString *parenthetical(UCLocalize("PARENTHETICAL")); | |
4148 | ||
4149 | essential_ = [[UIAlertView alloc] | |
4150 | initWithTitle:UCLocalize("REMOVING_ESSENTIALS") | |
4151 | message:UCLocalize("REMOVING_ESSENTIALS_EX") | |
4152 | delegate:self | |
4153 | cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")] | |
4154 | otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil | |
4155 | ]; | |
4156 | ||
4157 | [essential_ setContext:@"remove"]; | |
4158 | } else { | |
4159 | essential_ = [[UIAlertView alloc] | |
4160 | initWithTitle:UCLocalize("UNABLE_TO_COMPLY") | |
4161 | message:UCLocalize("UNABLE_TO_COMPLY_EX") | |
4162 | delegate:self | |
4163 | cancelButtonTitle:UCLocalize("OKAY") | |
4164 | otherButtonTitles:nil | |
4165 | ]; | |
4166 | ||
4167 | [essential_ setContext:@"unable"]; | |
4168 | } | |
4169 | ||
4170 | changes_ = [[NSArray alloc] initWithObjects: | |
4171 | installing, | |
4172 | reinstalling, | |
4173 | upgrading, | |
4174 | downgrading, | |
4175 | removing, | |
4176 | nil]; | |
4177 | ||
4178 | issues_ = [database_ issues]; | |
4179 | if (issues_ != nil) | |
4180 | issues_ = [issues_ retain]; | |
4181 | ||
4182 | sizes_ = [[NSArray alloc] initWithObjects: | |
4183 | SizeString([database_ fetcher].FetchNeeded()), | |
4184 | SizeString([database_ fetcher].PartialPresent()), | |
4185 | nil]; | |
4186 | ||
4187 | [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]]; | |
4188 | ||
4189 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
4190 | initWithTitle:UCLocalize("CANCEL") | |
4191 | // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")] | |
4192 | style:UIBarButtonItemStylePlain | |
4193 | target:self | |
4194 | action:@selector(cancelButtonClicked) | |
4195 | ] autorelease]]; | |
4196 | } return self; | |
4197 | } | |
4198 | ||
4199 | - (void) applyRightButton { | |
4200 | #if !AlwaysReload && !IgnoreInstall | |
4201 | if (issues_ == nil && ![self isLoading]) | |
4202 | [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] | |
4203 | initWithTitle:UCLocalize("CONFIRM") | |
4204 | style:UIBarButtonItemStylePlain | |
4205 | target:self | |
4206 | action:@selector(confirmButtonClicked) | |
4207 | ] autorelease]]; | |
4208 | else | |
4209 | [super applyRightButton]; | |
4210 | #else | |
4211 | [[self navigationItem] setRightBarButtonItem:nil]; | |
4212 | #endif | |
4213 | } | |
4214 | ||
4215 | - (void) cancelButtonClicked { | |
4216 | [self dismissModalViewControllerAnimated:YES]; | |
4217 | [delegate_ cancelAndClear:YES]; | |
4218 | } | |
4219 | ||
4220 | #if !AlwaysReload | |
4221 | - (void) confirmButtonClicked { | |
4222 | #if IgnoreInstall | |
4223 | return; | |
4224 | #endif | |
4225 | if (essential_ != nil) | |
4226 | [essential_ show]; | |
4227 | else { | |
4228 | if (substrate_) | |
4229 | Finish_ = 2; | |
4230 | [delegate_ confirmWithNavigationController:[self navigationController]]; | |
4231 | } | |
4232 | } | |
4233 | #endif | |
4234 | ||
4235 | @end | |
4236 | /* }}} */ | |
4237 | ||
4238 | /* Progress Data {{{ */ | |
4239 | @interface ProgressData : NSObject { | |
4240 | SEL selector_; | |
4241 | // XXX: should these really both be _transient? | |
4242 | _transient id target_; | |
4243 | _transient id object_; | |
4244 | } | |
4245 | ||
4246 | - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object; | |
4247 | ||
4248 | - (SEL) selector; | |
4249 | - (id) target; | |
4250 | - (id) object; | |
4251 | @end | |
4252 | ||
4253 | @implementation ProgressData | |
4254 | ||
4255 | - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object { | |
4256 | if ((self = [super init]) != nil) { | |
4257 | selector_ = selector; | |
4258 | target_ = target; | |
4259 | object_ = object; | |
4260 | } return self; | |
4261 | } | |
4262 | ||
4263 | - (SEL) selector { | |
4264 | return selector_; | |
4265 | } | |
4266 | ||
4267 | - (id) target { | |
4268 | return target_; | |
4269 | } | |
4270 | ||
4271 | - (id) object { | |
4272 | return object_; | |
4273 | } | |
4274 | ||
4275 | @end | |
4276 | /* }}} */ | |
4277 | /* Progress Controller {{{ */ | |
4278 | @interface ProgressController : CYViewController < | |
4279 | ConfigurationDelegate, | |
4280 | ProgressDelegate | |
4281 | > { | |
4282 | _transient Database *database_; | |
4283 | UIProgressBar *progress_; | |
4284 | UITextView *output_; | |
4285 | UITextLabel *status_; | |
4286 | UIPushButton *close_; | |
4287 | BOOL running_; | |
4288 | SHA1SumValue springlist_; | |
4289 | SHA1SumValue notifyconf_; | |
4290 | NSString *title_; | |
4291 | } | |
4292 | ||
4293 | - (id) initWithDatabase:(Database *)database delegate:(id)delegate; | |
4294 | ||
4295 | - (void) _retachThread; | |
4296 | - (void) _detachNewThreadData:(ProgressData *)data; | |
4297 | - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title; | |
4298 | ||
4299 | - (BOOL) isRunning; | |
4300 | ||
4301 | @end | |
4302 | ||
4303 | @protocol ProgressControllerDelegate | |
4304 | - (void) progressControllerIsComplete:(ProgressController *)sender; | |
4305 | @end | |
4306 | ||
4307 | @implementation ProgressController | |
4308 | ||
4309 | - (void) dealloc { | |
4310 | [database_ setDelegate:nil]; | |
4311 | [progress_ release]; | |
4312 | [output_ release]; | |
4313 | [status_ release]; | |
4314 | [close_ release]; | |
4315 | if (title_ != nil) | |
4316 | [title_ release]; | |
4317 | [super dealloc]; | |
4318 | } | |
4319 | ||
4320 | - (id) initWithDatabase:(Database *)database delegate:(id)delegate { | |
4321 | if ((self = [super init]) != nil) { | |
4322 | database_ = database; | |
4323 | [database_ setDelegate:self]; | |
4324 | delegate_ = delegate; | |
4325 | ||
4326 | [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]]; | |
4327 | ||
4328 | progress_ = [[UIProgressBar alloc] init]; | |
4329 | [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)]; | |
4330 | [progress_ setStyle:0]; | |
4331 | ||
4332 | status_ = [[UITextLabel alloc] init]; | |
4333 | [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)]; | |
4334 | [status_ setColor:[UIColor whiteColor]]; | |
4335 | [status_ setBackgroundColor:[UIColor clearColor]]; | |
4336 | [status_ setCentersHorizontally:YES]; | |
4337 | //[status_ setFont:font]; | |
4338 | ||
4339 | output_ = [[UITextView alloc] init]; | |
4340 | ||
4341 | [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
4342 | //[output_ setTextFont:@"Courier New"]; | |
4343 | [output_ setFont:[[output_ font] fontWithSize:12]]; | |
4344 | [output_ setTextColor:[UIColor whiteColor]]; | |
4345 | [output_ setBackgroundColor:[UIColor clearColor]]; | |
4346 | [output_ setMarginTop:0]; | |
4347 | [output_ setAllowsRubberBanding:YES]; | |
4348 | [output_ setEditable:NO]; | |
4349 | [[self view] addSubview:output_]; | |
4350 | ||
4351 | close_ = [[UIPushButton alloc] init]; | |
4352 | [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)]; | |
4353 | [close_ setAutosizesToFit:NO]; | |
4354 | [close_ setDrawsShadow:YES]; | |
4355 | [close_ setStretchBackground:YES]; | |
4356 | [close_ setEnabled:YES]; | |
4357 | [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]]; | |
4358 | [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside]; | |
4359 | [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0]; | |
4360 | [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1]; | |
4361 | } return self; | |
4362 | } | |
4363 | ||
4364 | - (void) positionViews { | |
4365 | CGRect bounds = [[self view] bounds]; | |
4366 | CGSize prgsize = [UIProgressBar defaultSize]; | |
4367 | ||
4368 | CGRect prgrect = {{ | |
4369 | (bounds.size.width - prgsize.width) / 2, | |
4370 | bounds.size.height - prgsize.height - 20 | |
4371 | }, prgsize}; | |
4372 | ||
4373 | float closewidth = std::min(bounds.size.width - 20, 300.0f); | |
4374 | ||
4375 | [progress_ setFrame:prgrect]; | |
4376 | [status_ setFrame:CGRectMake( | |
4377 | 10, | |
4378 | bounds.size.height - prgsize.height - 50, | |
4379 | bounds.size.width - 20, | |
4380 | 24 | |
4381 | )]; | |
4382 | [output_ setFrame:CGRectMake( | |
4383 | 10, | |
4384 | 20, | |
4385 | bounds.size.width - 20, | |
4386 | bounds.size.height - 62 | |
4387 | )]; | |
4388 | [close_ setFrame:CGRectMake( | |
4389 | (bounds.size.width - closewidth) / 2, | |
4390 | bounds.size.height - prgsize.height - 50, | |
4391 | closewidth, | |
4392 | 32 + prgsize.height | |
4393 | )]; | |
4394 | } | |
4395 | ||
4396 | - (void) viewWillAppear:(BOOL)animated { | |
4397 | [super viewDidAppear:animated]; | |
4398 | [[self navigationItem] setHidesBackButton:YES]; | |
4399 | [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack]; | |
4400 | ||
4401 | [self positionViews]; | |
4402 | } | |
4403 | ||
4404 | - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { | |
4405 | [self positionViews]; | |
4406 | } | |
4407 | ||
4408 | - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { | |
4409 | NSString *context([alert context]); | |
4410 | ||
4411 | if ([context isEqualToString:@"conffile"]) { | |
4412 | FILE *input = [database_ input]; | |
4413 | if (button == [alert cancelButtonIndex]) | |
4414 | fprintf(input, "N\n"); | |
4415 | else if (button == [alert firstOtherButtonIndex]) | |
4416 | fprintf(input, "Y\n"); | |
4417 | fflush(input); | |
4418 | } | |
4419 | } | |
4420 | ||
4421 | - (void) closeButtonPushed { | |
4422 | running_ = NO; | |
4423 | ||
4424 | UpdateExternalStatus(0); | |
4425 | ||
4426 | switch (Finish_) { | |
4427 | case 0: | |
4428 | [self dismissModalViewControllerAnimated:YES]; | |
4429 | break; | |
4430 | ||
4431 | case 1: | |
4432 | [delegate_ terminateWithSuccess]; | |
4433 | /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)]) | |
4434 | [delegate_ suspendWithAnimation:YES]; | |
4435 | else | |
4436 | [delegate_ suspend];*/ | |
4437 | break; | |
4438 | ||
4439 | case 2: | |
4440 | system("launchctl stop com.apple.SpringBoard"); | |
4441 | break; | |
4442 | ||
4443 | case 3: | |
4444 | system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_); | |
4445 | break; | |
4446 | ||
4447 | case 4: | |
4448 | system("reboot"); | |
4449 | break; | |
4450 | } | |
4451 | } | |
4452 | ||
4453 | - (void) _retachThread { | |
4454 | [[self navigationItem] setTitle:UCLocalize("COMPLETE")]; | |
4455 | ||
4456 | [[self view] addSubview:close_]; | |
4457 | [progress_ removeFromSuperview]; | |
4458 | [status_ removeFromSuperview]; | |
4459 | ||
4460 | [database_ popErrorWithTitle:title_]; | |
4461 | [delegate_ progressControllerIsComplete:self]; | |
4462 | ||
4463 | if (Finish_ < 4) { | |
4464 | FileFd file; | |
4465 | if (!file.Open(NotifyConfig_, FileFd::ReadOnly)) | |
4466 | _error->Discard(); | |
4467 | else { | |
4468 | MMap mmap(file, MMap::ReadOnly); | |
4469 | SHA1Summation sha1; | |
4470 | sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size()); | |
4471 | if (!(notifyconf_ == sha1.Result())) | |
4472 | Finish_ = 4; | |
4473 | } | |
4474 | } | |
4475 | ||
4476 | if (Finish_ < 3) { | |
4477 | FileFd file; | |
4478 | if (!file.Open(SpringBoard_, FileFd::ReadOnly)) | |
4479 | _error->Discard(); | |
4480 | else { | |
4481 | MMap mmap(file, MMap::ReadOnly); | |
4482 | SHA1Summation sha1; | |
4483 | sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size()); | |
4484 | if (!(springlist_ == sha1.Result())) | |
4485 | Finish_ = 3; | |
4486 | } | |
4487 | } | |
4488 | ||
4489 | switch (Finish_) { | |
4490 | case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */ | |
4491 | case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break; | |
4492 | case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break; | |
4493 | case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break; | |
4494 | case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break; | |
4495 | } | |
4496 | ||
4497 | system("su -c /usr/bin/uicache mobile"); | |
4498 | ||
4499 | UpdateExternalStatus(Finish_ == 0 ? 2 : 0); | |
4500 | ||
4501 | [delegate_ setStatusBarShowsProgress:NO]; | |
4502 | } | |
4503 | ||
4504 | - (void) _detachNewThreadData:(ProgressData *)data { _pooled | |
4505 | [[data target] performSelector:[data selector] withObject:[data object]]; | |
4506 | [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES]; | |
4507 | } | |
4508 | ||
4509 | - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title { | |
4510 | UpdateExternalStatus(1); | |
4511 | ||
4512 | if (title_ != nil) | |
4513 | [title_ release]; | |
4514 | if (title == nil) | |
4515 | title_ = nil; | |
4516 | else | |
4517 | title_ = [title retain]; | |
4518 | ||
4519 | [[self navigationItem] setTitle:title_]; | |
4520 | ||
4521 | [status_ setText:nil]; | |
4522 | [output_ setText:@""]; | |
4523 | [progress_ setProgress:0]; | |
4524 | ||
4525 | [close_ removeFromSuperview]; | |
4526 | [[self view] addSubview:progress_]; | |
4527 | [[self view] addSubview:status_]; | |
4528 | ||
4529 | [delegate_ setStatusBarShowsProgress:YES]; | |
4530 | running_ = YES; | |
4531 | ||
4532 | { | |
4533 | FileFd file; | |
4534 | if (!file.Open(NotifyConfig_, FileFd::ReadOnly)) | |
4535 | _error->Discard(); | |
4536 | else { | |
4537 | MMap mmap(file, MMap::ReadOnly); | |
4538 | SHA1Summation sha1; | |
4539 | sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size()); | |
4540 | notifyconf_ = sha1.Result(); | |
4541 | } | |
4542 | } | |
4543 | ||
4544 | { | |
4545 | FileFd file; | |
4546 | if (!file.Open(SpringBoard_, FileFd::ReadOnly)) | |
4547 | _error->Discard(); | |
4548 | else { | |
4549 | MMap mmap(file, MMap::ReadOnly); | |
4550 | SHA1Summation sha1; | |
4551 | sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size()); | |
4552 | springlist_ = sha1.Result(); | |
4553 | } | |
4554 | } | |
4555 | ||
4556 | [NSThread | |
4557 | detachNewThreadSelector:@selector(_detachNewThreadData:) | |
4558 | toTarget:self | |
4559 | withObject:[[[ProgressData alloc] | |
4560 | initWithSelector:selector | |
4561 | target:target | |
4562 | object:object | |
4563 | ] autorelease] | |
4564 | ]; | |
4565 | } | |
4566 | ||
4567 | - (void) repairWithSelector:(SEL)selector { | |
4568 | [self | |
4569 | detachNewThreadSelector:selector | |
4570 | toTarget:database_ | |
4571 | withObject:nil | |
4572 | title:UCLocalize("REPAIRING") | |
4573 | ]; | |
4574 | } | |
4575 | ||
4576 | - (void) setConfigurationData:(NSString *)data { | |
4577 | [self | |
4578 | performSelectorOnMainThread:@selector(_setConfigurationData:) | |
4579 | withObject:data | |
4580 | waitUntilDone:YES | |
4581 | ]; | |
4582 | } | |
4583 | ||
4584 | - (void) setProgressError:(NSString *)error withTitle:(NSString *)title { | |
4585 | CYActionSheet *sheet([[[CYActionSheet alloc] | |
4586 | initWithTitle:title | |
4587 | buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil] | |
4588 | defaultButtonIndex:0 | |
4589 | ] autorelease]); | |
4590 | ||
4591 | [sheet setMessage:error]; | |
4592 | [sheet yieldToPopupAlertAnimated:YES]; | |
4593 | [sheet dismiss]; | |
4594 | } | |
4595 | ||
4596 | - (void) setProgressTitle:(NSString *)title { | |
4597 | [self | |
4598 | performSelectorOnMainThread:@selector(_setProgressTitle:) | |
4599 | withObject:title | |
4600 | waitUntilDone:YES | |
4601 | ]; | |
4602 | } | |
4603 | ||
4604 | - (void) setProgressPercent:(float)percent { | |
4605 | [self | |
4606 | performSelectorOnMainThread:@selector(_setProgressPercent:) | |
4607 | withObject:[NSNumber numberWithFloat:percent] | |
4608 | waitUntilDone:YES | |
4609 | ]; | |
4610 | } | |
4611 | ||
4612 | - (void) startProgress { | |
4613 | } | |
4614 | ||
4615 | - (void) addProgressOutput:(NSString *)output { | |
4616 | [self | |
4617 | performSelectorOnMainThread:@selector(_addProgressOutput:) | |
4618 | withObject:output | |
4619 | waitUntilDone:YES | |
4620 | ]; | |
4621 | } | |
4622 | ||
4623 | - (bool) isCancelling:(size_t)received { | |
4624 | return false; | |
4625 | } | |
4626 | ||
4627 | - (void) _setConfigurationData:(NSString *)data { | |
4628 | static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$"); | |
4629 | ||
4630 | if (!conffile_r(data)) { | |
4631 | lprintf("E:invalid conffile\n"); | |
4632 | return; | |
4633 | } | |
4634 | ||
4635 | NSString *ofile = conffile_r[1]; | |
4636 | //NSString *nfile = conffile_r[2]; | |
4637 | ||
4638 | UIAlertView *alert = [[[UIAlertView alloc] | |
4639 | initWithTitle:UCLocalize("CONFIGURATION_UPGRADE") | |
4640 | message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile] | |
4641 | delegate:self | |
4642 | cancelButtonTitle:UCLocalize("KEEP_OLD_COPY") | |
4643 | otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"), | |
4644 | // XXX: UCLocalize("SEE_WHAT_CHANGED"), | |
4645 | nil | |
4646 | ] autorelease]; | |
4647 | ||
4648 | [alert setContext:@"conffile"]; | |
4649 | [alert show]; | |
4650 | } | |
4651 | ||
4652 | - (void) _setProgressTitle:(NSString *)title { | |
4653 | NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]); | |
4654 | for (size_t i(0), e([words count]); i != e; ++i) { | |
4655 | NSString *word([words objectAtIndex:i]); | |
4656 | if (Package *package = [database_ packageWithName:word]) | |
4657 | [words replaceObjectAtIndex:i withObject:[package name]]; | |
4658 | } | |
4659 | ||
4660 | [status_ setText:[words componentsJoinedByString:@" "]]; | |
4661 | } | |
4662 | ||
4663 | - (void) _setProgressPercent:(NSNumber *)percent { | |
4664 | [progress_ setProgress:[percent floatValue]]; | |
4665 | } | |
4666 | ||
4667 | - (void) _addProgressOutput:(NSString *)output { | |
4668 | [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]]; | |
4669 | CGSize size = [output_ contentSize]; | |
4670 | CGRect rect = {{0, size.height}, {size.width, 0}}; | |
4671 | [output_ scrollRectToVisible:rect animated:YES]; | |
4672 | } | |
4673 | ||
4674 | - (BOOL) isRunning { | |
4675 | return running_; | |
4676 | } | |
4677 | ||
4678 | @end | |
4679 | /* }}} */ | |
4680 | ||
4681 | /* Cell Content View {{{ */ | |
4682 | @protocol ContentDelegate | |
4683 | - (void) drawContentRect:(CGRect)rect; | |
4684 | @end | |
4685 | ||
4686 | @interface ContentView : UIView { | |
4687 | _transient id<ContentDelegate> delegate_; | |
4688 | } | |
4689 | ||
4690 | @end | |
4691 | ||
4692 | @implementation ContentView | |
4693 | ||
4694 | - (id) initWithFrame:(CGRect)frame { | |
4695 | if ((self = [super initWithFrame:frame]) != nil) { | |
4696 | [self setNeedsDisplayOnBoundsChange:YES]; | |
4697 | } return self; | |
4698 | } | |
4699 | ||
4700 | - (void) setDelegate:(id<ContentDelegate>)delegate { | |
4701 | delegate_ = delegate; | |
4702 | } | |
4703 | ||
4704 | - (void) drawRect:(CGRect)rect { | |
4705 | [super drawRect:rect]; | |
4706 | [delegate_ drawContentRect:rect]; | |
4707 | } | |
4708 | ||
4709 | @end | |
4710 | /* }}} */ | |
4711 | /* Cydia TableView Cell {{{ */ | |
4712 | @interface CYTableViewCell : UITableViewCell { | |
4713 | ContentView *content_; | |
4714 | bool highlighted_; | |
4715 | } | |
4716 | ||
4717 | @end | |
4718 | ||
4719 | @implementation CYTableViewCell | |
4720 | ||
4721 | - (void) dealloc { | |
4722 | [content_ release]; | |
4723 | [super dealloc]; | |
4724 | } | |
4725 | ||
4726 | - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted { | |
4727 | //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_); | |
4728 | ||
4729 | if (view == content_) { | |
4730 | //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_); | |
4731 | highlighted_ = highlighted; | |
4732 | } | |
4733 | ||
4734 | [super _updateHighlightColorsForView:view highlighted:highlighted]; | |
4735 | } | |
4736 | ||
4737 | - (void) setSelected:(BOOL)selected animated:(BOOL)animated { | |
4738 | //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO"); | |
4739 | highlighted_ = selected; | |
4740 | ||
4741 | [super setSelected:selected animated:animated]; | |
4742 | [content_ setNeedsDisplay]; | |
4743 | } | |
4744 | ||
4745 | @end | |
4746 | /* }}} */ | |
4747 | /* Package Cell {{{ */ | |
4748 | @interface PackageCell : CYTableViewCell < | |
4749 | ContentDelegate | |
4750 | > { | |
4751 | UIImage *icon_; | |
4752 | NSString *name_; | |
4753 | NSString *description_; | |
4754 | bool commercial_; | |
4755 | NSString *source_; | |
4756 | UIImage *badge_; | |
4757 | Package *package_; | |
4758 | UIImage *placard_; | |
4759 | } | |
4760 | ||
4761 | - (PackageCell *) init; | |
4762 | - (void) setPackage:(Package *)package; | |
4763 | ||
4764 | + (int) heightForPackage:(Package *)package; | |
4765 | - (void) drawContentRect:(CGRect)rect; | |
4766 | ||
4767 | @end | |
4768 | ||
4769 | @implementation PackageCell | |
4770 | ||
4771 | - (void) clearPackage { | |
4772 | if (icon_ != nil) { | |
4773 | [icon_ release]; | |
4774 | icon_ = nil; | |
4775 | } | |
4776 | ||
4777 | if (name_ != nil) { | |
4778 | [name_ release]; | |
4779 | name_ = nil; | |
4780 | } | |
4781 | ||
4782 | if (description_ != nil) { | |
4783 | [description_ release]; | |
4784 | description_ = nil; | |
4785 | } | |
4786 | ||
4787 | if (source_ != nil) { | |
4788 | [source_ release]; | |
4789 | source_ = nil; | |
4790 | } | |
4791 | ||
4792 | if (badge_ != nil) { | |
4793 | [badge_ release]; | |
4794 | badge_ = nil; | |
4795 | } | |
4796 | ||
4797 | if (placard_ != nil) { | |
4798 | [placard_ release]; | |
4799 | placard_ = nil; | |
4800 | } | |
4801 | ||
4802 | [package_ release]; | |
4803 | package_ = nil; | |
4804 | } | |
4805 | ||
4806 | - (void) dealloc { | |
4807 | [self clearPackage]; | |
4808 | [super dealloc]; | |
4809 | } | |
4810 | ||
4811 | - (PackageCell *) init { | |
4812 | CGRect frame(CGRectMake(0, 0, 320, 74)); | |
4813 | if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) { | |
4814 | UIView *content([self contentView]); | |
4815 | CGRect bounds([content bounds]); | |
4816 | ||
4817 | content_ = [[ContentView alloc] initWithFrame:bounds]; | |
4818 | [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
4819 | [content addSubview:content_]; | |
4820 | ||
4821 | [content_ setDelegate:self]; | |
4822 | [content_ setOpaque:YES]; | |
4823 | } return self; | |
4824 | } | |
4825 | ||
4826 | - (void) _setBackgroundColor { | |
4827 | UIColor *color; | |
4828 | if (NSString *mode = [package_ mode]) { | |
4829 | bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]); | |
4830 | color = remove ? RemovingColor_ : InstallingColor_; | |
4831 | } else | |
4832 | color = [UIColor whiteColor]; | |
4833 | ||
4834 | [content_ setBackgroundColor:color]; | |
4835 | [self setNeedsDisplay]; | |
4836 | } | |
4837 | ||
4838 | - (void) setPackage:(Package *)package { | |
4839 | [self clearPackage]; | |
4840 | [package parse]; | |
4841 | ||
4842 | Source *source = [package source]; | |
4843 | ||
4844 | icon_ = [[package icon] retain]; | |
4845 | name_ = [[package name] retain]; | |
4846 | ||
4847 | if (IsWildcat_) | |
4848 | description_ = [package longDescription]; | |
4849 | if (description_ == nil) | |
4850 | description_ = [package shortDescription]; | |
4851 | if (description_ != nil) | |
4852 | description_ = [description_ retain]; | |
4853 | ||
4854 | commercial_ = [package isCommercial]; | |
4855 | ||
4856 | package_ = [package retain]; | |
4857 | ||
4858 | NSString *label = nil; | |
4859 | bool trusted = false; | |
4860 | ||
4861 | if (source != nil) { | |
4862 | label = [source label]; | |
4863 | trusted = [source trusted]; | |
4864 | } else if ([[package id] isEqualToString:@"firmware"]) | |
4865 | label = UCLocalize("APPLE"); | |
4866 | else | |
4867 | label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")]; | |
4868 | ||
4869 | NSString *from(label); | |
4870 | ||
4871 | NSString *section = [package simpleSection]; | |
4872 | if (section != nil && ![section isEqualToString:label]) { | |
4873 | section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"]; | |
4874 | from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section]; | |
4875 | } | |
4876 | ||
4877 | from = [NSString stringWithFormat:UCLocalize("FROM"), from]; | |
4878 | source_ = [from retain]; | |
4879 | ||
4880 | if (NSString *purpose = [package primaryPurpose]) | |
4881 | if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil) | |
4882 | badge_ = [badge_ retain]; | |
4883 | ||
4884 | if ([package installed] != nil) | |
4885 | if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil) | |
4886 | placard_ = [placard_ retain]; | |
4887 | ||
4888 | [self _setBackgroundColor]; | |
4889 | [content_ setNeedsDisplay]; | |
4890 | } | |
4891 | ||
4892 | - (void) drawContentRect:(CGRect)rect { | |
4893 | bool highlighted(highlighted_); | |
4894 | float width([self bounds].size.width); | |
4895 | ||
4896 | #if 0 | |
4897 | CGContextRef context(UIGraphicsGetCurrentContext()); | |
4898 | [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set]; | |
4899 | CGContextFillRect(context, rect); | |
4900 | #endif | |
4901 | ||
4902 | if (icon_ != nil) { | |
4903 | CGRect rect; | |
4904 | rect.size = [icon_ size]; | |
4905 | ||
4906 | rect.size.width /= 2; | |
4907 | rect.size.height /= 2; | |
4908 | ||
4909 | rect.origin.x = 25 - rect.size.width / 2; | |
4910 | rect.origin.y = 25 - rect.size.height / 2; | |
4911 | ||
4912 | [icon_ drawInRect:rect]; | |
4913 | } | |
4914 | ||
4915 | if (badge_ != nil) { | |
4916 | CGSize size = [badge_ size]; | |
4917 | ||
4918 | [badge_ drawAtPoint:CGPointMake( | |
4919 | 36 - size.width / 2, | |
4920 | 36 - size.height / 2 | |
4921 | )]; | |
4922 | } | |
4923 | ||
4924 | if (highlighted) | |
4925 | UISetColor(White_); | |
4926 | ||
4927 | if (!highlighted) | |
4928 | UISetColor(commercial_ ? Purple_ : Black_); | |
4929 | [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation]; | |
4930 | [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation]; | |
4931 | ||
4932 | if (!highlighted) | |
4933 | UISetColor(commercial_ ? Purplish_ : Gray_); | |
4934 | [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation]; | |
4935 | ||
4936 | if (placard_ != nil) | |
4937 | [placard_ drawAtPoint:CGPointMake(width - 52, 9)]; | |
4938 | } | |
4939 | ||
4940 | + (int) heightForPackage:(Package *)package { | |
4941 | return 73; | |
4942 | } | |
4943 | ||
4944 | @end | |
4945 | /* }}} */ | |
4946 | /* Section Cell {{{ */ | |
4947 | @interface SectionCell : CYTableViewCell < | |
4948 | ContentDelegate | |
4949 | > { | |
4950 | NSString *basic_; | |
4951 | NSString *section_; | |
4952 | NSString *name_; | |
4953 | NSString *count_; | |
4954 | UIImage *icon_; | |
4955 | UISwitch *switch_; | |
4956 | BOOL editing_; | |
4957 | } | |
4958 | ||
4959 | - (void) setSection:(Section *)section editing:(BOOL)editing; | |
4960 | ||
4961 | @end | |
4962 | ||
4963 | @implementation SectionCell | |
4964 | ||
4965 | - (void) clearSection { | |
4966 | if (basic_ != nil) { | |
4967 | [basic_ release]; | |
4968 | basic_ = nil; | |
4969 | } | |
4970 | ||
4971 | if (section_ != nil) { | |
4972 | [section_ release]; | |
4973 | section_ = nil; | |
4974 | } | |
4975 | ||
4976 | if (name_ != nil) { | |
4977 | [name_ release]; | |
4978 | name_ = nil; | |
4979 | } | |
4980 | ||
4981 | if (count_ != nil) { | |
4982 | [count_ release]; | |
4983 | count_ = nil; | |
4984 | } | |
4985 | } | |
4986 | ||
4987 | - (void) dealloc { | |
4988 | [self clearSection]; | |
4989 | [icon_ release]; | |
4990 | [switch_ release]; | |
4991 | [super dealloc]; | |
4992 | } | |
4993 | ||
4994 | - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier { | |
4995 | if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) { | |
4996 | icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain]; | |
4997 | switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)]; | |
4998 | [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged]; | |
4999 | ||
5000 | UIView *content([self contentView]); | |
5001 | CGRect bounds([content bounds]); | |
5002 | ||
5003 | content_ = [[ContentView alloc] initWithFrame:bounds]; | |
5004 | [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
5005 | [content addSubview:content_]; | |
5006 | [content_ setBackgroundColor:[UIColor whiteColor]]; | |
5007 | ||
5008 | [content_ setDelegate:self]; | |
5009 | } return self; | |
5010 | } | |
5011 | ||
5012 | - (void) onSwitch:(id)sender { | |
5013 | NSMutableDictionary *metadata([Sections_ objectForKey:basic_]); | |
5014 | if (metadata == nil) { | |
5015 | metadata = [NSMutableDictionary dictionaryWithCapacity:2]; | |
5016 | [Sections_ setObject:metadata forKey:basic_]; | |
5017 | } | |
5018 | ||
5019 | [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"]; | |
5020 | Changed_ = true; | |
5021 | } | |
5022 | ||
5023 | - (void) setSection:(Section *)section editing:(BOOL)editing { | |
5024 | if (editing != editing_) { | |
5025 | if (editing_) | |
5026 | [switch_ removeFromSuperview]; | |
5027 | else | |
5028 | [self addSubview:switch_]; | |
5029 | editing_ = editing; | |
5030 | } | |
5031 | ||
5032 | [self clearSection]; | |
5033 | ||
5034 | if (section == nil) { | |
5035 | name_ = [UCLocalize("ALL_PACKAGES") retain]; | |
5036 | count_ = nil; | |
5037 | } else { | |
5038 | basic_ = [section name]; | |
5039 | if (basic_ != nil) | |
5040 | basic_ = [basic_ retain]; | |
5041 | ||
5042 | section_ = [section localized]; | |
5043 | if (section_ != nil) | |
5044 | section_ = [section_ retain]; | |
5045 | ||
5046 | name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain]; | |
5047 | count_ = [[NSString stringWithFormat:@"%d", [section count]] retain]; | |
5048 | ||
5049 | if (editing_) | |
5050 | [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO]; | |
5051 | } | |
5052 | ||
5053 | [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator]; | |
5054 | [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue]; | |
5055 | ||
5056 | [content_ setNeedsDisplay]; | |
5057 | } | |
5058 | ||
5059 | - (void) setFrame:(CGRect)frame { | |
5060 | [super setFrame:frame]; | |
5061 | ||
5062 | CGRect rect([switch_ frame]); | |
5063 | [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)]; | |
5064 | } | |
5065 | ||
5066 | - (void) drawContentRect:(CGRect)rect { | |
5067 | bool highlighted(highlighted_); | |
5068 | ||
5069 | [icon_ drawInRect:CGRectMake(8, 7, 32, 32)]; | |
5070 | ||
5071 | if (highlighted) | |
5072 | UISetColor(White_); | |
5073 | ||
5074 | float width(rect.size.width); | |
5075 | if (editing_) | |
5076 | width -= 87; | |
5077 | ||
5078 | if (!highlighted) | |
5079 | UISetColor(Black_); | |
5080 | [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation]; | |
5081 | ||
5082 | CGSize size = [count_ sizeWithFont:Font14_]; | |
5083 | ||
5084 | UISetColor(White_); | |
5085 | if (count_ != nil) | |
5086 | [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_]; | |
5087 | } | |
5088 | ||
5089 | @end | |
5090 | /* }}} */ | |
5091 | ||
5092 | /* File Table {{{ */ | |
5093 | @interface FileTable : CYViewController < | |
5094 | UITableViewDataSource, | |
5095 | UITableViewDelegate | |
5096 | > { | |
5097 | _transient Database *database_; | |
5098 | Package *package_; | |
5099 | NSString *name_; | |
5100 | NSMutableArray *files_; | |
5101 | UITableView *list_; | |
5102 | } | |
5103 | ||
5104 | - (id) initWithDatabase:(Database *)database; | |
5105 | - (void) setPackage:(Package *)package; | |
5106 | ||
5107 | @end | |
5108 | ||
5109 | @implementation FileTable | |
5110 | ||
5111 | - (void) dealloc { | |
5112 | if (package_ != nil) | |
5113 | [package_ release]; | |
5114 | if (name_ != nil) | |
5115 | [name_ release]; | |
5116 | [files_ release]; | |
5117 | [list_ release]; | |
5118 | [super dealloc]; | |
5119 | } | |
5120 | ||
5121 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
5122 | return files_ == nil ? 0 : [files_ count]; | |
5123 | } | |
5124 | ||
5125 | /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { | |
5126 | return 24.0f; | |
5127 | }*/ | |
5128 | ||
5129 | - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
5130 | static NSString *reuseIdentifier = @"Cell"; | |
5131 | ||
5132 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; | |
5133 | if (cell == nil) { | |
5134 | cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease]; | |
5135 | [cell setFont:[UIFont systemFontOfSize:16]]; | |
5136 | } | |
5137 | [cell setText:[files_ objectAtIndex:indexPath.row]]; | |
5138 | [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; | |
5139 | ||
5140 | return cell; | |
5141 | } | |
5142 | ||
5143 | - (id) initWithDatabase:(Database *)database { | |
5144 | if ((self = [super init]) != nil) { | |
5145 | database_ = database; | |
5146 | ||
5147 | [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")]; | |
5148 | ||
5149 | files_ = [[NSMutableArray arrayWithCapacity:32] retain]; | |
5150 | ||
5151 | list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]]; | |
5152 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
5153 | [list_ setRowHeight:24.0f]; | |
5154 | [[self view] addSubview:list_]; | |
5155 | ||
5156 | [list_ setDataSource:self]; | |
5157 | [list_ setDelegate:self]; | |
5158 | } return self; | |
5159 | } | |
5160 | ||
5161 | - (void) setPackage:(Package *)package { | |
5162 | if (package_ != nil) { | |
5163 | [package_ autorelease]; | |
5164 | package_ = nil; | |
5165 | } | |
5166 | ||
5167 | if (name_ != nil) { | |
5168 | [name_ release]; | |
5169 | name_ = nil; | |
5170 | } | |
5171 | ||
5172 | [files_ removeAllObjects]; | |
5173 | ||
5174 | if (package != nil) { | |
5175 | package_ = [package retain]; | |
5176 | name_ = [[package id] retain]; | |
5177 | ||
5178 | if (NSArray *files = [package files]) | |
5179 | [files_ addObjectsFromArray:files]; | |
5180 | ||
5181 | if ([files_ count] != 0) { | |
5182 | if ([[files_ objectAtIndex:0] isEqualToString:@"/."]) | |
5183 | [files_ removeObjectAtIndex:0]; | |
5184 | [files_ sortUsingSelector:@selector(compareByPath:)]; | |
5185 | ||
5186 | NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8]; | |
5187 | [stack addObject:@"/"]; | |
5188 | ||
5189 | for (int i(0), e([files_ count]); i != e; ++i) { | |
5190 | NSString *file = [files_ objectAtIndex:i]; | |
5191 | while (![file hasPrefix:[stack lastObject]]) | |
5192 | [stack removeLastObject]; | |
5193 | NSString *directory = [stack lastObject]; | |
5194 | [stack addObject:[file stringByAppendingString:@"/"]]; | |
5195 | [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@", | |
5196 | ([stack count] - 2) * 3, "", | |
5197 | [file substringFromIndex:[directory length]] | |
5198 | ]]; | |
5199 | } | |
5200 | } | |
5201 | } | |
5202 | ||
5203 | [list_ reloadData]; | |
5204 | } | |
5205 | ||
5206 | - (void) reloadData { | |
5207 | [self setPackage:[database_ packageWithName:name_]]; | |
5208 | } | |
5209 | ||
5210 | @end | |
5211 | /* }}} */ | |
5212 | /* Package Controller {{{ */ | |
5213 | @interface PackageController : CYBrowserController < | |
5214 | UIActionSheetDelegate | |
5215 | > { | |
5216 | _transient Database *database_; | |
5217 | Package *package_; | |
5218 | NSString *name_; | |
5219 | bool commercial_; | |
5220 | NSMutableArray *buttons_; | |
5221 | UIBarButtonItem *button_; | |
5222 | } | |
5223 | ||
5224 | - (id) initWithDatabase:(Database *)database; | |
5225 | - (void) setPackage:(Package *)package; | |
5226 | ||
5227 | @end | |
5228 | ||
5229 | @implementation PackageController | |
5230 | ||
5231 | - (void) dealloc { | |
5232 | if (package_ != nil) | |
5233 | [package_ release]; | |
5234 | if (name_ != nil) | |
5235 | [name_ release]; | |
5236 | ||
5237 | [buttons_ release]; | |
5238 | ||
5239 | if (button_ != nil) | |
5240 | [button_ release]; | |
5241 | ||
5242 | [super dealloc]; | |
5243 | } | |
5244 | ||
5245 | - (void) release { | |
5246 | if ([self retainCount] == 1) | |
5247 | [delegate_ setPackageController:self]; | |
5248 | [super release]; | |
5249 | } | |
5250 | ||
5251 | /* XXX: this is not safe at all... localization of /fail/ */ | |
5252 | - (void) _clickButtonWithName:(NSString *)name { | |
5253 | if ([name isEqualToString:UCLocalize("CLEAR")]) | |
5254 | [delegate_ clearPackage:package_]; | |
5255 | else if ([name isEqualToString:UCLocalize("INSTALL")]) | |
5256 | [delegate_ installPackage:package_]; | |
5257 | else if ([name isEqualToString:UCLocalize("REINSTALL")]) | |
5258 | [delegate_ installPackage:package_]; | |
5259 | else if ([name isEqualToString:UCLocalize("REMOVE")]) | |
5260 | [delegate_ removePackage:package_]; | |
5261 | else if ([name isEqualToString:UCLocalize("UPGRADE")]) | |
5262 | [delegate_ installPackage:package_]; | |
5263 | else _assert(false); | |
5264 | } | |
5265 | ||
5266 | - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button { | |
5267 | NSString *context([sheet context]); | |
5268 | ||
5269 | if ([context isEqualToString:@"modify"]) { | |
5270 | if (button != [sheet cancelButtonIndex]) { | |
5271 | NSString *buttonName = [buttons_ objectAtIndex:button]; | |
5272 | [self _clickButtonWithName:buttonName]; | |
5273 | } | |
5274 | ||
5275 | [sheet dismissWithClickedButtonIndex:-1 animated:YES]; | |
5276 | } | |
5277 | } | |
5278 | ||
5279 | - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame { | |
5280 | [super webView:view didClearWindowObject:window forFrame:frame]; | |
5281 | [window setValue:package_ forKey:@"package"]; | |
5282 | } | |
5283 | ||
5284 | - (bool) _allowJavaScriptPanel { | |
5285 | return commercial_; | |
5286 | } | |
5287 | ||
5288 | #if !AlwaysReload | |
5289 | - (void) _customButtonClicked { | |
5290 | int count([buttons_ count]); | |
5291 | if (count == 0) | |
5292 | return; | |
5293 | ||
5294 | if (count == 1) | |
5295 | [self _clickButtonWithName:[buttons_ objectAtIndex:0]]; | |
5296 | else { | |
5297 | NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count]; | |
5298 | [buttons addObjectsFromArray:buttons_]; | |
5299 | ||
5300 | UIActionSheet *sheet = [[[UIActionSheet alloc] | |
5301 | initWithTitle:nil | |
5302 | delegate:self | |
5303 | cancelButtonTitle:nil | |
5304 | destructiveButtonTitle:nil | |
5305 | otherButtonTitles:nil | |
5306 | ] autorelease]; | |
5307 | ||
5308 | for (NSString *button in buttons) [sheet addButtonWithTitle:button]; | |
5309 | if (!IsWildcat_) { | |
5310 | [sheet addButtonWithTitle:UCLocalize("CANCEL")]; | |
5311 | [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1]; | |
5312 | } | |
5313 | [sheet setContext:@"modify"]; | |
5314 | ||
5315 | [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]]; | |
5316 | } | |
5317 | } | |
5318 | ||
5319 | // We don't want to allow non-commercial packages to do custom things to the install button, | |
5320 | // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough. | |
5321 | - (void) customButtonClicked { | |
5322 | if (commercial_) | |
5323 | [super customButtonClicked]; | |
5324 | else | |
5325 | [self _customButtonClicked]; | |
5326 | } | |
5327 | ||
5328 | - (void) reloadButtonClicked { | |
5329 | // Don't reload a package view by clicking the button. | |
5330 | } | |
5331 | ||
5332 | - (void) applyLoadingTitle { | |
5333 | // Don't show "Loading" as the title. Ever. | |
5334 | } | |
5335 | ||
5336 | - (UIBarButtonItem *) rightButton { | |
5337 | return button_; | |
5338 | } | |
5339 | #endif | |
5340 | ||
5341 | - (id) initWithDatabase:(Database *)database { | |
5342 | if ((self = [super init]) != nil) { | |
5343 | database_ = database; | |
5344 | buttons_ = [[NSMutableArray alloc] initWithCapacity:4]; | |
5345 | [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]]; | |
5346 | } return self; | |
5347 | } | |
5348 | ||
5349 | - (void) setPackage:(Package *)package { | |
5350 | if (package_ != nil) { | |
5351 | [package_ autorelease]; | |
5352 | package_ = nil; | |
5353 | } | |
5354 | ||
5355 | if (name_ != nil) { | |
5356 | [name_ release]; | |
5357 | name_ = nil; | |
5358 | } | |
5359 | ||
5360 | [buttons_ removeAllObjects]; | |
5361 | ||
5362 | if (package != nil) { | |
5363 | [package parse]; | |
5364 | ||
5365 | package_ = [package retain]; | |
5366 | name_ = [[package id] retain]; | |
5367 | commercial_ = [package isCommercial]; | |
5368 | ||
5369 | if ([package_ mode] != nil) | |
5370 | [buttons_ addObject:UCLocalize("CLEAR")]; | |
5371 | if ([package_ source] == nil); | |
5372 | else if ([package_ upgradableAndEssential:NO]) | |
5373 | [buttons_ addObject:UCLocalize("UPGRADE")]; | |
5374 | else if ([package_ uninstalled]) | |
5375 | [buttons_ addObject:UCLocalize("INSTALL")]; | |
5376 | else | |
5377 | [buttons_ addObject:UCLocalize("REINSTALL")]; | |
5378 | if (![package_ uninstalled]) | |
5379 | [buttons_ addObject:UCLocalize("REMOVE")]; | |
5380 | } | |
5381 | ||
5382 | if (button_ != nil) | |
5383 | [button_ release]; | |
5384 | ||
5385 | NSString *title; | |
5386 | switch ([buttons_ count]) { | |
5387 | case 0: title = nil; break; | |
5388 | case 1: title = [buttons_ objectAtIndex:0]; break; | |
5389 | default: title = UCLocalize("MODIFY"); break; | |
5390 | } | |
5391 | ||
5392 | button_ = [[UIBarButtonItem alloc] | |
5393 | initWithTitle:title | |
5394 | style:UIBarButtonItemStylePlain | |
5395 | target:self | |
5396 | action:@selector(customButtonClicked) | |
5397 | ]; | |
5398 | ||
5399 | [self reloadURL]; | |
5400 | } | |
5401 | ||
5402 | - (bool) isLoading { | |
5403 | return commercial_ ? [super isLoading] : false; | |
5404 | } | |
5405 | ||
5406 | - (void) reloadData { | |
5407 | [self setPackage:[database_ packageWithName:name_]]; | |
5408 | } | |
5409 | ||
5410 | @end | |
5411 | /* }}} */ | |
5412 | /* Package Table {{{ */ | |
5413 | @interface PackageTable : UIView < | |
5414 | UITableViewDataSource, | |
5415 | UITableViewDelegate | |
5416 | > { | |
5417 | _transient Database *database_; | |
5418 | unsigned era_; | |
5419 | NSMutableArray *packages_; | |
5420 | NSMutableArray *sections_; | |
5421 | UITableView *list_; | |
5422 | NSMutableArray *index_; | |
5423 | NSMutableDictionary *indices_; | |
5424 | // XXX: this target_ seems to be delegate_. :( | |
5425 | _transient id target_; | |
5426 | SEL action_; | |
5427 | // XXX: why do we even have this delegate_? | |
5428 | _transient id delegate_; | |
5429 | } | |
5430 | ||
5431 | - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action; | |
5432 | ||
5433 | - (void) setDelegate:(id)delegate; | |
5434 | ||
5435 | - (void) reloadData; | |
5436 | - (void) resetCursor; | |
5437 | ||
5438 | - (UITableView *) list; | |
5439 | ||
5440 | - (void) setShouldHideHeaderInShortLists:(BOOL)hide; | |
5441 | ||
5442 | - (void) deselectWithAnimation:(BOOL)animated; | |
5443 | ||
5444 | @end | |
5445 | ||
5446 | @implementation PackageTable | |
5447 | ||
5448 | - (void) dealloc { | |
5449 | [packages_ release]; | |
5450 | [sections_ release]; | |
5451 | [list_ release]; | |
5452 | [index_ release]; | |
5453 | [indices_ release]; | |
5454 | ||
5455 | [super dealloc]; | |
5456 | } | |
5457 | ||
5458 | - (NSInteger) numberOfSectionsInTableView:(UITableView *)list { | |
5459 | NSInteger count([sections_ count]); | |
5460 | return count == 0 ? 1 : count; | |
5461 | } | |
5462 | ||
5463 | - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section { | |
5464 | if ([sections_ count] == 0) | |
5465 | return nil; | |
5466 | return [[sections_ objectAtIndex:section] name]; | |
5467 | } | |
5468 | ||
5469 | - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section { | |
5470 | if ([sections_ count] == 0) | |
5471 | return 0; | |
5472 | return [[sections_ objectAtIndex:section] count]; | |
5473 | } | |
5474 | ||
5475 | - (Package *) packageAtIndexPath:(NSIndexPath *)path { | |
5476 | @synchronized (database_) { | |
5477 | if ([database_ era] != era_) | |
5478 | return nil; | |
5479 | ||
5480 | Section *section([sections_ objectAtIndex:[path section]]); | |
5481 | NSInteger row([path row]); | |
5482 | Package *package([packages_ objectAtIndex:([section row] + row)]); | |
5483 | return [[package retain] autorelease]; | |
5484 | } } | |
5485 | ||
5486 | - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path { | |
5487 | PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]); | |
5488 | if (cell == nil) | |
5489 | cell = [[[PackageCell alloc] init] autorelease]; | |
5490 | [cell setPackage:[self packageAtIndexPath:path]]; | |
5491 | return cell; | |
5492 | } | |
5493 | ||
5494 | - (void) deselectWithAnimation:(BOOL)animated { | |
5495 | [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; | |
5496 | } | |
5497 | ||
5498 | /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path { | |
5499 | return [PackageCell heightForPackage:[self packageAtIndexPath:path]]; | |
5500 | }*/ | |
5501 | ||
5502 | - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path { | |
5503 | Package *package([self packageAtIndexPath:path]); | |
5504 | package = [database_ packageWithName:[package id]]; | |
5505 | [target_ performSelector:action_ withObject:package]; | |
5506 | return path; | |
5507 | } | |
5508 | ||
5509 | - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView { | |
5510 | return [packages_ count] > 20 ? index_ : nil; | |
5511 | } | |
5512 | ||
5513 | - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { | |
5514 | return index; | |
5515 | } | |
5516 | ||
5517 | - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action { | |
5518 | if ((self = [super initWithFrame:frame]) != nil) { | |
5519 | database_ = database; | |
5520 | ||
5521 | target_ = target; | |
5522 | action_ = action; | |
5523 | ||
5524 | index_ = [[NSMutableArray alloc] initWithCapacity:32]; | |
5525 | indices_ = [[NSMutableDictionary alloc] initWithCapacity:32]; | |
5526 | ||
5527 | packages_ = [[NSMutableArray arrayWithCapacity:16] retain]; | |
5528 | sections_ = [[NSMutableArray arrayWithCapacity:16] retain]; | |
5529 | ||
5530 | list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain]; | |
5531 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
5532 | [list_ setRowHeight:73.0f]; | |
5533 | [self addSubview:list_]; | |
5534 | ||
5535 | [list_ setDataSource:self]; | |
5536 | [list_ setDelegate:self]; | |
5537 | } return self; | |
5538 | } | |
5539 | ||
5540 | - (void) setDelegate:(id)delegate { | |
5541 | delegate_ = delegate; | |
5542 | } | |
5543 | ||
5544 | - (bool) hasPackage:(Package *)package { | |
5545 | return true; | |
5546 | } | |
5547 | ||
5548 | - (void) reloadData { | |
5549 | era_ = [database_ era]; | |
5550 | NSArray *packages = [database_ packages]; | |
5551 | ||
5552 | [packages_ removeAllObjects]; | |
5553 | [sections_ removeAllObjects]; | |
5554 | ||
5555 | _profile(PackageTable$reloadData$Filter) | |
5556 | for (Package *package in packages) | |
5557 | if ([self hasPackage:package]) | |
5558 | [packages_ addObject:package]; | |
5559 | _end | |
5560 | ||
5561 | [index_ removeAllObjects]; | |
5562 | [indices_ removeAllObjects]; | |
5563 | ||
5564 | Section *section = nil; | |
5565 | ||
5566 | _profile(PackageTable$reloadData$Section) | |
5567 | for (size_t offset(0), end([packages_ count]); offset != end; ++offset) { | |
5568 | Package *package; | |
5569 | unichar index; | |
5570 | ||
5571 | _profile(PackageTable$reloadData$Section$Package) | |
5572 | package = [packages_ objectAtIndex:offset]; | |
5573 | index = [package index]; | |
5574 | _end | |
5575 | ||
5576 | if (section == nil || [section index] != index) { | |
5577 | _profile(PackageTable$reloadData$Section$Allocate) | |
5578 | section = [[[Section alloc] initWithIndex:index row:offset] autorelease]; | |
5579 | _end | |
5580 | ||
5581 | [index_ addObject:[section name]]; | |
5582 | //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index]; | |
5583 | ||
5584 | _profile(PackageTable$reloadData$Section$Add) | |
5585 | [sections_ addObject:section]; | |
5586 | _end | |
5587 | } | |
5588 | ||
5589 | [section addToCount]; | |
5590 | } | |
5591 | _end | |
5592 | ||
5593 | _profile(PackageTable$reloadData$List) | |
5594 | [list_ reloadData]; | |
5595 | _end | |
5596 | } | |
5597 | ||
5598 | - (void) resetCursor { | |
5599 | [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO]; | |
5600 | } | |
5601 | ||
5602 | - (UITableView *) list { | |
5603 | return list_; | |
5604 | } | |
5605 | ||
5606 | - (void) setShouldHideHeaderInShortLists:(BOOL)hide { | |
5607 | //XXX:[list_ setShouldHideHeaderInShortLists:hide]; | |
5608 | } | |
5609 | ||
5610 | @end | |
5611 | /* }}} */ | |
5612 | /* Filtered Package Table {{{ */ | |
5613 | @interface FilteredPackageTable : PackageTable { | |
5614 | SEL filter_; | |
5615 | IMP imp_; | |
5616 | id object_; | |
5617 | } | |
5618 | ||
5619 | - (void) setObject:(id)object; | |
5620 | - (void) setObject:(id)object forFilter:(SEL)filter; | |
5621 | ||
5622 | - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object; | |
5623 | ||
5624 | @end | |
5625 | ||
5626 | @implementation FilteredPackageTable | |
5627 | ||
5628 | - (void) dealloc { | |
5629 | if (object_ != nil) | |
5630 | [object_ release]; | |
5631 | [super dealloc]; | |
5632 | } | |
5633 | ||
5634 | - (void) setFilter:(SEL)filter { | |
5635 | filter_ = filter; | |
5636 | ||
5637 | /* XXX: this is an unsafe optimization of doomy hell */ | |
5638 | Method method(class_getInstanceMethod([Package class], filter)); | |
5639 | _assert(method != NULL); | |
5640 | imp_ = method_getImplementation(method); | |
5641 | _assert(imp_ != NULL); | |
5642 | } | |
5643 | ||
5644 | - (void) setObject:(id)object { | |
5645 | if (object_ != nil) | |
5646 | [object_ release]; | |
5647 | if (object == nil) | |
5648 | object_ = nil; | |
5649 | else | |
5650 | object_ = [object retain]; | |
5651 | } | |
5652 | ||
5653 | - (void) setObject:(id)object forFilter:(SEL)filter { | |
5654 | [self setFilter:filter]; | |
5655 | [self setObject:object]; | |
5656 | } | |
5657 | ||
5658 | - (bool) hasPackage:(Package *)package { | |
5659 | _profile(FilteredPackageTable$hasPackage) | |
5660 | return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_); | |
5661 | _end | |
5662 | } | |
5663 | ||
5664 | - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object { | |
5665 | if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) { | |
5666 | [self setFilter:filter]; | |
5667 | object_ = [object retain]; | |
5668 | [self reloadData]; | |
5669 | } return self; | |
5670 | } | |
5671 | ||
5672 | @end | |
5673 | /* }}} */ | |
5674 | ||
5675 | /* Filtered Package Controller {{{ */ | |
5676 | @interface FilteredPackageController : CYViewController { | |
5677 | _transient Database *database_; | |
5678 | FilteredPackageTable *packages_; | |
5679 | NSString *title_; | |
5680 | } | |
5681 | ||
5682 | - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object; | |
5683 | ||
5684 | @end | |
5685 | ||
5686 | @implementation FilteredPackageController | |
5687 | ||
5688 | - (void) dealloc { | |
5689 | [packages_ release]; | |
5690 | [title_ release]; | |
5691 | ||
5692 | [super dealloc]; | |
5693 | } | |
5694 | ||
5695 | - (void) viewDidAppear:(BOOL)animated { | |
5696 | [super viewDidAppear:animated]; | |
5697 | [packages_ deselectWithAnimation:animated]; | |
5698 | } | |
5699 | ||
5700 | - (void) didSelectPackage:(Package *)package { | |
5701 | PackageController *view([delegate_ packageController]); | |
5702 | [view setPackage:package]; | |
5703 | [view setDelegate:delegate_]; | |
5704 | [[self navigationController] pushViewController:view animated:YES]; | |
5705 | } | |
5706 | ||
5707 | - (NSString *) title { return title_; } | |
5708 | ||
5709 | - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object { | |
5710 | if ((self = [super init]) != nil) { | |
5711 | database_ = database; | |
5712 | title_ = [title copy]; | |
5713 | [[self navigationItem] setTitle:title_]; | |
5714 | ||
5715 | packages_ = [[FilteredPackageTable alloc] | |
5716 | initWithFrame:[[self view] bounds] | |
5717 | database:database | |
5718 | target:self | |
5719 | action:@selector(didSelectPackage:) | |
5720 | filter:filter | |
5721 | with:object | |
5722 | ]; | |
5723 | ||
5724 | [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
5725 | [[self view] addSubview:packages_]; | |
5726 | } return self; | |
5727 | } | |
5728 | ||
5729 | - (void) reloadData { | |
5730 | [packages_ reloadData]; | |
5731 | } | |
5732 | ||
5733 | - (void) setDelegate:(id)delegate { | |
5734 | [super setDelegate:delegate]; | |
5735 | [packages_ setDelegate:delegate]; | |
5736 | } | |
5737 | ||
5738 | @end | |
5739 | ||
5740 | /* }}} */ | |
5741 | ||
5742 | /* Add Source Controller {{{ */ | |
5743 | @interface AddSourceController : CYViewController { | |
5744 | _transient Database *database_; | |
5745 | } | |
5746 | ||
5747 | - (id) initWithDatabase:(Database *)database; | |
5748 | ||
5749 | @end | |
5750 | ||
5751 | @implementation AddSourceController | |
5752 | ||
5753 | - (id) initWithDatabase:(Database *)database { | |
5754 | if ((self = [super init]) != nil) { | |
5755 | database_ = database; | |
5756 | } return self; | |
5757 | } | |
5758 | ||
5759 | @end | |
5760 | /* }}} */ | |
5761 | /* Source Cell {{{ */ | |
5762 | @interface SourceCell : CYTableViewCell < | |
5763 | ContentDelegate | |
5764 | > { | |
5765 | UIImage *icon_; | |
5766 | NSString *origin_; | |
5767 | NSString *description_; | |
5768 | NSString *label_; | |
5769 | } | |
5770 | ||
5771 | - (void) setSource:(Source *)source; | |
5772 | ||
5773 | @end | |
5774 | ||
5775 | @implementation SourceCell | |
5776 | ||
5777 | - (void) clearSource { | |
5778 | [icon_ release]; | |
5779 | [origin_ release]; | |
5780 | [description_ release]; | |
5781 | [label_ release]; | |
5782 | ||
5783 | icon_ = nil; | |
5784 | origin_ = nil; | |
5785 | description_ = nil; | |
5786 | label_ = nil; | |
5787 | } | |
5788 | ||
5789 | - (void) setSource:(Source *)source { | |
5790 | [self clearSource]; | |
5791 | ||
5792 | if (icon_ == nil) | |
5793 | icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]]; | |
5794 | if (icon_ == nil) | |
5795 | icon_ = [UIImage applicationImageNamed:@"unknown.png"]; | |
5796 | icon_ = [icon_ retain]; | |
5797 | ||
5798 | origin_ = [[source name] retain]; | |
5799 | label_ = [[source uri] retain]; | |
5800 | description_ = [[source description] retain]; | |
5801 | ||
5802 | [content_ setNeedsDisplay]; | |
5803 | } | |
5804 | ||
5805 | - (void) dealloc { | |
5806 | [self clearSource]; | |
5807 | [super dealloc]; | |
5808 | } | |
5809 | ||
5810 | - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier { | |
5811 | if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) { | |
5812 | UIView *content([self contentView]); | |
5813 | CGRect bounds([content bounds]); | |
5814 | ||
5815 | content_ = [[ContentView alloc] initWithFrame:bounds]; | |
5816 | [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
5817 | [content_ setBackgroundColor:[UIColor whiteColor]]; | |
5818 | [content addSubview:content_]; | |
5819 | ||
5820 | [content_ setDelegate:self]; | |
5821 | [content_ setOpaque:YES]; | |
5822 | } return self; | |
5823 | } | |
5824 | ||
5825 | - (void) drawContentRect:(CGRect)rect { | |
5826 | bool highlighted(highlighted_); | |
5827 | float width(rect.size.width); | |
5828 | ||
5829 | if (icon_ != nil) | |
5830 | [icon_ drawInRect:CGRectMake(10, 10, 30, 30)]; | |
5831 | ||
5832 | if (highlighted) | |
5833 | UISetColor(White_); | |
5834 | ||
5835 | if (!highlighted) | |
5836 | UISetColor(Black_); | |
5837 | [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation]; | |
5838 | ||
5839 | if (!highlighted) | |
5840 | UISetColor(Blue_); | |
5841 | [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation]; | |
5842 | ||
5843 | if (!highlighted) | |
5844 | UISetColor(Gray_); | |
5845 | [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation]; | |
5846 | } | |
5847 | ||
5848 | @end | |
5849 | /* }}} */ | |
5850 | /* Source Table {{{ */ | |
5851 | @interface SourceTable : CYViewController < | |
5852 | UITableViewDataSource, | |
5853 | UITableViewDelegate | |
5854 | > { | |
5855 | _transient Database *database_; | |
5856 | UITableView *list_; | |
5857 | NSMutableArray *sources_; | |
5858 | int offset_; | |
5859 | ||
5860 | NSString *href_; | |
5861 | UIProgressHUD *hud_; | |
5862 | NSError *error_; | |
5863 | ||
5864 | //NSURLConnection *installer_; | |
5865 | NSURLConnection *trivial_; | |
5866 | NSURLConnection *trivial_bz2_; | |
5867 | NSURLConnection *trivial_gz_; | |
5868 | //NSURLConnection *automatic_; | |
5869 | ||
5870 | BOOL cydia_; | |
5871 | } | |
5872 | ||
5873 | - (id) initWithDatabase:(Database *)database; | |
5874 | ||
5875 | - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated; | |
5876 | ||
5877 | @end | |
5878 | ||
5879 | @implementation SourceTable | |
5880 | ||
5881 | - (void) _releaseConnection:(NSURLConnection *)connection { | |
5882 | if (connection != nil) { | |
5883 | [connection cancel]; | |
5884 | //[connection setDelegate:nil]; | |
5885 | [connection release]; | |
5886 | } | |
5887 | } | |
5888 | ||
5889 | - (void) dealloc { | |
5890 | if (href_ != nil) | |
5891 | [href_ release]; | |
5892 | if (hud_ != nil) | |
5893 | [hud_ release]; | |
5894 | if (error_ != nil) | |
5895 | [error_ release]; | |
5896 | ||
5897 | //[self _releaseConnection:installer_]; | |
5898 | [self _releaseConnection:trivial_]; | |
5899 | [self _releaseConnection:trivial_gz_]; | |
5900 | [self _releaseConnection:trivial_bz2_]; | |
5901 | //[self _releaseConnection:automatic_]; | |
5902 | ||
5903 | [sources_ release]; | |
5904 | [list_ release]; | |
5905 | [super dealloc]; | |
5906 | } | |
5907 | ||
5908 | - (void) viewDidAppear:(BOOL)animated { | |
5909 | [super viewDidAppear:animated]; | |
5910 | [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; | |
5911 | } | |
5912 | ||
5913 | - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { | |
5914 | return offset_ == 0 ? 1 : 2; | |
5915 | } | |
5916 | ||
5917 | - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { | |
5918 | switch (section + (offset_ == 0 ? 1 : 0)) { | |
5919 | case 0: return UCLocalize("ENTERED_BY_USER"); | |
5920 | case 1: return UCLocalize("INSTALLED_BY_PACKAGE"); | |
5921 | ||
5922 | _nodefault | |
5923 | } | |
5924 | } | |
5925 | ||
5926 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
5927 | int count = [sources_ count]; | |
5928 | switch (section) { | |
5929 | case 0: return (offset_ == 0 ? count : offset_); | |
5930 | case 1: return count - offset_; | |
5931 | ||
5932 | _nodefault | |
5933 | } | |
5934 | } | |
5935 | ||
5936 | - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath { | |
5937 | unsigned idx = 0; | |
5938 | switch (indexPath.section) { | |
5939 | case 0: idx = indexPath.row; break; | |
5940 | case 1: idx = indexPath.row + offset_; break; | |
5941 | ||
5942 | _nodefault | |
5943 | } | |
5944 | return [sources_ objectAtIndex:idx]; | |
5945 | } | |
5946 | ||
5947 | - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { | |
5948 | Source *source = [self sourceAtIndexPath:indexPath]; | |
5949 | return [source description] == nil ? 56 : 73; | |
5950 | } | |
5951 | ||
5952 | - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
5953 | static NSString *cellIdentifier = @"SourceCell"; | |
5954 | ||
5955 | SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; | |
5956 | if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease]; | |
5957 | [cell setSource:[self sourceAtIndexPath:indexPath]]; | |
5958 | ||
5959 | return cell; | |
5960 | } | |
5961 | ||
5962 | - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath { | |
5963 | return UITableViewCellAccessoryDisclosureIndicator; | |
5964 | } | |
5965 | ||
5966 | - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { | |
5967 | Source *source = [self sourceAtIndexPath:indexPath]; | |
5968 | ||
5969 | FilteredPackageController *packages = [[[FilteredPackageController alloc] | |
5970 | initWithDatabase:database_ | |
5971 | title:[source label] | |
5972 | filter:@selector(isVisibleInSource:) | |
5973 | with:source | |
5974 | ] autorelease]; | |
5975 | ||
5976 | [packages setDelegate:delegate_]; | |
5977 | ||
5978 | [[self navigationController] pushViewController:packages animated:YES]; | |
5979 | } | |
5980 | ||
5981 | - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { | |
5982 | Source *source = [self sourceAtIndexPath:indexPath]; | |
5983 | return [source record] != nil; | |
5984 | } | |
5985 | ||
5986 | - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { | |
5987 | Source *source = [self sourceAtIndexPath:indexPath]; | |
5988 | [Sources_ removeObjectForKey:[source key]]; | |
5989 | [delegate_ syncData]; | |
5990 | } | |
5991 | ||
5992 | - (void) complete { | |
5993 | [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys: | |
5994 | @"deb", @"Type", | |
5995 | href_, @"URI", | |
5996 | @"./", @"Distribution", | |
5997 | nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]]; | |
5998 | ||
5999 | [delegate_ syncData]; | |
6000 | } | |
6001 | ||
6002 | - (NSString *) getWarning { | |
6003 | NSString *href(href_); | |
6004 | NSRange colon([href rangeOfString:@"://"]); | |
6005 | if (colon.location != NSNotFound) | |
6006 | href = [href substringFromIndex:(colon.location + 3)]; | |
6007 | href = [href stringByAddingPercentEscapes]; | |
6008 | href = [CydiaURL(@"api/repotag/") stringByAppendingString:href]; | |
6009 | href = [href stringByCachingURLWithCurrentCDN]; | |
6010 | ||
6011 | NSURL *url([NSURL URLWithString:href]); | |
6012 | ||
6013 | NSStringEncoding encoding; | |
6014 | NSError *error(nil); | |
6015 | ||
6016 | if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error]) | |
6017 | return [warning length] == 0 ? nil : warning; | |
6018 | return nil; | |
6019 | } | |
6020 | ||
6021 | - (void) _endConnection:(NSURLConnection *)connection { | |
6022 | // XXX: the memory management in this method is horribly awkward | |
6023 | ||
6024 | NSURLConnection **field = NULL; | |
6025 | if (connection == trivial_) | |
6026 | field = &trivial_; | |
6027 | else if (connection == trivial_bz2_) | |
6028 | field = &trivial_bz2_; | |
6029 | else if (connection == trivial_gz_) | |
6030 | field = &trivial_gz_; | |
6031 | _assert(field != NULL); | |
6032 | [connection release]; | |
6033 | *field = nil; | |
6034 | ||
6035 | if ( | |
6036 | trivial_ == nil && | |
6037 | trivial_bz2_ == nil && | |
6038 | trivial_gz_ == nil | |
6039 | ) { | |
6040 | bool defer(false); | |
6041 | ||
6042 | if (cydia_) { | |
6043 | if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) { | |
6044 | defer = true; | |
6045 | ||
6046 | UIAlertView *alert = [[[UIAlertView alloc] | |
6047 | initWithTitle:UCLocalize("SOURCE_WARNING") | |
6048 | message:warning | |
6049 | delegate:self | |
6050 | cancelButtonTitle:UCLocalize("CANCEL") | |
6051 | otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil | |
6052 | ] autorelease]; | |
6053 | ||
6054 | [alert setContext:@"warning"]; | |
6055 | [alert setNumberOfRows:1]; | |
6056 | [alert show]; | |
6057 | } else | |
6058 | [self complete]; | |
6059 | } else if (error_ != nil) { | |
6060 | UIAlertView *alert = [[[UIAlertView alloc] | |
6061 | initWithTitle:UCLocalize("VERIFICATION_ERROR") | |
6062 | message:[error_ localizedDescription] | |
6063 | delegate:self | |
6064 | cancelButtonTitle:UCLocalize("OK") | |
6065 | otherButtonTitles:nil | |
6066 | ] autorelease]; | |
6067 | ||
6068 | [alert setContext:@"urlerror"]; | |
6069 | [alert show]; | |
6070 | } else { | |
6071 | UIAlertView *alert = [[[UIAlertView alloc] | |
6072 | initWithTitle:UCLocalize("NOT_REPOSITORY") | |
6073 | message:UCLocalize("NOT_REPOSITORY_EX") | |
6074 | delegate:self | |
6075 | cancelButtonTitle:UCLocalize("OK") | |
6076 | otherButtonTitles:nil | |
6077 | ] autorelease]; | |
6078 | ||
6079 | [alert setContext:@"trivial"]; | |
6080 | [alert show]; | |
6081 | } | |
6082 | ||
6083 | [delegate_ setStatusBarShowsProgress:NO]; | |
6084 | [delegate_ removeProgressHUD:hud_]; | |
6085 | ||
6086 | [hud_ autorelease]; | |
6087 | hud_ = nil; | |
6088 | ||
6089 | if (!defer) { | |
6090 | [href_ release]; | |
6091 | href_ = nil; | |
6092 | } | |
6093 | ||
6094 | if (error_ != nil) { | |
6095 | [error_ release]; | |
6096 | error_ = nil; | |
6097 | } | |
6098 | } | |
6099 | } | |
6100 | ||
6101 | - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { | |
6102 | switch ([response statusCode]) { | |
6103 | case 200: | |
6104 | cydia_ = YES; | |
6105 | } | |
6106 | } | |
6107 | ||
6108 | - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { | |
6109 | lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]); | |
6110 | if (error_ != nil) | |
6111 | error_ = [error retain]; | |
6112 | [self _endConnection:connection]; | |
6113 | } | |
6114 | ||
6115 | - (void) connectionDidFinishLoading:(NSURLConnection *)connection { | |
6116 | [self _endConnection:connection]; | |
6117 | } | |
6118 | ||
6119 | - (NSString *) title { return UCLocalize("SOURCES"); } | |
6120 | ||
6121 | - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method { | |
6122 | NSMutableURLRequest *request = [NSMutableURLRequest | |
6123 | requestWithURL:[NSURL URLWithString:href] | |
6124 | cachePolicy:NSURLRequestUseProtocolCachePolicy | |
6125 | timeoutInterval:120.0 | |
6126 | ]; | |
6127 | ||
6128 | [request setHTTPMethod:method]; | |
6129 | ||
6130 | if (Machine_ != NULL) | |
6131 | [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"]; | |
6132 | if (UniqueID_ != nil) | |
6133 | [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"]; | |
6134 | if (Role_ != nil) | |
6135 | [request setValue:Role_ forHTTPHeaderField:@"X-Role"]; | |
6136 | ||
6137 | return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; | |
6138 | } | |
6139 | ||
6140 | - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { | |
6141 | NSString *context([alert context]); | |
6142 | ||
6143 | if ([context isEqualToString:@"source"]) { | |
6144 | switch (button) { | |
6145 | case 1: { | |
6146 | NSString *href = [[alert textField] text]; | |
6147 | ||
6148 | //installer_ = [[self _requestHRef:href method:@"GET"] retain]; | |
6149 | ||
6150 | if (![href hasSuffix:@"/"]) | |
6151 | href_ = [href stringByAppendingString:@"/"]; | |
6152 | else | |
6153 | href_ = href; | |
6154 | href_ = [href_ retain]; | |
6155 | ||
6156 | trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain]; | |
6157 | trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain]; | |
6158 | trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain]; | |
6159 | //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain]; | |
6160 | ||
6161 | cydia_ = false; | |
6162 | ||
6163 | // XXX: this is stupid | |
6164 | hud_ = [[delegate_ addProgressHUD] retain]; | |
6165 | [hud_ setText:UCLocalize("VERIFYING_URL")]; | |
6166 | } break; | |
6167 | ||
6168 | case 0: | |
6169 | break; | |
6170 | ||
6171 | _nodefault | |
6172 | } | |
6173 | ||
6174 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
6175 | } else if ([context isEqualToString:@"trivial"]) | |
6176 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
6177 | else if ([context isEqualToString:@"urlerror"]) | |
6178 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
6179 | else if ([context isEqualToString:@"warning"]) { | |
6180 | switch (button) { | |
6181 | case 1: | |
6182 | [self complete]; | |
6183 | break; | |
6184 | ||
6185 | case 0: | |
6186 | break; | |
6187 | ||
6188 | _nodefault | |
6189 | } | |
6190 | ||
6191 | [href_ release]; | |
6192 | href_ = nil; | |
6193 | ||
6194 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
6195 | } | |
6196 | } | |
6197 | ||
6198 | - (id) initWithDatabase:(Database *)database { | |
6199 | if ((self = [super init]) != nil) { | |
6200 | [[self navigationItem] setTitle:UCLocalize("SOURCES")]; | |
6201 | [self updateButtonsForEditingStatus:NO animated:NO]; | |
6202 | ||
6203 | database_ = database; | |
6204 | sources_ = [[NSMutableArray arrayWithCapacity:16] retain]; | |
6205 | ||
6206 | list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain]; | |
6207 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
6208 | [[self view] addSubview:list_]; | |
6209 | ||
6210 | [list_ setDataSource:self]; | |
6211 | [list_ setDelegate:self]; | |
6212 | ||
6213 | [self reloadData]; | |
6214 | } return self; | |
6215 | } | |
6216 | ||
6217 | - (void) reloadData { | |
6218 | pkgSourceList list; | |
6219 | if (!list.ReadMainList()) | |
6220 | return; | |
6221 | ||
6222 | [sources_ removeAllObjects]; | |
6223 | [sources_ addObjectsFromArray:[database_ sources]]; | |
6224 | _trace(); | |
6225 | [sources_ sortUsingSelector:@selector(compareByNameAndType:)]; | |
6226 | _trace(); | |
6227 | ||
6228 | int count([sources_ count]); | |
6229 | offset_ = 0; | |
6230 | for (int i = 0; i != count; i++) { | |
6231 | if ([[sources_ objectAtIndex:i] record] == nil) | |
6232 | break; | |
6233 | offset_++; | |
6234 | } | |
6235 | ||
6236 | [list_ setEditing:NO]; | |
6237 | [self updateButtonsForEditingStatus:NO animated:NO]; | |
6238 | [list_ reloadData]; | |
6239 | } | |
6240 | ||
6241 | - (void) addButtonClicked { | |
6242 | /*[book_ pushPage:[[[AddSourceController alloc] | |
6243 | initWithBook:book_ | |
6244 | database:database_ | |
6245 | ] autorelease]];*/ | |
6246 | ||
6247 | UIAlertView *alert = [[[UIAlertView alloc] | |
6248 | initWithTitle:UCLocalize("ENTER_APT_URL") | |
6249 | message:nil | |
6250 | delegate:self | |
6251 | cancelButtonTitle:UCLocalize("CANCEL") | |
6252 | otherButtonTitles:UCLocalize("ADD_SOURCE"), nil | |
6253 | ] autorelease]; | |
6254 | ||
6255 | [alert setContext:@"source"]; | |
6256 | [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)]; | |
6257 | ||
6258 | [alert setNumberOfRows:1]; | |
6259 | [alert addTextFieldWithValue:@"http://" label:@""]; | |
6260 | ||
6261 | UITextInputTraits *traits = [[alert textField] textInputTraits]; | |
6262 | [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone]; | |
6263 | [traits setAutocorrectionType:UITextAutocorrectionTypeNo]; | |
6264 | [traits setKeyboardType:UIKeyboardTypeURL]; | |
6265 | // XXX: UIReturnKeyDone | |
6266 | [traits setReturnKeyType:UIReturnKeyNext]; | |
6267 | ||
6268 | [alert show]; | |
6269 | } | |
6270 | ||
6271 | - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated { | |
6272 | [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc] | |
6273 | initWithTitle:UCLocalize("ADD") | |
6274 | style:UIBarButtonItemStylePlain | |
6275 | target:self | |
6276 | action:@selector(addButtonClicked) | |
6277 | ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated]; | |
6278 | ||
6279 | [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] | |
6280 | initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT")) | |
6281 | style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain) | |
6282 | target:self | |
6283 | action:@selector(editButtonClicked) | |
6284 | ] autorelease] animated:animated]; | |
6285 | ||
6286 | if (IsWildcat_ && !editing) | |
6287 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
6288 | initWithTitle:UCLocalize("SETTINGS") | |
6289 | style:UIBarButtonItemStylePlain | |
6290 | target:self | |
6291 | action:@selector(settingsButtonClicked) | |
6292 | ] autorelease]]; | |
6293 | } | |
6294 | ||
6295 | - (void) settingsButtonClicked { | |
6296 | [delegate_ showSettings]; | |
6297 | } | |
6298 | ||
6299 | - (void) editButtonClicked { | |
6300 | [list_ setEditing:![list_ isEditing] animated:YES]; | |
6301 | ||
6302 | [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES]; | |
6303 | } | |
6304 | ||
6305 | @end | |
6306 | /* }}} */ | |
6307 | ||
6308 | /* Installed Controller {{{ */ | |
6309 | @interface InstalledController : FilteredPackageController { | |
6310 | BOOL expert_; | |
6311 | } | |
6312 | ||
6313 | - (id) initWithDatabase:(Database *)database; | |
6314 | ||
6315 | - (void) updateRoleButton; | |
6316 | - (void) queueStatusDidChange; | |
6317 | ||
6318 | @end | |
6319 | ||
6320 | @implementation InstalledController | |
6321 | ||
6322 | - (void) dealloc { | |
6323 | [super dealloc]; | |
6324 | } | |
6325 | ||
6326 | - (NSString *) title { return UCLocalize("INSTALLED"); } | |
6327 | ||
6328 | - (id) initWithDatabase:(Database *)database { | |
6329 | if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) { | |
6330 | [self updateRoleButton]; | |
6331 | [self queueStatusDidChange]; | |
6332 | } return self; | |
6333 | } | |
6334 | ||
6335 | #if !AlwaysReload | |
6336 | - (void) queueButtonClicked { | |
6337 | [delegate_ queue]; | |
6338 | } | |
6339 | #endif | |
6340 | ||
6341 | - (void) queueStatusDidChange { | |
6342 | #if !AlwaysReload | |
6343 | if (IsWildcat_) { | |
6344 | if (Queuing_) { | |
6345 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
6346 | initWithTitle:UCLocalize("QUEUE") | |
6347 | style:UIBarButtonItemStyleDone | |
6348 | target:self | |
6349 | action:@selector(queueButtonClicked) | |
6350 | ] autorelease]]; | |
6351 | } else { | |
6352 | [[self navigationItem] setLeftBarButtonItem:nil]; | |
6353 | } | |
6354 | } | |
6355 | #endif | |
6356 | } | |
6357 | ||
6358 | - (void) reloadData { | |
6359 | [packages_ reloadData]; | |
6360 | } | |
6361 | ||
6362 | - (void) updateRoleButton { | |
6363 | if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) | |
6364 | [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] | |
6365 | initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")) | |
6366 | style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain) | |
6367 | target:self | |
6368 | action:@selector(roleButtonClicked) | |
6369 | ] autorelease]]; | |
6370 | } | |
6371 | ||
6372 | - (void) roleButtonClicked { | |
6373 | [packages_ setObject:[NSNumber numberWithBool:expert_]]; | |
6374 | [packages_ reloadData]; | |
6375 | expert_ = !expert_; | |
6376 | ||
6377 | [self updateRoleButton]; | |
6378 | } | |
6379 | ||
6380 | - (void) setDelegate:(id)delegate { | |
6381 | [super setDelegate:delegate]; | |
6382 | [packages_ setDelegate:delegate]; | |
6383 | } | |
6384 | ||
6385 | @end | |
6386 | /* }}} */ | |
6387 | ||
6388 | /* Home Controller {{{ */ | |
6389 | @interface HomeController : CYBrowserController { | |
6390 | } | |
6391 | ||
6392 | @end | |
6393 | ||
6394 | @implementation HomeController | |
6395 | ||
6396 | - (void) _setMoreHeaders:(NSMutableURLRequest *)request { | |
6397 | [super _setMoreHeaders:request]; | |
6398 | ||
6399 | if (ChipID_ != nil) | |
6400 | [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"]; | |
6401 | if (UniqueID_ != nil) | |
6402 | [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"]; | |
6403 | if (PLMN_ != nil) | |
6404 | [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"]; | |
6405 | } | |
6406 | ||
6407 | - (void) aboutButtonClicked { | |
6408 | UIAlertView *alert([[[UIAlertView alloc] init] autorelease]); | |
6409 | ||
6410 | [alert setTitle:UCLocalize("ABOUT_CYDIA")]; | |
6411 | [alert addButtonWithTitle:UCLocalize("CLOSE")]; | |
6412 | [alert setCancelButtonIndex:0]; | |
6413 | ||
6414 | [alert setMessage: | |
6415 | @"Copyright (C) 2008-2010\n" | |
6416 | "Jay Freeman (saurik)\n" | |
6417 | "saurik@saurik.com\n" | |
6418 | "http://www.saurik.com/" | |
6419 | ]; | |
6420 | ||
6421 | [alert show]; | |
6422 | } | |
6423 | ||
6424 | - (void) viewWillAppear:(BOOL)animated { | |
6425 | [super viewWillAppear:animated]; | |
6426 | //[[self navigationController] setNavigationBarHidden:YES animated:animated]; | |
6427 | } | |
6428 | ||
6429 | - (void) viewWillDisappear:(BOOL)animated { | |
6430 | [super viewWillDisappear:animated]; | |
6431 | //[[self navigationController] setNavigationBarHidden:NO animated:animated]; | |
6432 | } | |
6433 | ||
6434 | - (id) init { | |
6435 | if ((self = [super init]) != nil) { | |
6436 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
6437 | initWithTitle:UCLocalize("ABOUT") | |
6438 | style:UIBarButtonItemStylePlain | |
6439 | target:self | |
6440 | action:@selector(aboutButtonClicked) | |
6441 | ] autorelease]]; | |
6442 | } return self; | |
6443 | } | |
6444 | ||
6445 | @end | |
6446 | /* }}} */ | |
6447 | /* Manage Controller {{{ */ | |
6448 | @interface ManageController : CYBrowserController { | |
6449 | } | |
6450 | ||
6451 | - (void) queueStatusDidChange; | |
6452 | @end | |
6453 | ||
6454 | @implementation ManageController | |
6455 | ||
6456 | - (id) init { | |
6457 | if ((self = [super init]) != nil) { | |
6458 | [[self navigationItem] setTitle:UCLocalize("MANAGE")]; | |
6459 | ||
6460 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
6461 | initWithTitle:UCLocalize("SETTINGS") | |
6462 | style:UIBarButtonItemStylePlain | |
6463 | target:self | |
6464 | action:@selector(settingsButtonClicked) | |
6465 | ] autorelease]]; | |
6466 | ||
6467 | [self queueStatusDidChange]; | |
6468 | } return self; | |
6469 | } | |
6470 | ||
6471 | - (void) settingsButtonClicked { | |
6472 | [delegate_ showSettings]; | |
6473 | } | |
6474 | ||
6475 | #if !AlwaysReload | |
6476 | - (void) queueButtonClicked { | |
6477 | [delegate_ queue]; | |
6478 | } | |
6479 | ||
6480 | - (void) applyLoadingTitle { | |
6481 | // No "Loading" title. | |
6482 | } | |
6483 | ||
6484 | - (void) applyRightButton { | |
6485 | // No right button. | |
6486 | } | |
6487 | #endif | |
6488 | ||
6489 | - (void) queueStatusDidChange { | |
6490 | #if !AlwaysReload | |
6491 | if (!IsWildcat_ && Queuing_) { | |
6492 | [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] | |
6493 | initWithTitle:UCLocalize("QUEUE") | |
6494 | style:UIBarButtonItemStyleDone | |
6495 | target:self | |
6496 | action:@selector(queueButtonClicked) | |
6497 | ] autorelease]]; | |
6498 | } else { | |
6499 | [[self navigationItem] setRightBarButtonItem:nil]; | |
6500 | } | |
6501 | #endif | |
6502 | } | |
6503 | ||
6504 | - (bool) isLoading { | |
6505 | return false; | |
6506 | } | |
6507 | ||
6508 | @end | |
6509 | /* }}} */ | |
6510 | ||
6511 | /* Refresh Bar {{{ */ | |
6512 | @interface RefreshBar : UINavigationBar { | |
6513 | UIProgressIndicator *indicator_; | |
6514 | UITextLabel *prompt_; | |
6515 | UIProgressBar *progress_; | |
6516 | UINavigationButton *cancel_; | |
6517 | } | |
6518 | ||
6519 | @end | |
6520 | ||
6521 | @implementation RefreshBar | |
6522 | ||
6523 | - (void) dealloc { | |
6524 | [indicator_ release]; | |
6525 | [prompt_ release]; | |
6526 | [progress_ release]; | |
6527 | [cancel_ release]; | |
6528 | [super dealloc]; | |
6529 | } | |
6530 | ||
6531 | - (void) positionViews { | |
6532 | CGRect frame = [cancel_ frame]; | |
6533 | frame.origin.x = [self frame].size.width - frame.size.width - 5; | |
6534 | frame.origin.y = ([self frame].size.height - frame.size.height) / 2; | |
6535 | [cancel_ setFrame:frame]; | |
6536 | ||
6537 | CGSize prgsize = {75, 100}; | |
6538 | CGRect prgrect = {{ | |
6539 | [self frame].size.width - prgsize.width - 10, | |
6540 | ([self frame].size.height - prgsize.height) / 2 | |
6541 | } , prgsize}; | |
6542 | [progress_ setFrame:prgrect]; | |
6543 | ||
6544 | CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]); | |
6545 | unsigned indoffset = ([self frame].size.height - indsize.height) / 2; | |
6546 | CGRect indrect = {{indoffset, indoffset}, indsize}; | |
6547 | [indicator_ setFrame:indrect]; | |
6548 | ||
6549 | CGSize prmsize = {215, indsize.height + 4}; | |
6550 | CGRect prmrect = {{ | |
6551 | indoffset * 2 + indsize.width, | |
6552 | unsigned([self frame].size.height - prmsize.height) / 2 - 1 | |
6553 | }, prmsize}; | |
6554 | [prompt_ setFrame:prmrect]; | |
6555 | } | |
6556 | ||
6557 | - (void)setFrame:(CGRect)frame { | |
6558 | [super setFrame:frame]; | |
6559 | ||
6560 | [self positionViews]; | |
6561 | } | |
6562 | ||
6563 | - (id) initWithFrame:(CGRect)frame delegate:(id)delegate { | |
6564 | if ((self = [super initWithFrame:frame])) { | |
6565 | [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth]; | |
6566 | ||
6567 | [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]]; | |
6568 | [self setBarStyle:UIBarStyleBlack]; | |
6569 | ||
6570 | UIBarStyle barstyle([self _barStyle:NO]); | |
6571 | bool ugly(barstyle == UIBarStyleDefault); | |
6572 | ||
6573 | UIProgressIndicatorStyle style = ugly ? | |
6574 | UIProgressIndicatorStyleMediumBrown : | |
6575 | UIProgressIndicatorStyleMediumWhite; | |
6576 | ||
6577 | indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero]; | |
6578 | [indicator_ setStyle:style]; | |
6579 | [indicator_ startAnimation]; | |
6580 | [self addSubview:indicator_]; | |
6581 | ||
6582 | prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero]; | |
6583 | [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]]; | |
6584 | [prompt_ setBackgroundColor:[UIColor clearColor]]; | |
6585 | [prompt_ setFont:[UIFont systemFontOfSize:15]]; | |
6586 | [self addSubview:prompt_]; | |
6587 | ||
6588 | progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero]; | |
6589 | [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin]; | |
6590 | [progress_ setStyle:0]; | |
6591 | [self addSubview:progress_]; | |
6592 | ||
6593 | cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted]; | |
6594 | [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; | |
6595 | [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside]; | |
6596 | [cancel_ setBarStyle:barstyle]; | |
6597 | ||
6598 | [self positionViews]; | |
6599 | } return self; | |
6600 | } | |
6601 | ||
6602 | - (void) cancel { | |
6603 | [cancel_ removeFromSuperview]; | |
6604 | } | |
6605 | ||
6606 | - (void) start { | |
6607 | [prompt_ setText:UCLocalize("UPDATING_DATABASE")]; | |
6608 | [progress_ setProgress:0]; | |
6609 | [self addSubview:cancel_]; | |
6610 | } | |
6611 | ||
6612 | - (void) stop { | |
6613 | [cancel_ removeFromSuperview]; | |
6614 | } | |
6615 | ||
6616 | - (void) setPrompt:(NSString *)prompt { | |
6617 | [prompt_ setText:prompt]; | |
6618 | } | |
6619 | ||
6620 | - (void) setProgress:(float)progress { | |
6621 | [progress_ setProgress:progress]; | |
6622 | } | |
6623 | ||
6624 | @end | |
6625 | /* }}} */ | |
6626 | ||
6627 | @class CYNavigationController; | |
6628 | ||
6629 | /* Cydia Tab Bar Controller {{{ */ | |
6630 | @interface CYTabBarController : UITabBarController < | |
6631 | ProgressDelegate | |
6632 | > { | |
6633 | _transient Database *database_; | |
6634 | RefreshBar *refreshbar_; | |
6635 | ||
6636 | bool dropped_; | |
6637 | bool updating_; | |
6638 | // XXX: ok, "updatedelegate_"?... | |
6639 | _transient NSObject<CydiaDelegate> *updatedelegate_; | |
6640 | ||
6641 | id root_; | |
6642 | } | |
6643 | ||
6644 | - (void) dropBar:(BOOL)animated; | |
6645 | - (void) beginUpdate; | |
6646 | - (void) raiseBar:(BOOL)animated; | |
6647 | - (BOOL) updating; | |
6648 | ||
6649 | @end | |
6650 | ||
6651 | @implementation CYTabBarController | |
6652 | ||
6653 | /* XXX: some logic should probably go here related to | |
6654 | freeing the view controllers on tab change */ | |
6655 | ||
6656 | - (void) reloadData { | |
6657 | size_t count([[self viewControllers] count]); | |
6658 | for (size_t i(0); i != count; ++i) { | |
6659 | CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]); | |
6660 | [page reloadData]; | |
6661 | } | |
6662 | } | |
6663 | ||
6664 | - (id) initWithDatabase:(Database *)database { | |
6665 | if ((self = [super init]) != nil) { | |
6666 | database_ = database; | |
6667 | ||
6668 | [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
6669 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil]; | |
6670 | ||
6671 | refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self]; | |
6672 | } return self; | |
6673 | } | |
6674 | ||
6675 | - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation { | |
6676 | return IsWildcat_ || orientation == UIInterfaceOrientationPortrait; | |
6677 | } | |
6678 | ||
6679 | - (void) setUpdate:(NSDate *)date { | |
6680 | [self beginUpdate]; | |
6681 | } | |
6682 | ||
6683 | - (void) beginUpdate { | |
6684 | [self dropBar:YES]; | |
6685 | [refreshbar_ start]; | |
6686 | ||
6687 | updating_ = true; | |
6688 | ||
6689 | [NSThread | |
6690 | detachNewThreadSelector:@selector(performUpdate) | |
6691 | toTarget:self | |
6692 | withObject:nil | |
6693 | ]; | |
6694 | } | |
6695 | ||
6696 | - (void) performUpdate { _pooled | |
6697 | Status status; | |
6698 | status.setDelegate(self); | |
6699 | [database_ updateWithStatus:status]; | |
6700 | ||
6701 | [self | |
6702 | performSelectorOnMainThread:@selector(completeUpdate) | |
6703 | withObject:nil | |
6704 | waitUntilDone:NO | |
6705 | ]; | |
6706 | } | |
6707 | ||
6708 | - (void) completeUpdate { | |
6709 | if (!updating_) | |
6710 | return; | |
6711 | updating_ = false; | |
6712 | ||
6713 | [self raiseBar:YES]; | |
6714 | [refreshbar_ stop]; | |
6715 | [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0]; | |
6716 | } | |
6717 | ||
6718 | - (void) cancelUpdate { | |
6719 | updating_ = false; | |
6720 | [self raiseBar:YES]; | |
6721 | [refreshbar_ stop]; | |
6722 | [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0]; | |
6723 | } | |
6724 | ||
6725 | - (void) cancelPressed { | |
6726 | [self cancelUpdate]; | |
6727 | } | |
6728 | ||
6729 | - (BOOL) updating { | |
6730 | return updating_; | |
6731 | } | |
6732 | ||
6733 | - (void) setProgressError:(NSString *)error withTitle:(NSString *)title { | |
6734 | [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]]; | |
6735 | } | |
6736 | ||
6737 | - (void) startProgress { | |
6738 | } | |
6739 | ||
6740 | - (void) setProgressTitle:(NSString *)title { | |
6741 | [self | |
6742 | performSelectorOnMainThread:@selector(_setProgressTitle:) | |
6743 | withObject:title | |
6744 | waitUntilDone:YES | |
6745 | ]; | |
6746 | } | |
6747 | ||
6748 | - (bool) isCancelling:(size_t)received { | |
6749 | return !updating_; | |
6750 | } | |
6751 | ||
6752 | - (void) setProgressPercent:(float)percent { | |
6753 | [self | |
6754 | performSelectorOnMainThread:@selector(_setProgressPercent:) | |
6755 | withObject:[NSNumber numberWithFloat:percent] | |
6756 | waitUntilDone:YES | |
6757 | ]; | |
6758 | } | |
6759 | ||
6760 | - (void) addProgressOutput:(NSString *)output { | |
6761 | [self | |
6762 | performSelectorOnMainThread:@selector(_addProgressOutput:) | |
6763 | withObject:output | |
6764 | waitUntilDone:YES | |
6765 | ]; | |
6766 | } | |
6767 | ||
6768 | - (void) _setProgressTitle:(NSString *)title { | |
6769 | [refreshbar_ setPrompt:title]; | |
6770 | } | |
6771 | ||
6772 | - (void) _setProgressPercent:(NSNumber *)percent { | |
6773 | [refreshbar_ setProgress:[percent floatValue]]; | |
6774 | } | |
6775 | ||
6776 | - (void) _addProgressOutput:(NSString *)output { | |
6777 | } | |
6778 | ||
6779 | - (void) setUpdateDelegate:(id)delegate { | |
6780 | updatedelegate_ = delegate; | |
6781 | } | |
6782 | ||
6783 | - (CGFloat) statusBarHeight { | |
6784 | if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) { | |
6785 | return [[UIApplication sharedApplication] statusBarFrame].size.height; | |
6786 | } else { | |
6787 | return [[UIApplication sharedApplication] statusBarFrame].size.width; | |
6788 | } | |
6789 | } | |
6790 | ||
6791 | - (UIView *) transitionView { | |
6792 | if ([self respondsToSelector:@selector(_transitionView)]) | |
6793 | return [self _transitionView]; | |
6794 | else | |
6795 | return MSHookIvar<id>(self, "_viewControllerTransitionView"); | |
6796 | } | |
6797 | ||
6798 | - (void) dropBar:(BOOL)animated { | |
6799 | if (dropped_) | |
6800 | return; | |
6801 | dropped_ = true; | |
6802 | ||
6803 | UIView *transition([self transitionView]); | |
6804 | [[self view] addSubview:refreshbar_]; | |
6805 | ||
6806 | CGRect barframe([refreshbar_ frame]); | |
6807 | ||
6808 | if (false) // XXX: _UIApplicationLinkedOnOrAfter(4) | |
6809 | barframe.origin.y = [self statusBarHeight]; | |
6810 | else | |
6811 | barframe.origin.y = 0; | |
6812 | ||
6813 | [refreshbar_ setFrame:barframe]; | |
6814 | ||
6815 | if (animated) | |
6816 | [UIView beginAnimations:nil context:NULL]; | |
6817 | ||
6818 | CGRect viewframe = [transition frame]; | |
6819 | viewframe.origin.y += barframe.size.height; | |
6820 | viewframe.size.height -= barframe.size.height; | |
6821 | [transition setFrame:viewframe]; | |
6822 | ||
6823 | if (animated) | |
6824 | [UIView commitAnimations]; | |
6825 | ||
6826 | // Ensure bar has the proper width for our view, it might have changed | |
6827 | barframe.size.width = viewframe.size.width; | |
6828 | [refreshbar_ setFrame:barframe]; | |
6829 | ||
6830 | // XXX: fix Apple's layout bug | |
6831 | [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; | |
6832 | } | |
6833 | ||
6834 | - (void) raiseBar:(BOOL)animated { | |
6835 | if (!dropped_) | |
6836 | return; | |
6837 | dropped_ = false; | |
6838 | ||
6839 | UIView *transition([self transitionView]); | |
6840 | [refreshbar_ removeFromSuperview]; | |
6841 | ||
6842 | CGRect barframe([refreshbar_ frame]); | |
6843 | ||
6844 | if (animated) | |
6845 | [UIView beginAnimations:nil context:NULL]; | |
6846 | ||
6847 | CGRect viewframe = [transition frame]; | |
6848 | viewframe.origin.y -= barframe.size.height; | |
6849 | viewframe.size.height += barframe.size.height; | |
6850 | [transition setFrame:viewframe]; | |
6851 | ||
6852 | if (animated) | |
6853 | [UIView commitAnimations]; | |
6854 | ||
6855 | // XXX: fix Apple's layout bug | |
6856 | // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; | |
6857 | } | |
6858 | ||
6859 | #if 0 | |
6860 | - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration { | |
6861 | // XXX: fix Apple's layout bug | |
6862 | // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; | |
6863 | } | |
6864 | #endif | |
6865 | ||
6866 | - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { | |
6867 | bool dropped(dropped_); | |
6868 | ||
6869 | if (dropped) | |
6870 | [self raiseBar:NO]; | |
6871 | ||
6872 | [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; | |
6873 | ||
6874 | if (dropped) | |
6875 | [self dropBar:NO]; | |
6876 | ||
6877 | // XXX: fix Apple's layout bug | |
6878 | // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation]; | |
6879 | } | |
6880 | ||
6881 | - (void) statusBarFrameChanged:(NSNotification *)notification { | |
6882 | if (dropped_) { | |
6883 | [self raiseBar:NO]; | |
6884 | [self dropBar:NO]; | |
6885 | } | |
6886 | } | |
6887 | ||
6888 | - (void) dealloc { | |
6889 | [refreshbar_ release]; | |
6890 | [[NSNotificationCenter defaultCenter] removeObserver:self]; | |
6891 | [super dealloc]; | |
6892 | } | |
6893 | ||
6894 | @end | |
6895 | /* }}} */ | |
6896 | ||
6897 | /* Cydia Navigation Controller {{{ */ | |
6898 | @interface CYNavigationController : UINavigationController { | |
6899 | _transient Database *database_; | |
6900 | _transient id<UINavigationControllerDelegate> delegate_; | |
6901 | } | |
6902 | ||
6903 | - (id) initWithDatabase:(Database *)database; | |
6904 | - (void) reloadData; | |
6905 | ||
6906 | @end | |
6907 | ||
6908 | ||
6909 | @implementation CYNavigationController | |
6910 | ||
6911 | - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation { | |
6912 | // Inherit autorotation settings for modal parents. | |
6913 | if ([self parentViewController] && [[self parentViewController] modalViewController] == self) { | |
6914 | return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation]; | |
6915 | } else { | |
6916 | return [super shouldAutorotateToInterfaceOrientation:orientation]; | |
6917 | } | |
6918 | } | |
6919 | ||
6920 | - (void) dealloc { | |
6921 | [super dealloc]; | |
6922 | } | |
6923 | ||
6924 | - (void) reloadData { | |
6925 | size_t count([[self viewControllers] count]); | |
6926 | for (size_t i(0); i != count; ++i) { | |
6927 | CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]); | |
6928 | [page reloadData]; | |
6929 | } | |
6930 | } | |
6931 | ||
6932 | - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate { | |
6933 | delegate_ = delegate; | |
6934 | } | |
6935 | ||
6936 | - (id) initWithDatabase:(Database *)database { | |
6937 | if ((self = [super init]) != nil) { | |
6938 | database_ = database; | |
6939 | } return self; | |
6940 | } | |
6941 | ||
6942 | @end | |
6943 | /* }}} */ | |
6944 | /* Cydia:// Protocol {{{ */ | |
6945 | @interface CydiaURLProtocol : NSURLProtocol { | |
6946 | } | |
6947 | ||
6948 | @end | |
6949 | ||
6950 | @implementation CydiaURLProtocol | |
6951 | ||
6952 | + (BOOL) canInitWithRequest:(NSURLRequest *)request { | |
6953 | NSURL *url([request URL]); | |
6954 | if (url == nil) | |
6955 | return NO; | |
6956 | NSString *scheme([[url scheme] lowercaseString]); | |
6957 | if (scheme == nil || ![scheme isEqualToString:@"cydia"]) | |
6958 | return NO; | |
6959 | return YES; | |
6960 | } | |
6961 | ||
6962 | + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request { | |
6963 | return request; | |
6964 | } | |
6965 | ||
6966 | - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request { | |
6967 | id<NSURLProtocolClient> client([self client]); | |
6968 | if (icon == nil) | |
6969 | [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]]; | |
6970 | else { | |
6971 | NSData *data(UIImagePNGRepresentation(icon)); | |
6972 | ||
6973 | NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]); | |
6974 | [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; | |
6975 | [client URLProtocol:self didLoadData:data]; | |
6976 | [client URLProtocolDidFinishLoading:self]; | |
6977 | } | |
6978 | } | |
6979 | ||
6980 | - (void) startLoading { | |
6981 | id<NSURLProtocolClient> client([self client]); | |
6982 | NSURLRequest *request([self request]); | |
6983 | ||
6984 | NSURL *url([request URL]); | |
6985 | NSString *href([url absoluteString]); | |
6986 | ||
6987 | NSString *path([href substringFromIndex:8]); | |
6988 | NSRange slash([path rangeOfString:@"/"]); | |
6989 | ||
6990 | NSString *command; | |
6991 | if (slash.location == NSNotFound) { | |
6992 | command = path; | |
6993 | path = nil; | |
6994 | } else { | |
6995 | command = [path substringToIndex:slash.location]; | |
6996 | path = [path substringFromIndex:(slash.location + 1)]; | |
6997 | } | |
6998 | ||
6999 | Database *database([Database sharedInstance]); | |
7000 | ||
7001 | if ([command isEqualToString:@"package-icon"]) { | |
7002 | if (path == nil) | |
7003 | goto fail; | |
7004 | path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
7005 | Package *package([database packageWithName:path]); | |
7006 | if (package == nil) | |
7007 | goto fail; | |
7008 | UIImage *icon([package icon]); | |
7009 | [self _returnPNGWithImage:icon forRequest:request]; | |
7010 | } else if ([command isEqualToString:@"source-icon"]) { | |
7011 | if (path == nil) | |
7012 | goto fail; | |
7013 | path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
7014 | NSString *source(Simplify(path)); | |
7015 | UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]); | |
7016 | if (icon == nil) | |
7017 | icon = [UIImage applicationImageNamed:@"unknown.png"]; | |
7018 | [self _returnPNGWithImage:icon forRequest:request]; | |
7019 | } else if ([command isEqualToString:@"uikit-image"]) { | |
7020 | if (path == nil) | |
7021 | goto fail; | |
7022 | path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
7023 | UIImage *icon(_UIImageWithName(path)); | |
7024 | [self _returnPNGWithImage:icon forRequest:request]; | |
7025 | } else if ([command isEqualToString:@"section-icon"]) { | |
7026 | if (path == nil) | |
7027 | goto fail; | |
7028 | path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
7029 | NSString *section(Simplify(path)); | |
7030 | UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]); | |
7031 | if (icon == nil) | |
7032 | icon = [UIImage applicationImageNamed:@"unknown.png"]; | |
7033 | [self _returnPNGWithImage:icon forRequest:request]; | |
7034 | } else fail: { | |
7035 | [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]]; | |
7036 | } | |
7037 | } | |
7038 | ||
7039 | - (void) stopLoading { | |
7040 | } | |
7041 | ||
7042 | @end | |
7043 | /* }}} */ | |
7044 | ||
7045 | /* Sections Controller {{{ */ | |
7046 | @interface SectionsController : CYViewController < | |
7047 | UITableViewDataSource, | |
7048 | UITableViewDelegate | |
7049 | > { | |
7050 | _transient Database *database_; | |
7051 | NSMutableArray *sections_; | |
7052 | NSMutableArray *filtered_; | |
7053 | UITableView *list_; | |
7054 | UIView *accessory_; | |
7055 | BOOL editing_; | |
7056 | } | |
7057 | ||
7058 | - (id) initWithDatabase:(Database *)database; | |
7059 | - (void) reloadData; | |
7060 | - (void) resetView; | |
7061 | ||
7062 | - (void) editButtonClicked; | |
7063 | ||
7064 | @end | |
7065 | ||
7066 | @implementation SectionsController | |
7067 | ||
7068 | - (void) dealloc { | |
7069 | [list_ setDataSource:nil]; | |
7070 | [list_ setDelegate:nil]; | |
7071 | ||
7072 | [sections_ release]; | |
7073 | [filtered_ release]; | |
7074 | [list_ release]; | |
7075 | [accessory_ release]; | |
7076 | [super dealloc]; | |
7077 | } | |
7078 | ||
7079 | - (void) viewDidAppear:(BOOL)animated { | |
7080 | [super viewDidAppear:animated]; | |
7081 | [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; | |
7082 | } | |
7083 | ||
7084 | - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath { | |
7085 | Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)])); | |
7086 | return section; | |
7087 | } | |
7088 | ||
7089 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
7090 | return editing_ ? [sections_ count] : [filtered_ count] + 1; | |
7091 | } | |
7092 | ||
7093 | /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { | |
7094 | return 45.0f; | |
7095 | }*/ | |
7096 | ||
7097 | - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
7098 | static NSString *reuseIdentifier = @"SectionCell"; | |
7099 | ||
7100 | SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; | |
7101 | if (cell == nil) | |
7102 | cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease]; | |
7103 | ||
7104 | [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_]; | |
7105 | ||
7106 | return cell; | |
7107 | } | |
7108 | ||
7109 | - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { | |
7110 | if (editing_) | |
7111 | return; | |
7112 | ||
7113 | Section *section = [self sectionAtIndexPath:indexPath]; | |
7114 | NSString *name = [section name]; | |
7115 | NSString *title; | |
7116 | ||
7117 | if ([indexPath row] == 0) { | |
7118 | section = nil; | |
7119 | name = nil; | |
7120 | title = UCLocalize("ALL_PACKAGES"); | |
7121 | } else { | |
7122 | if (name != nil) { | |
7123 | name = [NSString stringWithString:name]; | |
7124 | title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"]; | |
7125 | } else { | |
7126 | name = @""; | |
7127 | title = UCLocalize("NO_SECTION"); | |
7128 | } | |
7129 | } | |
7130 | ||
7131 | FilteredPackageController *table = [[[FilteredPackageController alloc] | |
7132 | initWithDatabase:database_ | |
7133 | title:title | |
7134 | filter:@selector(isVisibleInSection:) | |
7135 | with:name | |
7136 | ] autorelease]; | |
7137 | ||
7138 | [table setDelegate:delegate_]; | |
7139 | ||
7140 | [[self navigationController] pushViewController:table animated:YES]; | |
7141 | } | |
7142 | ||
7143 | - (NSString *) title { return UCLocalize("SECTIONS"); } | |
7144 | ||
7145 | - (id) initWithDatabase:(Database *)database { | |
7146 | if ((self = [super init]) != nil) { | |
7147 | database_ = database; | |
7148 | ||
7149 | [[self navigationItem] setTitle:UCLocalize("SECTIONS")]; | |
7150 | ||
7151 | sections_ = [[NSMutableArray arrayWithCapacity:16] retain]; | |
7152 | filtered_ = [[NSMutableArray arrayWithCapacity:16] retain]; | |
7153 | ||
7154 | list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]]; | |
7155 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
7156 | [list_ setRowHeight:45.0f]; | |
7157 | [[self view] addSubview:list_]; | |
7158 | ||
7159 | [list_ setDataSource:self]; | |
7160 | [list_ setDelegate:self]; | |
7161 | ||
7162 | [self reloadData]; | |
7163 | } return self; | |
7164 | } | |
7165 | ||
7166 | - (void) reloadData { | |
7167 | NSArray *packages = [database_ packages]; | |
7168 | ||
7169 | [sections_ removeAllObjects]; | |
7170 | [filtered_ removeAllObjects]; | |
7171 | ||
7172 | NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]); | |
7173 | ||
7174 | _trace(); | |
7175 | for (Package *package in packages) { | |
7176 | NSString *name([package section]); | |
7177 | NSString *key(name == nil ? @"" : name); | |
7178 | ||
7179 | Section *section; | |
7180 | ||
7181 | _profile(SectionsView$reloadData$Section) | |
7182 | section = [sections objectForKey:key]; | |
7183 | if (section == nil) { | |
7184 | _profile(SectionsView$reloadData$Section$Allocate) | |
7185 | section = [[[Section alloc] initWithName:name localize:YES] autorelease]; | |
7186 | [sections setObject:section forKey:key]; | |
7187 | _end | |
7188 | } | |
7189 | _end | |
7190 | ||
7191 | [section addToCount]; | |
7192 | ||
7193 | _profile(SectionsView$reloadData$Filter) | |
7194 | if (![package valid] || ![package visible]) | |
7195 | continue; | |
7196 | _end | |
7197 | ||
7198 | [section addToRow]; | |
7199 | } | |
7200 | _trace(); | |
7201 | ||
7202 | [sections_ addObjectsFromArray:[sections allValues]]; | |
7203 | ||
7204 | [sections_ sortUsingSelector:@selector(compareByLocalized:)]; | |
7205 | ||
7206 | for (Section *section in sections_) { | |
7207 | size_t count([section row]); | |
7208 | if (count == 0) | |
7209 | continue; | |
7210 | ||
7211 | section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease]; | |
7212 | [section setCount:count]; | |
7213 | [filtered_ addObject:section]; | |
7214 | } | |
7215 | ||
7216 | [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] | |
7217 | initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT")) | |
7218 | style:UIBarButtonItemStylePlain | |
7219 | target:self | |
7220 | action:@selector(editButtonClicked) | |
7221 | ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)]; | |
7222 | ||
7223 | [list_ reloadData]; | |
7224 | _trace(); | |
7225 | } | |
7226 | ||
7227 | - (void) resetView { | |
7228 | if (editing_) | |
7229 | [self editButtonClicked]; | |
7230 | } | |
7231 | ||
7232 | - (void) editButtonClicked { | |
7233 | if ((editing_ = !editing_)) | |
7234 | [list_ reloadData]; | |
7235 | else | |
7236 | [delegate_ updateData]; | |
7237 | ||
7238 | [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")]; | |
7239 | [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")]; | |
7240 | [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain]; | |
7241 | } | |
7242 | ||
7243 | - (UIView *) accessoryView { | |
7244 | return accessory_; | |
7245 | } | |
7246 | ||
7247 | @end | |
7248 | /* }}} */ | |
7249 | /* Changes Controller {{{ */ | |
7250 | @interface ChangesController : CYViewController < | |
7251 | UITableViewDataSource, | |
7252 | UITableViewDelegate | |
7253 | > { | |
7254 | _transient Database *database_; | |
7255 | unsigned era_; | |
7256 | CFMutableArrayRef packages_; | |
7257 | NSMutableArray *sections_; | |
7258 | UITableView *list_; | |
7259 | unsigned upgrades_; | |
7260 | BOOL hasSentFirstLoad_; | |
7261 | } | |
7262 | ||
7263 | - (id) initWithDatabase:(Database *)database delegate:(id)delegate; | |
7264 | - (void) reloadData; | |
7265 | ||
7266 | @end | |
7267 | ||
7268 | @implementation ChangesController | |
7269 | ||
7270 | - (void) dealloc { | |
7271 | [list_ setDelegate:nil]; | |
7272 | [list_ setDataSource:nil]; | |
7273 | ||
7274 | CFRelease(packages_); | |
7275 | ||
7276 | [sections_ release]; | |
7277 | [list_ release]; | |
7278 | [super dealloc]; | |
7279 | } | |
7280 | ||
7281 | - (void) viewDidAppear:(BOOL)animated { | |
7282 | [super viewDidAppear:animated]; | |
7283 | if (!hasSentFirstLoad_) { | |
7284 | hasSentFirstLoad_ = YES; | |
7285 | [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0]; | |
7286 | } else { | |
7287 | [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; | |
7288 | } | |
7289 | } | |
7290 | ||
7291 | - (NSInteger) numberOfSectionsInTableView:(UITableView *)list { | |
7292 | NSInteger count([sections_ count]); | |
7293 | return count == 0 ? 1 : count; | |
7294 | } | |
7295 | ||
7296 | - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section { | |
7297 | if ([sections_ count] == 0) | |
7298 | return nil; | |
7299 | return [[sections_ objectAtIndex:section] name]; | |
7300 | } | |
7301 | ||
7302 | - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section { | |
7303 | if ([sections_ count] == 0) | |
7304 | return 0; | |
7305 | return [[sections_ objectAtIndex:section] count]; | |
7306 | } | |
7307 | ||
7308 | - (Package *) packageAtIndex:(NSUInteger)index { | |
7309 | return (Package *) CFArrayGetValueAtIndex(packages_, index); | |
7310 | } | |
7311 | ||
7312 | - (Package *) packageAtIndexPath:(NSIndexPath *)path { | |
7313 | @synchronized (database_) { | |
7314 | if ([database_ era] != era_) | |
7315 | return nil; | |
7316 | ||
7317 | Section *section([sections_ objectAtIndex:[path section]]); | |
7318 | NSInteger row([path row]); | |
7319 | return [[[self packageAtIndex:([section row] + row)] retain] autorelease]; | |
7320 | } } | |
7321 | ||
7322 | - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path { | |
7323 | PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]); | |
7324 | if (cell == nil) | |
7325 | cell = [[[PackageCell alloc] init] autorelease]; | |
7326 | [cell setPackage:[self packageAtIndexPath:path]]; | |
7327 | return cell; | |
7328 | } | |
7329 | ||
7330 | /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path { | |
7331 | return [PackageCell heightForPackage:[self packageAtIndexPath:path]]; | |
7332 | }*/ | |
7333 | ||
7334 | - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path { | |
7335 | Package *package([self packageAtIndexPath:path]); | |
7336 | PackageController *view([delegate_ packageController]); | |
7337 | [view setDelegate:delegate_]; | |
7338 | [view setPackage:package]; | |
7339 | [[self navigationController] pushViewController:view animated:YES]; | |
7340 | return path; | |
7341 | } | |
7342 | ||
7343 | - (void) refreshButtonClicked { | |
7344 | [delegate_ beginUpdate]; | |
7345 | [[self navigationItem] setLeftBarButtonItem:nil animated:YES]; | |
7346 | } | |
7347 | ||
7348 | - (void) upgradeButtonClicked { | |
7349 | [delegate_ distUpgrade]; | |
7350 | } | |
7351 | ||
7352 | - (NSString *) title { return UCLocalize("CHANGES"); } | |
7353 | ||
7354 | - (id) initWithDatabase:(Database *)database delegate:(id)delegate { | |
7355 | if ((self = [super init]) != nil) { | |
7356 | database_ = database; | |
7357 | [[self navigationItem] setTitle:UCLocalize("CHANGES")]; | |
7358 | ||
7359 | packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL); | |
7360 | ||
7361 | sections_ = [[NSMutableArray arrayWithCapacity:16] retain]; | |
7362 | ||
7363 | list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain]; | |
7364 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
7365 | [list_ setRowHeight:73.0f]; | |
7366 | [[self view] addSubview:list_]; | |
7367 | ||
7368 | [list_ setDataSource:self]; | |
7369 | [list_ setDelegate:self]; | |
7370 | ||
7371 | delegate_ = delegate; | |
7372 | } return self; | |
7373 | } | |
7374 | ||
7375 | - (void) _reloadPackages:(NSArray *)packages { | |
7376 | _trace(); | |
7377 | for (Package *package in packages) | |
7378 | if ([package upgradableAndEssential:YES] || [package visible]) | |
7379 | CFArrayAppendValue(packages_, package); | |
7380 | ||
7381 | _trace(); | |
7382 | [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL]; | |
7383 | _trace(); | |
7384 | } | |
7385 | ||
7386 | - (void) reloadData { | |
7387 | era_ = [database_ era]; | |
7388 | NSArray *packages = [database_ packages]; | |
7389 | ||
7390 | CFArrayRemoveAllValues(packages_); | |
7391 | ||
7392 | [sections_ removeAllObjects]; | |
7393 | ||
7394 | #if 1 | |
7395 | UIProgressHUD *hud([delegate_ addProgressHUD]); | |
7396 | [hud setText:UCLocalize("LOADING")]; | |
7397 | //NSLog(@"HUD:%@::%@", delegate_, hud); | |
7398 | [self yieldToSelector:@selector(_reloadPackages:) withObject:packages]; | |
7399 | [delegate_ removeProgressHUD:hud]; | |
7400 | #else | |
7401 | [self _reloadPackages:packages]; | |
7402 | #endif | |
7403 | ||
7404 | Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease]; | |
7405 | Section *ignored = nil; | |
7406 | Section *section = nil; | |
7407 | time_t last = 0; | |
7408 | ||
7409 | upgrades_ = 0; | |
7410 | bool unseens = false; | |
7411 | ||
7412 | CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle)); | |
7413 | ||
7414 | for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) { | |
7415 | Package *package = [self packageAtIndex:offset]; | |
7416 | ||
7417 | BOOL uae = [package upgradableAndEssential:YES]; | |
7418 | ||
7419 | if (!uae) { | |
7420 | unseens = true; | |
7421 | time_t seen([package seen]); | |
7422 | ||
7423 | if (section == nil || last != seen) { | |
7424 | last = seen; | |
7425 | ||
7426 | NSString *name; | |
7427 | name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]); | |
7428 | [name autorelease]; | |
7429 | ||
7430 | _profile(ChangesController$reloadData$Allocate) | |
7431 | name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name]; | |
7432 | section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease]; | |
7433 | [sections_ addObject:section]; | |
7434 | _end | |
7435 | } | |
7436 | ||
7437 | [section addToCount]; | |
7438 | } else if ([package ignored]) { | |
7439 | if (ignored == nil) { | |
7440 | ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease]; | |
7441 | } | |
7442 | [ignored addToCount]; | |
7443 | } else { | |
7444 | ++upgrades_; | |
7445 | [upgradable addToCount]; | |
7446 | } | |
7447 | } | |
7448 | _trace(); | |
7449 | ||
7450 | CFRelease(formatter); | |
7451 | ||
7452 | if (unseens) { | |
7453 | Section *last = [sections_ lastObject]; | |
7454 | size_t count = [last count]; | |
7455 | CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0); | |
7456 | [sections_ removeLastObject]; | |
7457 | } | |
7458 | ||
7459 | if ([ignored count] != 0) | |
7460 | [sections_ insertObject:ignored atIndex:0]; | |
7461 | if (upgrades_ != 0) | |
7462 | [sections_ insertObject:upgradable atIndex:0]; | |
7463 | ||
7464 | [list_ reloadData]; | |
7465 | ||
7466 | if (upgrades_ > 0) | |
7467 | [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] | |
7468 | initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]] | |
7469 | style:UIBarButtonItemStylePlain | |
7470 | target:self | |
7471 | action:@selector(upgradeButtonClicked) | |
7472 | ] autorelease]]; | |
7473 | ||
7474 | if (![delegate_ updating]) | |
7475 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
7476 | initWithTitle:UCLocalize("REFRESH") | |
7477 | style:UIBarButtonItemStylePlain | |
7478 | target:self | |
7479 | action:@selector(refreshButtonClicked) | |
7480 | ] autorelease]]; | |
7481 | } | |
7482 | ||
7483 | @end | |
7484 | /* }}} */ | |
7485 | /* Search Controller {{{ */ | |
7486 | @interface SearchController : FilteredPackageController < | |
7487 | UISearchBarDelegate | |
7488 | > { | |
7489 | UISearchBar *search_; | |
7490 | } | |
7491 | ||
7492 | - (id) initWithDatabase:(Database *)database; | |
7493 | - (void) reloadData; | |
7494 | ||
7495 | @end | |
7496 | ||
7497 | @implementation SearchController | |
7498 | ||
7499 | - (void) dealloc { | |
7500 | [search_ release]; | |
7501 | [super dealloc]; | |
7502 | } | |
7503 | ||
7504 | - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar { | |
7505 | [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)]; | |
7506 | [search_ resignFirstResponder]; | |
7507 | [self reloadData]; | |
7508 | } | |
7509 | ||
7510 | - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text { | |
7511 | [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)]; | |
7512 | [self reloadData]; | |
7513 | } | |
7514 | ||
7515 | - (NSString *) title { return nil; } | |
7516 | ||
7517 | - (id) initWithDatabase:(Database *)database { | |
7518 | return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil]; | |
7519 | } | |
7520 | ||
7521 | - (void)viewDidAppear:(BOOL)animated { | |
7522 | [super viewDidAppear:animated]; | |
7523 | if (!search_) { | |
7524 | search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)]; | |
7525 | [search_ layoutSubviews]; | |
7526 | [search_ setPlaceholder:UCLocalize("SEARCH_EX")]; | |
7527 | ||
7528 | UITextField *textField; | |
7529 | if ([search_ respondsToSelector:@selector(searchField)]) | |
7530 | textField = [search_ searchField]; | |
7531 | else | |
7532 | textField = MSHookIvar<UITextField *>(search_, "_searchField"); | |
7533 | ||
7534 | [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; | |
7535 | [search_ setDelegate:self]; | |
7536 | [textField setEnablesReturnKeyAutomatically:NO]; | |
7537 | [[self navigationItem] setTitleView:textField]; | |
7538 | } | |
7539 | } | |
7540 | ||
7541 | - (void) _reloadData { | |
7542 | } | |
7543 | ||
7544 | - (void) reloadData { | |
7545 | _profile(SearchController$reloadData) | |
7546 | [packages_ reloadData]; | |
7547 | _end | |
7548 | PrintTimes(); | |
7549 | [packages_ resetCursor]; | |
7550 | } | |
7551 | ||
7552 | - (void) didSelectPackage:(Package *)package { | |
7553 | [search_ resignFirstResponder]; | |
7554 | [super didSelectPackage:package]; | |
7555 | } | |
7556 | ||
7557 | @end | |
7558 | /* }}} */ | |
7559 | /* Settings Controller {{{ */ | |
7560 | @interface SettingsController : CYViewController < | |
7561 | UITableViewDataSource, | |
7562 | UITableViewDelegate | |
7563 | > { | |
7564 | _transient Database *database_; | |
7565 | NSString *name_; | |
7566 | Package *package_; | |
7567 | UITableView *table_; | |
7568 | UISwitch *subscribedSwitch_; | |
7569 | UISwitch *ignoredSwitch_; | |
7570 | UITableViewCell *subscribedCell_; | |
7571 | UITableViewCell *ignoredCell_; | |
7572 | } | |
7573 | ||
7574 | - (id) initWithDatabase:(Database *)database package:(NSString *)package; | |
7575 | ||
7576 | @end | |
7577 | ||
7578 | @implementation SettingsController | |
7579 | ||
7580 | - (void) dealloc { | |
7581 | [name_ release]; | |
7582 | if (package_ != nil) | |
7583 | [package_ release]; | |
7584 | [table_ release]; | |
7585 | [subscribedSwitch_ release]; | |
7586 | [ignoredSwitch_ release]; | |
7587 | [subscribedCell_ release]; | |
7588 | [ignoredCell_ release]; | |
7589 | ||
7590 | [super dealloc]; | |
7591 | } | |
7592 | ||
7593 | - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { | |
7594 | if (package_ == nil) | |
7595 | return 0; | |
7596 | ||
7597 | return 1; | |
7598 | } | |
7599 | ||
7600 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
7601 | if (package_ == nil) | |
7602 | return 0; | |
7603 | ||
7604 | return 2; | |
7605 | } | |
7606 | ||
7607 | - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { | |
7608 | return UCLocalize("SHOW_ALL_CHANGES_EX"); | |
7609 | } | |
7610 | ||
7611 | - (void) onSubscribed:(id)control { | |
7612 | bool value([control isOn]); | |
7613 | if (package_ == nil) | |
7614 | return; | |
7615 | if ([package_ setSubscribed:value]) | |
7616 | [delegate_ updateData]; | |
7617 | } | |
7618 | ||
7619 | - (void) onIgnored:(id)control { | |
7620 | // TODO: set Held state - possibly call out to dpkg, etc. | |
7621 | } | |
7622 | ||
7623 | - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
7624 | if (package_ == nil) | |
7625 | return nil; | |
7626 | ||
7627 | switch ([indexPath row]) { | |
7628 | case 0: return subscribedCell_; | |
7629 | case 1: return ignoredCell_; | |
7630 | ||
7631 | _nodefault | |
7632 | } | |
7633 | ||
7634 | return nil; | |
7635 | } | |
7636 | ||
7637 | - (NSString *) title { return UCLocalize("SETTINGS"); } | |
7638 | ||
7639 | - (id) initWithDatabase:(Database *)database package:(NSString *)package { | |
7640 | if ((self = [super init])) { | |
7641 | database_ = database; | |
7642 | name_ = [package retain]; | |
7643 | ||
7644 | [[self navigationItem] setTitle:UCLocalize("SETTINGS")]; | |
7645 | ||
7646 | table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped]; | |
7647 | [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
7648 | [[self view] addSubview:table_]; | |
7649 | ||
7650 | subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)]; | |
7651 | [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; | |
7652 | [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged]; | |
7653 | ||
7654 | ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)]; | |
7655 | [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; | |
7656 | [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged]; | |
7657 | ||
7658 | subscribedCell_ = [[UITableViewCell alloc] init]; | |
7659 | [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")]; | |
7660 | [subscribedCell_ setAccessoryView:subscribedSwitch_]; | |
7661 | [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone]; | |
7662 | ||
7663 | ignoredCell_ = [[UITableViewCell alloc] init]; | |
7664 | [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")]; | |
7665 | [ignoredCell_ setAccessoryView:ignoredSwitch_]; | |
7666 | [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone]; | |
7667 | ||
7668 | [table_ setDataSource:self]; | |
7669 | [table_ setDelegate:self]; | |
7670 | [self reloadData]; | |
7671 | } return self; | |
7672 | } | |
7673 | ||
7674 | - (void) reloadData { | |
7675 | if (package_ != nil) | |
7676 | [package_ autorelease]; | |
7677 | package_ = [database_ packageWithName:name_]; | |
7678 | if (package_ != nil) { | |
7679 | [package_ retain]; | |
7680 | [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO]; | |
7681 | [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO]; | |
7682 | } | |
7683 | ||
7684 | [table_ reloadData]; | |
7685 | } | |
7686 | ||
7687 | @end | |
7688 | /* }}} */ | |
7689 | /* Signature Controller {{{ */ | |
7690 | @interface SignatureController : CYBrowserController { | |
7691 | _transient Database *database_; | |
7692 | NSString *package_; | |
7693 | } | |
7694 | ||
7695 | - (id) initWithDatabase:(Database *)database package:(NSString *)package; | |
7696 | ||
7697 | @end | |
7698 | ||
7699 | @implementation SignatureController | |
7700 | ||
7701 | - (void) dealloc { | |
7702 | [package_ release]; | |
7703 | [super dealloc]; | |
7704 | } | |
7705 | ||
7706 | - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame { | |
7707 | // XXX: dude! | |
7708 | [super webView:view didClearWindowObject:window forFrame:frame]; | |
7709 | } | |
7710 | ||
7711 | - (id) initWithDatabase:(Database *)database package:(NSString *)package { | |
7712 | if ((self = [super init]) != nil) { | |
7713 | database_ = database; | |
7714 | package_ = [package retain]; | |
7715 | [self reloadData]; | |
7716 | } return self; | |
7717 | } | |
7718 | ||
7719 | - (void) reloadData { | |
7720 | [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]]; | |
7721 | } | |
7722 | ||
7723 | @end | |
7724 | /* }}} */ | |
7725 | ||
7726 | /* Role Controller {{{ */ | |
7727 | @interface RoleController : CYViewController < | |
7728 | UITableViewDataSource, | |
7729 | UITableViewDelegate | |
7730 | > { | |
7731 | _transient Database *database_; | |
7732 | // XXX: ok, "roledelegate_"?... | |
7733 | _transient id roledelegate_; | |
7734 | UITableView *table_; | |
7735 | UISegmentedControl *segment_; | |
7736 | UIView *container_; | |
7737 | } | |
7738 | ||
7739 | - (void) showDoneButton; | |
7740 | - (void) resizeSegmentedControl; | |
7741 | ||
7742 | @end | |
7743 | ||
7744 | @implementation RoleController | |
7745 | - (void) dealloc { | |
7746 | [table_ release]; | |
7747 | [segment_ release]; | |
7748 | [container_ release]; | |
7749 | ||
7750 | [super dealloc]; | |
7751 | } | |
7752 | ||
7753 | - (id) initWithDatabase:(Database *)database delegate:(id)delegate { | |
7754 | if ((self = [super init])) { | |
7755 | database_ = database; | |
7756 | roledelegate_ = delegate; | |
7757 | ||
7758 | [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")]; | |
7759 | ||
7760 | NSArray *items = [NSArray arrayWithObjects: | |
7761 | UCLocalize("USER"), | |
7762 | UCLocalize("HACKER"), | |
7763 | UCLocalize("DEVELOPER"), | |
7764 | nil]; | |
7765 | segment_ = [[UISegmentedControl alloc] initWithItems:items]; | |
7766 | container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)]; | |
7767 | [container_ addSubview:segment_]; | |
7768 | ||
7769 | int index = -1; | |
7770 | if ([Role_ isEqualToString:@"User"]) index = 0; | |
7771 | if ([Role_ isEqualToString:@"Hacker"]) index = 1; | |
7772 | if ([Role_ isEqualToString:@"Developer"]) index = 2; | |
7773 | if (index != -1) { | |
7774 | [segment_ setSelectedSegmentIndex:index]; | |
7775 | [self showDoneButton]; | |
7776 | } | |
7777 | ||
7778 | [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged]; | |
7779 | [self resizeSegmentedControl]; | |
7780 | ||
7781 | table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped]; | |
7782 | [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
7783 | [table_ setDelegate:self]; | |
7784 | [table_ setDataSource:self]; | |
7785 | [[self view] addSubview:table_]; | |
7786 | [table_ reloadData]; | |
7787 | } return self; | |
7788 | } | |
7789 | ||
7790 | - (void) resizeSegmentedControl { | |
7791 | CGFloat width = [[self view] frame].size.width; | |
7792 | [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)]; | |
7793 | } | |
7794 | ||
7795 | - (void) viewWillAppear:(BOOL)animated { | |
7796 | [super viewWillAppear:animated]; | |
7797 | ||
7798 | [self resizeSegmentedControl]; | |
7799 | } | |
7800 | ||
7801 | - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration { | |
7802 | [self resizeSegmentedControl]; | |
7803 | } | |
7804 | ||
7805 | - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { | |
7806 | [self resizeSegmentedControl]; | |
7807 | } | |
7808 | ||
7809 | - (void) save { | |
7810 | NSString *role(nil); | |
7811 | ||
7812 | switch ([segment_ selectedSegmentIndex]) { | |
7813 | case 0: role = @"User"; break; | |
7814 | case 1: role = @"Hacker"; break; | |
7815 | case 2: role = @"Developer"; break; | |
7816 | ||
7817 | _nodefault | |
7818 | } | |
7819 | ||
7820 | if (![role isEqualToString:Role_]) { | |
7821 | bool rolling(Role_ == nil); | |
7822 | Role_ = role; | |
7823 | ||
7824 | Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys: | |
7825 | Role_, @"Role", | |
7826 | nil]; | |
7827 | ||
7828 | [Metadata_ setObject:Settings_ forKey:@"Settings"]; | |
7829 | Changed_ = true; | |
7830 | ||
7831 | if (rolling) | |
7832 | [roledelegate_ loadData]; | |
7833 | else | |
7834 | [roledelegate_ updateData]; | |
7835 | } | |
7836 | } | |
7837 | ||
7838 | - (void) segmentChanged:(UISegmentedControl *)control { | |
7839 | [self showDoneButton]; | |
7840 | } | |
7841 | ||
7842 | - (void) saveAndClose { | |
7843 | [self save]; | |
7844 | ||
7845 | [[self navigationItem] setRightBarButtonItem:nil]; | |
7846 | [[self navigationController] dismissModalViewControllerAnimated:YES]; | |
7847 | } | |
7848 | ||
7849 | - (void) doneButtonClicked { | |
7850 | UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease]; | |
7851 | [spinner startAnimating]; | |
7852 | UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease]; | |
7853 | [[self navigationItem] setRightBarButtonItem:spinItem]; | |
7854 | ||
7855 | [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0]; | |
7856 | } | |
7857 | ||
7858 | - (void) showDoneButton { | |
7859 | [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] | |
7860 | initWithTitle:UCLocalize("DONE") | |
7861 | style:UIBarButtonItemStyleDone | |
7862 | target:self | |
7863 | action:@selector(doneButtonClicked) | |
7864 | ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)]; | |
7865 | } | |
7866 | ||
7867 | - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { | |
7868 | // XXX: For not having a single cell in the table, this sure is a lot of sections. | |
7869 | return 6; | |
7870 | } | |
7871 | ||
7872 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
7873 | return 0; // :( | |
7874 | } | |
7875 | ||
7876 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
7877 | return nil; // This method is required by the protocol. | |
7878 | } | |
7879 | ||
7880 | - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { | |
7881 | if (section == 1) | |
7882 | return UCLocalize("ROLE_EX"); | |
7883 | if (section == 4) | |
7884 | return [NSString stringWithFormat: | |
7885 | @"%@: %@\n%@: %@\n%@: %@", | |
7886 | UCLocalize("USER"), UCLocalize("USER_EX"), | |
7887 | UCLocalize("HACKER"), UCLocalize("HACKER_EX"), | |
7888 | UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX") | |
7889 | ]; | |
7890 | else return nil; | |
7891 | } | |
7892 | ||
7893 | - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { | |
7894 | return section == 3 ? 44.0f : 0; | |
7895 | } | |
7896 | ||
7897 | - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { | |
7898 | return section == 3 ? container_ : nil; | |
7899 | } | |
7900 | ||
7901 | @end | |
7902 | /* }}} */ | |
7903 | /* Stash Controller {{{ */ | |
7904 | @interface CYStashController : CYViewController { | |
7905 | // XXX: just delete these things | |
7906 | _transient UIActivityIndicatorView *spinner_; | |
7907 | _transient UILabel *status_; | |
7908 | _transient UILabel *caption_; | |
7909 | } | |
7910 | @end | |
7911 | ||
7912 | @implementation CYStashController | |
7913 | - (id) init { | |
7914 | if ((self = [super init])) { | |
7915 | [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]]; | |
7916 | ||
7917 | spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease]; | |
7918 | CGRect spinrect = [spinner_ frame]; | |
7919 | spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2); | |
7920 | spinrect.origin.y = [[self view] frame].size.height - 80.0f; | |
7921 | [spinner_ setFrame:spinrect]; | |
7922 | [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin]; | |
7923 | [[self view] addSubview:spinner_]; | |
7924 | [spinner_ startAnimating]; | |
7925 | ||
7926 | CGRect captrect; | |
7927 | captrect.size.width = [[self view] frame].size.width; | |
7928 | captrect.size.height = 40.0f; | |
7929 | captrect.origin.x = 0; | |
7930 | captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2); | |
7931 | caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease]; | |
7932 | [caption_ setText:@"Initializing Filesystem"]; | |
7933 | [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; | |
7934 | [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]]; | |
7935 | [caption_ setTextColor:[UIColor whiteColor]]; | |
7936 | [caption_ setBackgroundColor:[UIColor clearColor]]; | |
7937 | [caption_ setShadowColor:[UIColor blackColor]]; | |
7938 | [caption_ setTextAlignment:UITextAlignmentCenter]; | |
7939 | [[self view] addSubview:caption_]; | |
7940 | ||
7941 | CGRect statusrect; | |
7942 | statusrect.size.width = [[self view] frame].size.width; | |
7943 | statusrect.size.height = 30.0f; | |
7944 | statusrect.origin.x = 0; | |
7945 | statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height; | |
7946 | status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease]; | |
7947 | [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; | |
7948 | [status_ setText:@"(Cydia will exit when complete.)"]; | |
7949 | [status_ setFont:[UIFont systemFontOfSize:16.0f]]; | |
7950 | [status_ setTextColor:[UIColor whiteColor]]; | |
7951 | [status_ setBackgroundColor:[UIColor clearColor]]; | |
7952 | [status_ setShadowColor:[UIColor blackColor]]; | |
7953 | [status_ setTextAlignment:UITextAlignmentCenter]; | |
7954 | [[self view] addSubview:status_]; | |
7955 | } return self; | |
7956 | } | |
7957 | ||
7958 | - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation { | |
7959 | return IsWildcat_ || orientation == UIInterfaceOrientationPortrait; | |
7960 | } | |
7961 | @end | |
7962 | /* }}} */ | |
7963 | ||
7964 | typedef enum { | |
7965 | kCydiaTag = 0, | |
7966 | kSectionsTag = 1, | |
7967 | kChangesTag = 2, | |
7968 | kManageTag = 3, | |
7969 | kInstalledTag = 4, | |
7970 | kSourcesTag = 5, | |
7971 | kSearchTag = 6 | |
7972 | } CYTabTag; | |
7973 | ||
7974 | @interface Cydia : UIApplication < | |
7975 | ConfirmationControllerDelegate, | |
7976 | ProgressControllerDelegate, | |
7977 | CydiaDelegate, | |
7978 | UINavigationControllerDelegate, | |
7979 | UITabBarControllerDelegate | |
7980 | > { | |
7981 | // XXX: evaluate all fields for _transient | |
7982 | ||
7983 | UIWindow *window_; | |
7984 | CYTabBarController *tabbar_; | |
7985 | ||
7986 | NSMutableArray *essential_; | |
7987 | NSMutableArray *broken_; | |
7988 | ||
7989 | Database *database_; | |
7990 | ||
7991 | int tag_; | |
7992 | int hudcount_; | |
7993 | NSURL *starturl_; | |
7994 | ||
7995 | SectionsController *sections_; | |
7996 | ChangesController *changes_; | |
7997 | ManageController *manage_; | |
7998 | SearchController *search_; | |
7999 | SourceTable *sources_; | |
8000 | InstalledController *installed_; | |
8001 | id queueDelegate_; | |
8002 | ||
8003 | CYStashController *stash_; | |
8004 | ||
8005 | bool loaded_; | |
8006 | } | |
8007 | ||
8008 | - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class; | |
8009 | - (void) setPage:(CYViewController *)page; | |
8010 | - (void) loadData; | |
8011 | ||
8012 | // XXX: I hate prototypes | |
8013 | - (id) queueBadgeController; | |
8014 | ||
8015 | @end | |
8016 | ||
8017 | static _finline void _setHomePage(Cydia *self) { | |
8018 | [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]]; | |
8019 | } | |
8020 | ||
8021 | @implementation Cydia | |
8022 | ||
8023 | - (void) beginUpdate { | |
8024 | [tabbar_ beginUpdate]; | |
8025 | } | |
8026 | ||
8027 | - (BOOL) updating { | |
8028 | return [tabbar_ updating]; | |
8029 | } | |
8030 | ||
8031 | - (UIView *) rotatingContentViewForWindow:(UIWindow *)window { | |
8032 | return window_; | |
8033 | } | |
8034 | ||
8035 | - (void) _loaded { | |
8036 | if ([broken_ count] != 0) { | |
8037 | int count = [broken_ count]; | |
8038 | ||
8039 | UIAlertView *alert = [[[UIAlertView alloc] | |
8040 | initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count]) | |
8041 | message:UCLocalize("HALFINSTALLED_PACKAGE_EX") | |
8042 | delegate:self | |
8043 | cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR") | |
8044 | otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil | |
8045 | ] autorelease]; | |
8046 | ||
8047 | [alert setContext:@"fixhalf"]; | |
8048 | [alert show]; | |
8049 | } else if (!Ignored_ && [essential_ count] != 0) { | |
8050 | int count = [essential_ count]; | |
8051 | ||
8052 | UIAlertView *alert = [[[UIAlertView alloc] | |
8053 | initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count]) | |
8054 | message:UCLocalize("ESSENTIAL_UPGRADE_EX") | |
8055 | delegate:self | |
8056 | cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE") | |
8057 | otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil | |
8058 | ] autorelease]; | |
8059 | ||
8060 | [alert setContext:@"upgrade"]; | |
8061 | [alert show]; | |
8062 | } | |
8063 | } | |
8064 | ||
8065 | - (void) _saveConfig { | |
8066 | _trace(); | |
8067 | MetaFile_.Sync(); | |
8068 | _trace(); | |
8069 | ||
8070 | if (Changed_) { | |
8071 | NSString *error(nil); | |
8072 | ||
8073 | if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) { | |
8074 | _trace(); | |
8075 | NSError *error(nil); | |
8076 | if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error]) | |
8077 | NSLog(@"failure to save metadata data: %@", error); | |
8078 | _trace(); | |
8079 | ||
8080 | Changed_ = false; | |
8081 | } else { | |
8082 | NSLog(@"failure to serialize metadata: %@", error); | |
8083 | } | |
8084 | } | |
8085 | } | |
8086 | ||
8087 | - (void) _updateData { | |
8088 | [self _saveConfig]; | |
8089 | ||
8090 | /* XXX: this is just stupid */ | |
8091 | if (tag_ != 1 && sections_ != nil) | |
8092 | [sections_ reloadData]; | |
8093 | if (tag_ != 2 && changes_ != nil) | |
8094 | [changes_ reloadData]; | |
8095 | if (tag_ != 4 && search_ != nil) | |
8096 | [search_ reloadData]; | |
8097 | ||
8098 | [(CYNavigationController *)[tabbar_ selectedViewController] reloadData]; | |
8099 | ||
8100 | [queueDelegate_ queueStatusDidChange]; | |
8101 | [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)]; | |
8102 | } | |
8103 | ||
8104 | - (int)indexOfTabWithTag:(int)tag { | |
8105 | int i = 0; | |
8106 | for (UINavigationController *controller in [tabbar_ viewControllers]) { | |
8107 | if ([[controller tabBarItem] tag] == tag) | |
8108 | return i; | |
8109 | i += 1; | |
8110 | } | |
8111 | ||
8112 | return -1; | |
8113 | } | |
8114 | ||
8115 | - (void) _refreshIfPossible { | |
8116 | NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; | |
8117 | ||
8118 | bool recently = false; | |
8119 | NSDate *update([Metadata_ objectForKey:@"LastUpdate"]); | |
8120 | if (update != nil) { | |
8121 | NSTimeInterval interval([update timeIntervalSinceNow]); | |
8122 | if (interval <= 0 && interval > -(15*60)) | |
8123 | recently = true; | |
8124 | } | |
8125 | ||
8126 | // Don't automatic refresh if: | |
8127 | // - We already refreshed recently. | |
8128 | // - We already auto-refreshed this launch. | |
8129 | // - Auto-refresh is disabled. | |
8130 | if (recently || loaded_ || ManualRefresh) { | |
8131 | [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO]; | |
8132 | ||
8133 | // If we are cancelling due to ManualRefresh or a recent refresh | |
8134 | // we need to make sure it knows it's already loaded. | |
8135 | loaded_ = true; | |
8136 | return; | |
8137 | } else { | |
8138 | // We are going to load, so remember that. | |
8139 | loaded_ = true; | |
8140 | } | |
8141 | ||
8142 | SCNetworkReachabilityFlags flags; { | |
8143 | SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com")); | |
8144 | SCNetworkReachabilityGetFlags(reachability, &flags); | |
8145 | CFRelease(reachability); | |
8146 | } | |
8147 | ||
8148 | // XXX: this elaborate mess is what Apple is using to determine this? :( | |
8149 | // XXX: do we care if the user has to intervene? maybe that's ok? | |
8150 | bool reachable( | |
8151 | (flags & kSCNetworkReachabilityFlagsReachable) != 0 && ( | |
8152 | (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || ( | |
8153 | (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 || | |
8154 | (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0 | |
8155 | ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 || | |
8156 | (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0 | |
8157 | ) | |
8158 | ); | |
8159 | ||
8160 | // If we can reach the server, auto-refresh! | |
8161 | if (reachable) | |
8162 | [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO]; | |
8163 | ||
8164 | [pool release]; | |
8165 | } | |
8166 | ||
8167 | - (void) refreshIfPossible { | |
8168 | [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil]; | |
8169 | } | |
8170 | ||
8171 | - (void) _reloadData { | |
8172 | UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil); | |
8173 | [hud setText:UCLocalize("RELOADING_DATA")]; | |
8174 | ||
8175 | [database_ yieldToSelector:@selector(reloadData) withObject:nil]; | |
8176 | ||
8177 | if (hud != nil) | |
8178 | [self removeProgressHUD:hud]; | |
8179 | ||
8180 | size_t changes(0); | |
8181 | ||
8182 | [essential_ removeAllObjects]; | |
8183 | [broken_ removeAllObjects]; | |
8184 | ||
8185 | NSArray *packages([database_ packages]); | |
8186 | for (Package *package in packages) { | |
8187 | if ([package half]) | |
8188 | [broken_ addObject:package]; | |
8189 | if ([package upgradableAndEssential:NO]) { | |
8190 | if ([package essential]) | |
8191 | [essential_ addObject:package]; | |
8192 | ++changes; | |
8193 | } | |
8194 | } | |
8195 | ||
8196 | UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem]; | |
8197 | if (changes != 0) { | |
8198 | NSString *badge([[NSNumber numberWithInt:changes] stringValue]); | |
8199 | [changesItem setBadgeValue:badge]; | |
8200 | [changesItem setAnimatedBadge:([essential_ count] > 0)]; | |
8201 | ||
8202 | if ([self respondsToSelector:@selector(setApplicationBadge:)]) | |
8203 | [self setApplicationBadge:badge]; | |
8204 | else | |
8205 | [self setApplicationBadgeString:badge]; | |
8206 | } else { | |
8207 | [changesItem setBadgeValue:nil]; | |
8208 | [changesItem setAnimatedBadge:NO]; | |
8209 | ||
8210 | if ([self respondsToSelector:@selector(removeApplicationBadge)]) | |
8211 | [self removeApplicationBadge]; | |
8212 | else // XXX: maybe use setApplicationBadgeString also? | |
8213 | [self setApplicationIconBadgeNumber:0]; | |
8214 | } | |
8215 | ||
8216 | [self _updateData]; | |
8217 | ||
8218 | [self refreshIfPossible]; | |
8219 | } | |
8220 | ||
8221 | - (void) updateData { | |
8222 | [self _updateData]; | |
8223 | } | |
8224 | ||
8225 | - (void) update_ { | |
8226 | [database_ update]; | |
8227 | } | |
8228 | ||
8229 | - (void) syncData { | |
8230 | FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w")); | |
8231 | _assert(file != NULL); | |
8232 | ||
8233 | for (NSString *key in [Sources_ allKeys]) { | |
8234 | NSDictionary *source([Sources_ objectForKey:key]); | |
8235 | ||
8236 | fprintf(file, "%s %s %s\n", | |
8237 | [[source objectForKey:@"Type"] UTF8String], | |
8238 | [[source objectForKey:@"URI"] UTF8String], | |
8239 | [[source objectForKey:@"Distribution"] UTF8String] | |
8240 | ); | |
8241 | } | |
8242 | ||
8243 | fclose(file); | |
8244 | ||
8245 | [self _saveConfig]; | |
8246 | ||
8247 | ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]; | |
8248 | CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease]; | |
8249 | if (IsWildcat_) | |
8250 | [navigation setModalPresentationStyle:UIModalPresentationFormSheet]; | |
8251 | [tabbar_ presentModalViewController:navigation animated:YES]; | |
8252 | ||
8253 | [progress | |
8254 | detachNewThreadSelector:@selector(update_) | |
8255 | toTarget:self | |
8256 | withObject:nil | |
8257 | title:UCLocalize("UPDATING_SOURCES") | |
8258 | ]; | |
8259 | } | |
8260 | ||
8261 | - (void) reloadData { | |
8262 | @synchronized (self) { | |
8263 | [self _reloadData]; | |
8264 | } | |
8265 | } | |
8266 | ||
8267 | - (void) resolve { | |
8268 | pkgProblemResolver *resolver = [database_ resolver]; | |
8269 | ||
8270 | resolver->InstallProtect(); | |
8271 | if (!resolver->Resolve(true)) | |
8272 | _error->Discard(); | |
8273 | } | |
8274 | ||
8275 | - (CGRect) popUpBounds { | |
8276 | return [[tabbar_ view] bounds]; | |
8277 | } | |
8278 | ||
8279 | - (bool) perform { | |
8280 | if (![database_ prepare]) | |
8281 | return false; | |
8282 | ||
8283 | ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]); | |
8284 | [page setDelegate:self]; | |
8285 | CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]); | |
8286 | [confirm_ setDelegate:self]; | |
8287 | ||
8288 | if (IsWildcat_) | |
8289 | [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet]; | |
8290 | [tabbar_ presentModalViewController:confirm_ animated:YES]; | |
8291 | ||
8292 | return true; | |
8293 | } | |
8294 | ||
8295 | - (void) queue { | |
8296 | @synchronized (self) { | |
8297 | [self perform]; | |
8298 | } | |
8299 | } | |
8300 | ||
8301 | - (void) clearPackage:(Package *)package { | |
8302 | @synchronized (self) { | |
8303 | [package clear]; | |
8304 | [self resolve]; | |
8305 | [self perform]; | |
8306 | } | |
8307 | } | |
8308 | ||
8309 | - (void) installPackages:(NSArray *)packages { | |
8310 | @synchronized (self) { | |
8311 | for (Package *package in packages) | |
8312 | [package install]; | |
8313 | [self resolve]; | |
8314 | [self perform]; | |
8315 | } | |
8316 | } | |
8317 | ||
8318 | - (void) installPackage:(Package *)package { | |
8319 | @synchronized (self) { | |
8320 | [package install]; | |
8321 | [self resolve]; | |
8322 | [self perform]; | |
8323 | } | |
8324 | } | |
8325 | ||
8326 | - (void) removePackage:(Package *)package { | |
8327 | @synchronized (self) { | |
8328 | [package remove]; | |
8329 | [self resolve]; | |
8330 | [self perform]; | |
8331 | } | |
8332 | } | |
8333 | ||
8334 | - (void) distUpgrade { | |
8335 | @synchronized (self) { | |
8336 | if (![database_ upgrade]) | |
8337 | return; | |
8338 | [self perform]; | |
8339 | } | |
8340 | } | |
8341 | ||
8342 | - (void) complete { | |
8343 | @synchronized (self) { | |
8344 | [self _reloadData]; | |
8345 | } | |
8346 | } | |
8347 | ||
8348 | - (void) confirmWithNavigationController:(UINavigationController *)navigation { | |
8349 | Queuing_ = false; | |
8350 | ||
8351 | ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]; | |
8352 | ||
8353 | if (navigation != nil) { | |
8354 | [navigation pushViewController:progress animated:YES]; | |
8355 | } else { | |
8356 | navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease]; | |
8357 | if (IsWildcat_) | |
8358 | [navigation setModalPresentationStyle:UIModalPresentationFormSheet]; | |
8359 | [tabbar_ presentModalViewController:navigation animated:YES]; | |
8360 | } | |
8361 | ||
8362 | [progress | |
8363 | detachNewThreadSelector:@selector(perform) | |
8364 | toTarget:database_ | |
8365 | withObject:nil | |
8366 | title:UCLocalize("RUNNING") | |
8367 | ]; | |
8368 | } | |
8369 | ||
8370 | - (void) progressControllerIsComplete:(ProgressController *)progress { | |
8371 | [self complete]; | |
8372 | } | |
8373 | ||
8374 | - (void) setPage:(CYViewController *)page { | |
8375 | [page setDelegate:self]; | |
8376 | ||
8377 | CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController]; | |
8378 | [navController setViewControllers:[NSArray arrayWithObject:page]]; | |
8379 | for (CYNavigationController *page in [tabbar_ viewControllers]) | |
8380 | if (page != navController) | |
8381 | [page setViewControllers:nil]; | |
8382 | } | |
8383 | ||
8384 | - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class { | |
8385 | CYBrowserController *browser = [[[_class alloc] init] autorelease]; | |
8386 | [browser loadURL:url]; | |
8387 | return browser; | |
8388 | } | |
8389 | ||
8390 | - (SectionsController *) sectionsController { | |
8391 | if (sections_ == nil) | |
8392 | sections_ = [[SectionsController alloc] initWithDatabase:database_]; | |
8393 | return sections_; | |
8394 | } | |
8395 | ||
8396 | - (ChangesController *) changesController { | |
8397 | if (changes_ == nil) | |
8398 | changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self]; | |
8399 | return changes_; | |
8400 | } | |
8401 | ||
8402 | - (ManageController *) manageController { | |
8403 | if (manage_ == nil) { | |
8404 | manage_ = (ManageController *) [[self | |
8405 | _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]] | |
8406 | withClass:[ManageController class] | |
8407 | ] retain]; | |
8408 | if (!IsWildcat_) | |
8409 | queueDelegate_ = manage_; | |
8410 | } | |
8411 | return manage_; | |
8412 | } | |
8413 | ||
8414 | - (SearchController *) searchController { | |
8415 | if (search_ == nil) | |
8416 | search_ = [[SearchController alloc] initWithDatabase:database_]; | |
8417 | return search_; | |
8418 | } | |
8419 | ||
8420 | - (SourceTable *) sourcesController { | |
8421 | if (sources_ == nil) | |
8422 | sources_ = [[SourceTable alloc] initWithDatabase:database_]; | |
8423 | return sources_; | |
8424 | } | |
8425 | ||
8426 | - (InstalledController *) installedController { | |
8427 | if (installed_ == nil) { | |
8428 | installed_ = [[InstalledController alloc] initWithDatabase:database_]; | |
8429 | if (IsWildcat_) | |
8430 | queueDelegate_ = installed_; | |
8431 | } | |
8432 | return installed_; | |
8433 | } | |
8434 | ||
8435 | - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController { | |
8436 | int tag = [[viewController tabBarItem] tag]; | |
8437 | if (tag == tag_) { | |
8438 | [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES]; | |
8439 | return; | |
8440 | } else if (tag_ == 1) { | |
8441 | [[self sectionsController] resetView]; | |
8442 | } | |
8443 | ||
8444 | switch (tag) { | |
8445 | case kCydiaTag: _setHomePage(self); break; | |
8446 | ||
8447 | case kSectionsTag: [self setPage:[self sectionsController]]; break; | |
8448 | case kChangesTag: [self setPage:[self changesController]]; break; | |
8449 | case kManageTag: [self setPage:[self manageController]]; break; | |
8450 | case kInstalledTag: [self setPage:[self installedController]]; break; | |
8451 | case kSourcesTag: [self setPage:[self sourcesController]]; break; | |
8452 | case kSearchTag: [self setPage:[self searchController]]; break; | |
8453 | ||
8454 | _nodefault | |
8455 | } | |
8456 | ||
8457 | tag_ = tag; | |
8458 | } | |
8459 | ||
8460 | - (void) showSettings { | |
8461 | RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease]; | |
8462 | CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease]; | |
8463 | if (IsWildcat_) | |
8464 | [nav setModalPresentationStyle:UIModalPresentationFormSheet]; | |
8465 | [tabbar_ presentModalViewController:nav animated:YES]; | |
8466 | } | |
8467 | ||
8468 | - (void) setPackageController:(PackageController *)view { | |
8469 | WebThreadLock(); | |
8470 | [view setPackage:nil]; | |
8471 | WebThreadUnlock(); | |
8472 | } | |
8473 | ||
8474 | - (PackageController *) _packageController { | |
8475 | return [[[PackageController alloc] initWithDatabase:database_] autorelease]; | |
8476 | } | |
8477 | ||
8478 | - (PackageController *) packageController { | |
8479 | return [self _packageController]; | |
8480 | } | |
8481 | ||
8482 | // Returns the navigation controller for the queuing badge. | |
8483 | - (id) queueBadgeController { | |
8484 | int index = [self indexOfTabWithTag:kManageTag]; | |
8485 | if (index == -1) | |
8486 | index = [self indexOfTabWithTag:kInstalledTag]; | |
8487 | ||
8488 | return [[tabbar_ viewControllers] objectAtIndex:index]; | |
8489 | } | |
8490 | ||
8491 | - (void) cancelAndClear:(bool)clear { | |
8492 | @synchronized (self) { | |
8493 | if (clear) { | |
8494 | [database_ clear]; | |
8495 | Queuing_ = false; | |
8496 | } else { | |
8497 | Queuing_ = true; | |
8498 | } | |
8499 | ||
8500 | [self _updateData]; | |
8501 | } | |
8502 | } | |
8503 | ||
8504 | - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { | |
8505 | NSString *context([alert context]); | |
8506 | ||
8507 | if ([context isEqualToString:@"fixhalf"]) { | |
8508 | if (button == [alert firstOtherButtonIndex]) { | |
8509 | @synchronized (self) { | |
8510 | for (Package *broken in broken_) { | |
8511 | [broken remove]; | |
8512 | ||
8513 | NSString *id = [broken id]; | |
8514 | unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]); | |
8515 | unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]); | |
8516 | unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]); | |
8517 | unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]); | |
8518 | } | |
8519 | ||
8520 | [self resolve]; | |
8521 | [self perform]; | |
8522 | } | |
8523 | } else if (button == [alert cancelButtonIndex]) { | |
8524 | [broken_ removeAllObjects]; | |
8525 | [self _loaded]; | |
8526 | } | |
8527 | ||
8528 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
8529 | } else if ([context isEqualToString:@"upgrade"]) { | |
8530 | if (button == [alert firstOtherButtonIndex]) { | |
8531 | @synchronized (self) { | |
8532 | for (Package *essential in essential_) | |
8533 | [essential install]; | |
8534 | ||
8535 | [self resolve]; | |
8536 | [self perform]; | |
8537 | } | |
8538 | } else if (button == [alert firstOtherButtonIndex] + 1) { | |
8539 | [self distUpgrade]; | |
8540 | } else if (button == [alert cancelButtonIndex]) { | |
8541 | Ignored_ = YES; | |
8542 | } | |
8543 | ||
8544 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
8545 | } | |
8546 | } | |
8547 | ||
8548 | - (void) system:(NSString *)command { _pooled | |
8549 | system([command UTF8String]); | |
8550 | } | |
8551 | ||
8552 | - (void) applicationWillSuspend { | |
8553 | [database_ clean]; | |
8554 | [super applicationWillSuspend]; | |
8555 | } | |
8556 | ||
8557 | - (BOOL) hudIsShowing { | |
8558 | return (hudcount_ > 0); | |
8559 | } | |
8560 | ||
8561 | - (void) applicationSuspend:(__GSEvent *)event { | |
8562 | // Use external process status API internally. | |
8563 | // This is probably a really bad idea. | |
8564 | uint64_t status = 0; | |
8565 | int notify_token; | |
8566 | if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) { | |
8567 | notify_get_state(notify_token, &status); | |
8568 | notify_cancel(notify_token); | |
8569 | } | |
8570 | ||
8571 | if (![self hudIsShowing] && status == 0) | |
8572 | [super applicationSuspend:event]; | |
8573 | } | |
8574 | ||
8575 | - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 { | |
8576 | if (![self hudIsShowing]) | |
8577 | [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3]; | |
8578 | } | |
8579 | ||
8580 | - (void) _setSuspended:(BOOL)value { | |
8581 | if (![self hudIsShowing]) | |
8582 | [super _setSuspended:value]; | |
8583 | } | |
8584 | ||
8585 | - (UIProgressHUD *) addProgressHUD { | |
8586 | UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]); | |
8587 | [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
8588 | ||
8589 | [window_ setUserInteractionEnabled:NO]; | |
8590 | [hud show:YES]; | |
8591 | ||
8592 | UIViewController *target = tabbar_; | |
8593 | while ([target modalViewController] != nil) target = [target modalViewController]; | |
8594 | [[target view] addSubview:hud]; | |
8595 | ||
8596 | hudcount_++; | |
8597 | return hud; | |
8598 | } | |
8599 | ||
8600 | - (void) removeProgressHUD:(UIProgressHUD *)hud { | |
8601 | [hud show:NO]; | |
8602 | [hud removeFromSuperview]; | |
8603 | [window_ setUserInteractionEnabled:YES]; | |
8604 | hudcount_--; | |
8605 | } | |
8606 | ||
8607 | - (CYViewController *) pageForPackage:(NSString *)name { | |
8608 | if (Package *package = [database_ packageWithName:name]) { | |
8609 | PackageController *view([self packageController]); | |
8610 | [view setPackage:package]; | |
8611 | return view; | |
8612 | } else { | |
8613 | NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]); | |
8614 | url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]]; | |
8615 | return [self _pageForURL:url withClass:[CYBrowserController class]]; | |
8616 | } | |
8617 | } | |
8618 | ||
8619 | - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag { | |
8620 | if (tag != NULL) | |
8621 | *tag = -1; | |
8622 | ||
8623 | NSString *href([url absoluteString]); | |
8624 | if ([href hasPrefix:@"apptapp://package/"]) | |
8625 | return [self pageForPackage:[href substringFromIndex:18]]; | |
8626 | ||
8627 | NSString *scheme([[url scheme] lowercaseString]); | |
8628 | if (![scheme isEqualToString:@"cydia"]) | |
8629 | return nil; | |
8630 | NSString *path([url absoluteString]); | |
8631 | if ([path length] < 8) | |
8632 | return nil; | |
8633 | path = [path substringFromIndex:8]; | |
8634 | if (![path hasPrefix:@"/"]) | |
8635 | path = [@"/" stringByAppendingString:path]; | |
8636 | ||
8637 | if ([path isEqualToString:@"/add-source"]) | |
8638 | return [[[AddSourceController alloc] initWithDatabase:database_] autorelease]; | |
8639 | else if ([path isEqualToString:@"/storage"]) | |
8640 | return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]]; | |
8641 | else if ([path isEqualToString:@"/sources"]) | |
8642 | return [[[SourceTable alloc] initWithDatabase:database_] autorelease]; | |
8643 | else if ([path isEqualToString:@"/packages"]) | |
8644 | return [[[InstalledController alloc] initWithDatabase:database_] autorelease]; | |
8645 | else if ([path hasPrefix:@"/url/"]) | |
8646 | return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]]; | |
8647 | else if ([path hasPrefix:@"/launch/"]) | |
8648 | [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO]; | |
8649 | else if ([path hasPrefix:@"/package-settings/"]) | |
8650 | return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease]; | |
8651 | else if ([path hasPrefix:@"/package-signature/"]) | |
8652 | return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease]; | |
8653 | else if ([path hasPrefix:@"/package/"]) | |
8654 | return [self pageForPackage:[path substringFromIndex:9]]; | |
8655 | else if ([path hasPrefix:@"/files/"]) { | |
8656 | NSString *name = [path substringFromIndex:7]; | |
8657 | ||
8658 | if (Package *package = [database_ packageWithName:name]) { | |
8659 | FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease]; | |
8660 | [files setPackage:package]; | |
8661 | return files; | |
8662 | } | |
8663 | } | |
8664 | ||
8665 | return nil; | |
8666 | } | |
8667 | ||
8668 | - (BOOL) openCydiaURL:(NSURL *)url { | |
8669 | CYViewController *page = nil; | |
8670 | int tag = 0; | |
8671 | ||
8672 | NSLog(@"open url: %@", url); | |
8673 | ||
8674 | if ((page = [self pageForURL:url hasTag:&tag])) { | |
8675 | [self setPage:page]; | |
8676 | tag_ = tag; | |
8677 | [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])]; | |
8678 | } | |
8679 | ||
8680 | return !!page; | |
8681 | } | |
8682 | ||
8683 | - (void) applicationOpenURL:(NSURL *)url { | |
8684 | [super applicationOpenURL:url]; | |
8685 | NSLog(@"first: %@", url); | |
8686 | if (!loaded_) starturl_ = [url retain]; | |
8687 | else [self openCydiaURL:url]; | |
8688 | } | |
8689 | ||
8690 | - (void) applicationWillResignActive:(UIApplication *)application { | |
8691 | // Stop refreshing if you get a phone call or lock the device. | |
8692 | if ([tabbar_ updating]) | |
8693 | [tabbar_ cancelUpdate]; | |
8694 | ||
8695 | if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)]) | |
8696 | [super applicationWillResignActive:application]; | |
8697 | } | |
8698 | ||
8699 | - (void) addStashController { | |
8700 | stash_ = [[CYStashController alloc] init]; | |
8701 | [window_ addSubview:[stash_ view]]; | |
8702 | } | |
8703 | ||
8704 | - (void) removeStashController { | |
8705 | [[stash_ view] removeFromSuperview]; | |
8706 | [stash_ release]; | |
8707 | } | |
8708 | ||
8709 | - (void) stash { | |
8710 | [self setIdleTimerDisabled:YES]; | |
8711 | ||
8712 | [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque]; | |
8713 | [self setStatusBarShowsProgress:YES]; | |
8714 | UpdateExternalStatus(1); | |
8715 | ||
8716 | [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"]; | |
8717 | ||
8718 | UpdateExternalStatus(0); | |
8719 | [self setStatusBarShowsProgress:NO]; | |
8720 | ||
8721 | [self removeStashController]; | |
8722 | ||
8723 | if (ExecFork() == 0) { | |
8724 | execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL); | |
8725 | perror("launchctl stop"); | |
8726 | } | |
8727 | } | |
8728 | ||
8729 | - (void) setupTabBarController { | |
8730 | tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_]; | |
8731 | [tabbar_ setDelegate:self]; | |
8732 | ||
8733 | NSMutableArray *items([NSMutableArray arrayWithObjects: | |
8734 | [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease], | |
8735 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease], | |
8736 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease], | |
8737 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease], | |
8738 | nil]); | |
8739 | ||
8740 | if (IsWildcat_) { | |
8741 | [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3]; | |
8742 | [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3]; | |
8743 | } else { | |
8744 | [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3]; | |
8745 | } | |
8746 | ||
8747 | NSMutableArray *controllers([NSMutableArray array]); | |
8748 | ||
8749 | for (UITabBarItem *item in items) { | |
8750 | CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]); | |
8751 | [controller setTabBarItem:item]; | |
8752 | [controllers addObject:controller]; | |
8753 | } | |
8754 | ||
8755 | [tabbar_ setViewControllers:controllers]; | |
8756 | } | |
8757 | ||
8758 | - (void) applicationDidFinishLaunching:(id)unused { | |
8759 | _trace(); | |
8760 | [NSURLCache setSharedURLCache:[[[SDURLCache alloc] | |
8761 | initWithMemoryCapacity:524288 | |
8762 | diskCapacity:10485760 | |
8763 | diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"] | |
8764 | ] autorelease]]; | |
8765 | ||
8766 | [CYBrowserController _initialize]; | |
8767 | ||
8768 | [NSURLProtocol registerClass:[CydiaURLProtocol class]]; | |
8769 | ||
8770 | Font12_ = [[UIFont systemFontOfSize:12] retain]; | |
8771 | Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain]; | |
8772 | Font14_ = [[UIFont systemFontOfSize:14] retain]; | |
8773 | Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain]; | |
8774 | Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain]; | |
8775 | ||
8776 | tag_ = 0; | |
8777 | ||
8778 | essential_ = [[NSMutableArray alloc] initWithCapacity:4]; | |
8779 | broken_ = [[NSMutableArray alloc] initWithCapacity:4]; | |
8780 | ||
8781 | UIScreen *screen([UIScreen mainScreen]); | |
8782 | ||
8783 | window_ = [[UIWindow alloc] initWithFrame:[screen bounds]]; | |
8784 | [window_ orderFront:self]; | |
8785 | [window_ makeKey:self]; | |
8786 | [window_ setHidden:NO]; | |
8787 | ||
8788 | if ( | |
8789 | readlink("/Applications", NULL, 0) == -1 && errno == EINVAL || | |
8790 | readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL || | |
8791 | readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL || | |
8792 | //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL || | |
8793 | readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL || | |
8794 | readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL || | |
8795 | readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL || | |
8796 | readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL || | |
8797 | //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL || | |
8798 | false | |
8799 | ) { | |
8800 | [self addStashController]; | |
8801 | // XXX: this would be much cleaner as a yieldToSelector: | |
8802 | // that way the removeStashController could happen right here inline | |
8803 | // we also could no longer require the useless stash_ field anymore | |
8804 | [self performSelector:@selector(stash) withObject:nil afterDelay:0]; | |
8805 | return; | |
8806 | } | |
8807 | ||
8808 | database_ = [Database sharedInstance]; | |
8809 | ||
8810 | [self setupTabBarController]; | |
8811 | [tabbar_ setUpdateDelegate:self]; | |
8812 | [window_ addSubview:[tabbar_ view]]; | |
8813 | ||
8814 | // Show pinstripes while loading data. | |
8815 | [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]]; | |
8816 | ||
8817 | [self performSelector:@selector(loadData) withObject:nil afterDelay:0]; | |
8818 | _trace(); | |
8819 | } | |
8820 | ||
8821 | - (void) loadData { | |
8822 | _trace(); | |
8823 | if (Role_ == nil) { | |
8824 | [self showSettings]; | |
8825 | return; | |
8826 | } | |
8827 | ||
8828 | [window_ setUserInteractionEnabled:NO]; | |
8829 | ||
8830 | UIView *container = [[[UIView alloc] init] autorelease]; | |
8831 | [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin]; | |
8832 | ||
8833 | UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease]; | |
8834 | [spinner startAnimating]; | |
8835 | [container addSubview:spinner]; | |
8836 | ||
8837 | UILabel *label = [[[UILabel alloc] init] autorelease]; | |
8838 | [label setFont:[UIFont boldSystemFontOfSize:15.0f]]; | |
8839 | [label setBackgroundColor:[UIColor clearColor]]; | |
8840 | [label setTextColor:[UIColor blackColor]]; | |
8841 | [label setShadowColor:[UIColor whiteColor]]; | |
8842 | [label setShadowOffset:CGSizeMake(0, 1)]; | |
8843 | [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]]; | |
8844 | [container addSubview:label]; | |
8845 | ||
8846 | CGSize viewsize = [[tabbar_ view] frame].size; | |
8847 | CGSize spinnersize = [spinner bounds].size; | |
8848 | CGSize textsize = [[label text] sizeWithFont:[label font]]; | |
8849 | float bothwidth = spinnersize.width + textsize.width + 5.0f; | |
8850 | ||
8851 | CGRect containrect = { | |
8852 | CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))), | |
8853 | CGSizeMake(bothwidth, spinnersize.height) | |
8854 | }; | |
8855 | CGRect textrect = { | |
8856 | CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))), | |
8857 | textsize | |
8858 | }; | |
8859 | CGRect spinrect = { | |
8860 | CGPointZero, | |
8861 | spinnersize | |
8862 | }; | |
8863 | ||
8864 | [container setFrame:containrect]; | |
8865 | [spinner setFrame:spinrect]; | |
8866 | [label setFrame:textrect]; | |
8867 | [[tabbar_ view] addSubview:container]; | |
8868 | ||
8869 | [self reloadData]; | |
8870 | PrintTimes(); | |
8871 | ||
8872 | // Show the initial page | |
8873 | if (starturl_ == nil || ![self openCydiaURL:starturl_]) { | |
8874 | [tabbar_ setSelectedIndex:0]; | |
8875 | _setHomePage(self); | |
8876 | } | |
8877 | ||
8878 | [starturl_ release]; | |
8879 | starturl_ = nil; | |
8880 | ||
8881 | [window_ setUserInteractionEnabled:YES]; | |
8882 | ||
8883 | // XXX: does this actually slow anything down? | |
8884 | [[tabbar_ view] setBackgroundColor:[UIColor clearColor]]; | |
8885 | [container removeFromSuperview]; | |
8886 | } | |
8887 | ||
8888 | - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item { | |
8889 | if (item != nil && IsWildcat_) { | |
8890 | [sheet showFromBarButtonItem:item animated:YES]; | |
8891 | } else { | |
8892 | [sheet showInView:window_]; | |
8893 | } | |
8894 | } | |
8895 | ||
8896 | @end | |
8897 | ||
8898 | /*IMP alloc_; | |
8899 | id Alloc_(id self, SEL selector) { | |
8900 | id object = alloc_(self, selector); | |
8901 | lprintf("[%s]A-%p\n", self->isa->name, object); | |
8902 | return object; | |
8903 | }*/ | |
8904 | ||
8905 | /*IMP dealloc_; | |
8906 | id Dealloc_(id self, SEL selector) { | |
8907 | id object = dealloc_(self, selector); | |
8908 | lprintf("[%s]D-%p\n", self->isa->name, object); | |
8909 | return object; | |
8910 | }*/ | |
8911 | ||
8912 | Class $WebDefaultUIKitDelegate; | |
8913 | ||
8914 | MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) { | |
8915 | if (delegate == nil && $WebDefaultUIKitDelegate != nil) | |
8916 | delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate]; | |
8917 | return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate); | |
8918 | } | |
8919 | ||
8920 | static NSNumber *shouldPlayKeyboardSounds; | |
8921 | ||
8922 | Class $UIHardware; | |
8923 | ||
8924 | MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) { | |
8925 | switch (sound) { | |
8926 | case 1104: // Keyboard Button Clicked | |
8927 | case 1105: // Keyboard Delete Repeated | |
8928 | if (shouldPlayKeyboardSounds == nil) { | |
8929 | NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]); | |
8930 | shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain]; | |
8931 | } | |
8932 | ||
8933 | if (![shouldPlayKeyboardSounds boolValue]) | |
8934 | break; | |
8935 | ||
8936 | default: | |
8937 | _UIHardware$_playSystemSound$(self, _cmd, sound); | |
8938 | } | |
8939 | } | |
8940 | ||
8941 | int main(int argc, char *argv[]) { _pooled | |
8942 | _trace(); | |
8943 | ||
8944 | if (Class $UIDevice = objc_getClass("UIDevice")) { | |
8945 | UIDevice *device([$UIDevice currentDevice]); | |
8946 | IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat]; | |
8947 | } else | |
8948 | IsWildcat_ = false; | |
8949 | ||
8950 | PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname)))); | |
8951 | ||
8952 | /* Library Hacks {{{ */ | |
8953 | class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16"); | |
8954 | ||
8955 | $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate"); | |
8956 | Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:))); | |
8957 | if (UIWebDocumentView$_setUIKitDelegate$ != NULL) { | |
8958 | _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$)); | |
8959 | method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$)); | |
8960 | } | |
8961 | ||
8962 | $UIHardware = objc_getClass("UIHardware"); | |
8963 | Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:))); | |
8964 | if (UIHardware$_playSystemSound$ != NULL) { | |
8965 | _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$)); | |
8966 | method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$)); | |
8967 | } | |
8968 | /* }}} */ | |
8969 | /* Set Locale {{{ */ | |
8970 | Locale_ = CFLocaleCopyCurrent(); | |
8971 | Languages_ = [NSLocale preferredLanguages]; | |
8972 | //CFStringRef locale(CFLocaleGetIdentifier(Locale_)); | |
8973 | //NSLog(@"%@", [Languages_ description]); | |
8974 | ||
8975 | const char *lang; | |
8976 | if (Languages_ == nil || [Languages_ count] == 0) | |
8977 | // XXX: consider just setting to C and then falling through? | |
8978 | lang = NULL; | |
8979 | else { | |
8980 | lang = [[Languages_ objectAtIndex:0] UTF8String]; | |
8981 | setenv("LANG", lang, true); | |
8982 | } | |
8983 | ||
8984 | //std::setlocale(LC_ALL, lang); | |
8985 | NSLog(@"Setting Language: %s", lang); | |
8986 | /* }}} */ | |
8987 | ||
8988 | apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL); | |
8989 | ||
8990 | /* Parse Arguments {{{ */ | |
8991 | bool substrate(false); | |
8992 | ||
8993 | if (argc != 0) { | |
8994 | char **args(argv); | |
8995 | int arge(1); | |
8996 | ||
8997 | for (int argi(1); argi != argc; ++argi) | |
8998 | if (strcmp(argv[argi], "--") == 0) { | |
8999 | arge = argi; | |
9000 | argv[argi] = argv[0]; | |
9001 | argv += argi; | |
9002 | argc -= argi; | |
9003 | break; | |
9004 | } | |
9005 | ||
9006 | for (int argi(1); argi != arge; ++argi) | |
9007 | if (strcmp(args[argi], "--substrate") == 0) | |
9008 | substrate = true; | |
9009 | else | |
9010 | fprintf(stderr, "unknown argument: %s\n", args[argi]); | |
9011 | } | |
9012 | /* }}} */ | |
9013 | ||
9014 | App_ = [[NSBundle mainBundle] bundlePath]; | |
9015 | Home_ = NSHomeDirectory(); | |
9016 | Advanced_ = YES; | |
9017 | ||
9018 | setuid(0); | |
9019 | setgid(0); | |
9020 | ||
9021 | /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc)); | |
9022 | alloc_ = alloc->method_imp; | |
9023 | alloc->method_imp = (IMP) &Alloc_;*/ | |
9024 | ||
9025 | /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc)); | |
9026 | dealloc_ = dealloc->method_imp; | |
9027 | dealloc->method_imp = (IMP) &Dealloc_;*/ | |
9028 | ||
9029 | /* System Information {{{ */ | |
9030 | size_t size; | |
9031 | ||
9032 | int maxproc; | |
9033 | size = sizeof(maxproc); | |
9034 | if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1) | |
9035 | perror("sysctlbyname(\"kern.maxproc\", ?)"); | |
9036 | else if (maxproc < 64) { | |
9037 | maxproc = 64; | |
9038 | if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1) | |
9039 | perror("sysctlbyname(\"kern.maxproc\", #)"); | |
9040 | } | |
9041 | ||
9042 | sysctlbyname("kern.osversion", NULL, &size, NULL, 0); | |
9043 | char *osversion = new char[size]; | |
9044 | if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1) | |
9045 | perror("sysctlbyname(\"kern.osversion\", ?)"); | |
9046 | else | |
9047 | System_ = [NSString stringWithUTF8String:osversion]; | |
9048 | ||
9049 | sysctlbyname("hw.machine", NULL, &size, NULL, 0); | |
9050 | char *machine = new char[size]; | |
9051 | if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1) | |
9052 | perror("sysctlbyname(\"hw.machine\", ?)"); | |
9053 | else | |
9054 | Machine_ = machine; | |
9055 | ||
9056 | if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) { | |
9057 | if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) { | |
9058 | if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) { | |
9059 | SerialNumber_ = [NSString stringWithString:(NSString *)serial]; | |
9060 | CFRelease(serial); | |
9061 | } | |
9062 | ||
9063 | if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) { | |
9064 | NSData *data((NSData *) ecid); | |
9065 | size_t length([data length]); | |
9066 | uint8_t bytes[length]; | |
9067 | [data getBytes:bytes]; | |
9068 | char string[length * 2 + 1]; | |
9069 | for (size_t i(0); i != length; ++i) | |
9070 | sprintf(string + i * 2, "%.2X", bytes[length - i - 1]); | |
9071 | ChipID_ = [NSString stringWithUTF8String:string]; | |
9072 | CFRelease(ecid); | |
9073 | } | |
9074 | ||
9075 | IOObjectRelease(service); | |
9076 | } | |
9077 | } | |
9078 | ||
9079 | UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier]; | |
9080 | ||
9081 | CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef); | |
9082 | $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")); | |
9083 | CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault)); | |
9084 | ||
9085 | CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef); | |
9086 | $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")); | |
9087 | CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault)); | |
9088 | ||
9089 | if (mcc != NULL && mnc != NULL) | |
9090 | PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc]; | |
9091 | ||
9092 | if (mnc != NULL) | |
9093 | CFRelease(mnc); | |
9094 | if (mcc != NULL) | |
9095 | CFRelease(mcc); | |
9096 | ||
9097 | if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"]) | |
9098 | Build_ = [system objectForKey:@"ProductBuildVersion"]; | |
9099 | if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) { | |
9100 | Product_ = [info objectForKey:@"SafariProductVersion"]; | |
9101 | Safari_ = [info objectForKey:@"CFBundleVersion"]; | |
9102 | } | |
9103 | /* }}} */ | |
9104 | /* Load Database {{{ */ | |
9105 | _trace(); | |
9106 | Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]; | |
9107 | _trace(); | |
9108 | SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease]; | |
9109 | ||
9110 | if (Metadata_ == NULL) | |
9111 | Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2]; | |
9112 | else { | |
9113 | Settings_ = [Metadata_ objectForKey:@"Settings"]; | |
9114 | ||
9115 | Packages_ = [Metadata_ objectForKey:@"Packages"]; | |
9116 | Sections_ = [Metadata_ objectForKey:@"Sections"]; | |
9117 | Sources_ = [Metadata_ objectForKey:@"Sources"]; | |
9118 | ||
9119 | Token_ = [Metadata_ objectForKey:@"Token"]; | |
9120 | } | |
9121 | ||
9122 | if (Settings_ != nil) | |
9123 | Role_ = [Settings_ objectForKey:@"Role"]; | |
9124 | ||
9125 | if (Sections_ == nil) { | |
9126 | Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease]; | |
9127 | [Metadata_ setObject:Sections_ forKey:@"Sections"]; | |
9128 | } | |
9129 | ||
9130 | if (Sources_ == nil) { | |
9131 | Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease]; | |
9132 | [Metadata_ setObject:Sources_ forKey:@"Sources"]; | |
9133 | } | |
9134 | /* }}} */ | |
9135 | ||
9136 | _trace(); | |
9137 | MetaFile_.Open("/var/lib/cydia/metadata.cb0"); | |
9138 | _trace(); | |
9139 | ||
9140 | if (Packages_ != nil) { | |
9141 | CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL); | |
9142 | _trace(); | |
9143 | [Metadata_ removeObjectForKey:@"Packages"]; | |
9144 | Packages_ = nil; | |
9145 | Changed_ = true; | |
9146 | } | |
9147 | ||
9148 | Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil]; | |
9149 | ||
9150 | if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0) | |
9151 | dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL); | |
9152 | if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0) | |
9153 | dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL); | |
9154 | /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0) | |
9155 | dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/ | |
9156 | ||
9157 | int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]); | |
9158 | ||
9159 | if (access("/tmp/.cydia.fw", F_OK) == 0) { | |
9160 | unlink("/tmp/.cydia.fw"); | |
9161 | goto firmware; | |
9162 | } else if (access("/User", F_OK) != 0 || version < 2) { | |
9163 | firmware: | |
9164 | _trace(); | |
9165 | system("/usr/libexec/cydia/firmware.sh"); | |
9166 | _trace(); | |
9167 | } | |
9168 | ||
9169 | _assert([[NSFileManager defaultManager] | |
9170 | createDirectoryAtPath:@"/var/cache/apt/archives/partial" | |
9171 | withIntermediateDirectories:YES | |
9172 | attributes:nil | |
9173 | error:NULL | |
9174 | ]); | |
9175 | ||
9176 | if (access("/tmp/cydia.chk", F_OK) == 0) { | |
9177 | if (unlink("/var/cache/apt/pkgcache.bin") == -1) | |
9178 | _assert(errno == ENOENT); | |
9179 | if (unlink("/var/cache/apt/srcpkgcache.bin") == -1) | |
9180 | _assert(errno == ENOENT); | |
9181 | } | |
9182 | ||
9183 | /* APT Initialization {{{ */ | |
9184 | _assert(pkgInitConfig(*_config)); | |
9185 | _assert(pkgInitSystem(*_config, _system)); | |
9186 | ||
9187 | if (lang != NULL) | |
9188 | _config->Set("APT::Acquire::Translation", lang); | |
9189 | ||
9190 | // XXX: this timeout might be important :( | |
9191 | //_config->Set("Acquire::http::Timeout", 15); | |
9192 | ||
9193 | _config->Set("Acquire::http::MaxParallel", 3); | |
9194 | /* }}} */ | |
9195 | /* Color Choices {{{ */ | |
9196 | space_ = CGColorSpaceCreateDeviceRGB(); | |
9197 | ||
9198 | Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0); | |
9199 | Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0); | |
9200 | Black_.Set(space_, 0.0, 0.0, 0.0, 1.0); | |
9201 | Off_.Set(space_, 0.9, 0.9, 0.9, 1.0); | |
9202 | White_.Set(space_, 1.0, 1.0, 1.0, 1.0); | |
9203 | Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0); | |
9204 | Green_.Set(space_, 0.0, 0.5, 0.0, 1.0); | |
9205 | Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0); | |
9206 | Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0); | |
9207 | ||
9208 | InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f]; | |
9209 | RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f]; | |
9210 | /* }}}*/ | |
9211 | /* UIKit Configuration {{{ */ | |
9212 | void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics"))); | |
9213 | if ($GSFontSetUseLegacyFontMetrics != NULL) | |
9214 | $GSFontSetUseLegacyFontMetrics(YES); | |
9215 | ||
9216 | // XXX: I have a feeling this was important | |
9217 | //UIKeyboardDisableAutomaticAppearance(); | |
9218 | /* }}} */ | |
9219 | ||
9220 | Colon_ = UCLocalize("COLON_DELIMITED"); | |
9221 | Elision_ = UCLocalize("ELISION"); | |
9222 | Error_ = UCLocalize("ERROR"); | |
9223 | Warning_ = UCLocalize("WARNING"); | |
9224 | ||
9225 | _trace(); | |
9226 | int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia")); | |
9227 | ||
9228 | CGColorSpaceRelease(space_); | |
9229 | CFRelease(Locale_); | |
9230 | ||
9231 | return value; | |
9232 | } |