]>
Commit | Line | Data |
---|---|---|
1 | /* Cydia - iPhone UIKit Front-End for Debian APT | |
2 | * Copyright (C) 2008-2015 Jay Freeman (saurik) | |
3 | */ | |
4 | ||
5 | /* GNU General Public License, Version 3 {{{ */ | |
6 | /* | |
7 | * Cydia is free software: you can redistribute it and/or modify | |
8 | * it under the terms of the GNU General Public License as published | |
9 | * by the Free Software Foundation, either version 3 of the License, | |
10 | * or (at your option) any later version. | |
11 | * | |
12 | * Cydia is distributed in the hope that it will be useful, but | |
13 | * WITHOUT ANY WARRANTY; without even the implied warranty of | |
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
15 | * GNU General Public License for more details. | |
16 | * | |
17 | * You should have received a copy of the GNU General Public License | |
18 | * along with Cydia. If not, see <http://www.gnu.org/licenses/>. | |
19 | **/ | |
20 | /* }}} */ | |
21 | ||
22 | // XXX: wtf/FastMalloc.h... wtf? | |
23 | #define USE_SYSTEM_MALLOC 1 | |
24 | ||
25 | /* #include Directives {{{ */ | |
26 | #include "CyteKit/UCPlatform.h" | |
27 | #include "CyteKit/Localize.h" | |
28 | ||
29 | #include <unicode/ustring.h> | |
30 | #include <unicode/utrans.h> | |
31 | ||
32 | #include <objc/objc.h> | |
33 | #include <objc/runtime.h> | |
34 | ||
35 | #include <CoreGraphics/CoreGraphics.h> | |
36 | #include <Foundation/Foundation.h> | |
37 | ||
38 | #if 0 | |
39 | #define DEPLOYMENT_TARGET_MACOSX 1 | |
40 | #define CF_BUILDING_CF 1 | |
41 | #include <CoreFoundation/CFInternal.h> | |
42 | #endif | |
43 | ||
44 | #include <CoreFoundation/CFUniChar.h> | |
45 | ||
46 | #include <SystemConfiguration/SystemConfiguration.h> | |
47 | ||
48 | #include <UIKit/UIKit.h> | |
49 | #include "iPhonePrivate.h" | |
50 | ||
51 | #include <IOKit/IOKitLib.h> | |
52 | ||
53 | #include <QuartzCore/CALayer.h> | |
54 | ||
55 | #include <WebCore/WebCoreThread.h> | |
56 | #include <WebKit/DOMHTMLIFrameElement.h> | |
57 | ||
58 | #include <algorithm> | |
59 | #include <iomanip> | |
60 | #include <set> | |
61 | #include <sstream> | |
62 | #include <string> | |
63 | ||
64 | #include <ext/stdio_filebuf.h> | |
65 | ||
66 | #undef ABS | |
67 | ||
68 | #include <apt-pkg/acquire.h> | |
69 | #include <apt-pkg/acquire-item.h> | |
70 | #include <apt-pkg/algorithms.h> | |
71 | #include <apt-pkg/cachefile.h> | |
72 | #include <apt-pkg/clean.h> | |
73 | #include <apt-pkg/configuration.h> | |
74 | #include <apt-pkg/debindexfile.h> | |
75 | #include <apt-pkg/debmetaindex.h> | |
76 | #include <apt-pkg/error.h> | |
77 | #include <apt-pkg/init.h> | |
78 | #include <apt-pkg/mmap.h> | |
79 | #include <apt-pkg/pkgrecords.h> | |
80 | #include <apt-pkg/sha1.h> | |
81 | #include <apt-pkg/sourcelist.h> | |
82 | #include <apt-pkg/sptr.h> | |
83 | #include <apt-pkg/strutl.h> | |
84 | #include <apt-pkg/tagfile.h> | |
85 | ||
86 | #include <sys/types.h> | |
87 | #include <sys/stat.h> | |
88 | #include <sys/sysctl.h> | |
89 | #include <sys/param.h> | |
90 | #include <sys/mount.h> | |
91 | #include <sys/reboot.h> | |
92 | ||
93 | #include <dirent.h> | |
94 | #include <fcntl.h> | |
95 | #include <notify.h> | |
96 | #include <dlfcn.h> | |
97 | ||
98 | extern "C" { | |
99 | #include <mach-o/nlist.h> | |
100 | } | |
101 | ||
102 | #include <cstdio> | |
103 | #include <cstdlib> | |
104 | #include <cstring> | |
105 | ||
106 | #include <errno.h> | |
107 | ||
108 | #include <Cytore.hpp> | |
109 | #include "Sources.h" | |
110 | ||
111 | #include "Substrate.hpp" | |
112 | #include "Menes/Menes.h" | |
113 | ||
114 | #include "CyteKit/IndirectDelegate.h" | |
115 | #include "CyteKit/RegEx.hpp" | |
116 | #include "CyteKit/TableViewCell.h" | |
117 | #include "CyteKit/TabBarController.h" | |
118 | #include "CyteKit/WebScriptObject-Cyte.h" | |
119 | #include "CyteKit/WebViewController.h" | |
120 | #include "CyteKit/WebViewTableViewCell.h" | |
121 | #include "CyteKit/stringWithUTF8Bytes.h" | |
122 | ||
123 | #include "Cydia/MIMEAddress.h" | |
124 | #include "Cydia/LoadingViewController.h" | |
125 | #include "Cydia/ProgressEvent.h" | |
126 | ||
127 | #include "SDURLCache/SDURLCache.h" | |
128 | /* }}} */ | |
129 | ||
130 | /* Profiler {{{ */ | |
131 | struct timeval _ltv; | |
132 | bool _itv; | |
133 | ||
134 | #define _timestamp ({ \ | |
135 | struct timeval tv; \ | |
136 | gettimeofday(&tv, NULL); \ | |
137 | tv.tv_sec * 1000000 + tv.tv_usec; \ | |
138 | }) | |
139 | ||
140 | typedef std::vector<class ProfileTime *> TimeList; | |
141 | TimeList times_; | |
142 | ||
143 | class ProfileTime { | |
144 | private: | |
145 | const char *name_; | |
146 | uint64_t total_; | |
147 | uint64_t count_; | |
148 | ||
149 | public: | |
150 | ProfileTime(const char *name) : | |
151 | name_(name), | |
152 | total_(0) | |
153 | { | |
154 | times_.push_back(this); | |
155 | } | |
156 | ||
157 | void AddTime(uint64_t time) { | |
158 | total_ += time; | |
159 | ++count_; | |
160 | } | |
161 | ||
162 | void Print() { | |
163 | if (total_ != 0) | |
164 | std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl; | |
165 | total_ = 0; | |
166 | count_ = 0; | |
167 | } | |
168 | }; | |
169 | ||
170 | class ProfileTimer { | |
171 | private: | |
172 | ProfileTime &time_; | |
173 | uint64_t start_; | |
174 | ||
175 | public: | |
176 | ProfileTimer(ProfileTime &time) : | |
177 | time_(time), | |
178 | start_(_timestamp) | |
179 | { | |
180 | } | |
181 | ||
182 | ~ProfileTimer() { | |
183 | time_.AddTime(_timestamp - start_); | |
184 | } | |
185 | }; | |
186 | ||
187 | void PrintTimes() { | |
188 | for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i) | |
189 | (*i)->Print(); | |
190 | std::cerr << "========" << std::endl; | |
191 | } | |
192 | ||
193 | #define _profile(name) { \ | |
194 | static ProfileTime name(#name); \ | |
195 | ProfileTimer _ ## name(name); | |
196 | ||
197 | #define _end } | |
198 | /* }}} */ | |
199 | ||
200 | // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork | |
201 | #define synchronized(lock) \ | |
202 | synchronized(static_cast<NSObject *>(lock)) | |
203 | ||
204 | extern NSString *Cydia_; | |
205 | ||
206 | #define lprintf(args...) fprintf(stderr, args) | |
207 | ||
208 | #define ForRelease 1 | |
209 | #define TraceLogging (1 && !ForRelease) | |
210 | #define HistogramInsertionSort (0 && !ForRelease) | |
211 | #define ProfileTimes (0 && !ForRelease) | |
212 | #define ForSaurik (0 && !ForRelease) | |
213 | #define LogBrowser (0 && !ForRelease) | |
214 | #define TrackResize (0 && !ForRelease) | |
215 | #define ManualRefresh (1 && !ForRelease) | |
216 | #define ShowInternals (0 && !ForRelease) | |
217 | #define AlwaysReload (0 && !ForRelease) | |
218 | ||
219 | #if !TraceLogging | |
220 | #undef _trace | |
221 | #define _trace(args...) | |
222 | #endif | |
223 | ||
224 | #if !ProfileTimes | |
225 | #undef _profile | |
226 | #define _profile(name) { | |
227 | #undef _end | |
228 | #define _end } | |
229 | #define PrintTimes() do {} while (false) | |
230 | #endif | |
231 | ||
232 | // Hash Functions/Structures {{{ | |
233 | extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0); | |
234 | ||
235 | union SplitHash { | |
236 | uint32_t u32; | |
237 | uint16_t u16[2]; | |
238 | }; | |
239 | // }}} | |
240 | ||
241 | static NSString *Colon_; | |
242 | NSString *Elision_; | |
243 | static NSString *Error_; | |
244 | static NSString *Warning_; | |
245 | ||
246 | static NSString *Cache_; | |
247 | #define Cache(file) \ | |
248 | [NSString stringWithFormat:@"%@/%s", Cache_, file] | |
249 | ||
250 | static void (*$SBSSetInterceptsMenuButtonForever)(bool); | |
251 | static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *); | |
252 | ||
253 | static CFStringRef (*$MGCopyAnswer)(CFStringRef); | |
254 | ||
255 | static NSString *UniqueIdentifier(UIDevice *device = nil) { | |
256 | if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x | |
257 | return [device ?: [UIDevice currentDevice] uniqueIdentifier]; | |
258 | else | |
259 | return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease]; | |
260 | } | |
261 | ||
262 | static bool IsReachable(const char *name) { | |
263 | SCNetworkReachabilityFlags flags; { | |
264 | SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name)); | |
265 | SCNetworkReachabilityGetFlags(reachability, &flags); | |
266 | CFRelease(reachability); | |
267 | } | |
268 | ||
269 | // XXX: this elaborate mess is what Apple is using to determine this? :( | |
270 | // XXX: do we care if the user has to intervene? maybe that's ok? | |
271 | return | |
272 | (flags & kSCNetworkReachabilityFlagsReachable) != 0 && ( | |
273 | (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || ( | |
274 | (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 || | |
275 | (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0 | |
276 | ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 || | |
277 | (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0 | |
278 | ) | |
279 | ; | |
280 | } | |
281 | ||
282 | static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); | |
283 | ||
284 | static _finline NSString *CydiaURL(NSString *path) { | |
285 | char page[26]; | |
286 | page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's'; | |
287 | page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y'; | |
288 | page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's'; | |
289 | page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k'; | |
290 | page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/'; | |
291 | page[25] = '\0'; | |
292 | return [[NSString stringWithUTF8String:page] stringByAppendingString:path]; | |
293 | } | |
294 | ||
295 | static NSString *ShellEscape(NSString *value) { | |
296 | return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]]; | |
297 | } | |
298 | ||
299 | static _finline void UpdateExternalStatus(uint64_t newStatus) { | |
300 | int notify_token; | |
301 | if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) { | |
302 | notify_set_state(notify_token, newStatus); | |
303 | notify_cancel(notify_token); | |
304 | } | |
305 | notify_post("com.saurik.Cydia.status"); | |
306 | } | |
307 | ||
308 | static CGFloat CYStatusBarHeight() { | |
309 | CGSize size([[UIApplication sharedApplication] statusBarFrame].size); | |
310 | return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width; | |
311 | } | |
312 | ||
313 | /* NSForcedOrderingSearch doesn't work on the iPhone */ | |
314 | static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch; | |
315 | static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch; | |
316 | static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering; | |
317 | ||
318 | /* Insertion Sort {{{ */ | |
319 | ||
320 | CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) { | |
321 | const char *ptr = (const char *)list; | |
322 | while (0 < count) { | |
323 | CFIndex half = count / 2; | |
324 | const char *probe = ptr + elementSize * half; | |
325 | CFComparisonResult cr = comparator(element, probe, context); | |
326 | if (0 == cr) return (probe - (const char *)list) / elementSize; | |
327 | ptr = (cr < 0) ? ptr : probe + elementSize; | |
328 | count = (cr < 0) ? half : (half + (count & 1) - 1); | |
329 | } | |
330 | return (ptr - (const char *)list) / elementSize; | |
331 | } | |
332 | ||
333 | CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) { | |
334 | const char *ptr = (const char *)list; | |
335 | while (0 < count) { | |
336 | CFIndex half = count / 2; | |
337 | const char *probe = ptr + elementSize * half; | |
338 | CFComparisonResult cr = comparator(element, probe, context); | |
339 | if (0 == cr) return (probe - (const char *)list) / elementSize; | |
340 | ptr = (cr < 0) ? ptr : probe + elementSize; | |
341 | count = (cr < 0) ? half : (half + (count & 1) - 1); | |
342 | } | |
343 | return (ptr - (const char *)list) / elementSize; | |
344 | } | |
345 | ||
346 | void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) { | |
347 | if (range.length == 0) | |
348 | return; | |
349 | const void **values(new const void *[range.length]); | |
350 | CFArrayGetValues(array, range, values); | |
351 | ||
352 | #if HistogramInsertionSort > 0 | |
353 | uint32_t total(0), *offsets(new uint32_t[range.length]); | |
354 | #endif | |
355 | ||
356 | for (CFIndex index(1); index != range.length; ++index) { | |
357 | const void *value(values[index]); | |
358 | //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context)); | |
359 | CFIndex correct(index); | |
360 | while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) { | |
361 | #if HistogramInsertionSort > 1 | |
362 | NSLog(@"%@ < %@", value, values[correct - 1]); | |
363 | #endif | |
364 | if (--correct == 0) | |
365 | break; | |
366 | } | |
367 | if (correct != index) { | |
368 | size_t offset(index - correct); | |
369 | #if HistogramInsertionSort | |
370 | total += offset; | |
371 | ++offsets[offset]; | |
372 | if (offset > 10) | |
373 | NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value); | |
374 | #endif | |
375 | memmove(values + correct + 1, values + correct, sizeof(const void *) * offset); | |
376 | values[correct] = value; | |
377 | } | |
378 | } | |
379 | ||
380 | CFArrayReplaceValues(array, range, values, range.length); | |
381 | delete [] values; | |
382 | ||
383 | #if HistogramInsertionSort > 0 | |
384 | for (CFIndex index(0); index != range.length; ++index) | |
385 | if (offsets[index] != 0) | |
386 | NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]); | |
387 | NSLog(@"Average Insertion Displacement: %f", double(total) / range.length); | |
388 | delete [] offsets; | |
389 | #endif | |
390 | } | |
391 | ||
392 | /* }}} */ | |
393 | ||
394 | /* Apple Bug Fixes {{{ */ | |
395 | @implementation UIWebDocumentView (Cydia) | |
396 | ||
397 | - (void) _setScrollerOffset:(CGPoint)offset { | |
398 | UIScroller *scroller([self _scroller]); | |
399 | ||
400 | CGSize size([scroller contentSize]); | |
401 | CGSize bounds([scroller bounds].size); | |
402 | ||
403 | CGPoint max; | |
404 | max.x = size.width - bounds.width; | |
405 | max.y = size.height - bounds.height; | |
406 | ||
407 | // wtf Apple?! | |
408 | if (max.x < 0) | |
409 | max.x = 0; | |
410 | if (max.y < 0) | |
411 | max.y = 0; | |
412 | ||
413 | offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x; | |
414 | offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y; | |
415 | ||
416 | [scroller setOffset:offset]; | |
417 | } | |
418 | ||
419 | @end | |
420 | /* }}} */ | |
421 | ||
422 | NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) { | |
423 | size_t length([self length] - state->state); | |
424 | if (length <= 0) | |
425 | return 0; | |
426 | else if (length > count) | |
427 | length = count; | |
428 | for (size_t i(0); i != length; ++i) | |
429 | objects[i] = [self item:state->state++]; | |
430 | state->itemsPtr = objects; | |
431 | state->mutationsPtr = (unsigned long *) self; | |
432 | return length; | |
433 | } | |
434 | ||
435 | /* Cydia NSString Additions {{{ */ | |
436 | @interface NSString (Cydia) | |
437 | - (NSComparisonResult) compareByPath:(NSString *)other; | |
438 | - (NSString *) stringByAddingPercentEscapesIncludingReserved; | |
439 | @end | |
440 | ||
441 | @implementation NSString (Cydia) | |
442 | ||
443 | - (NSComparisonResult) compareByPath:(NSString *)other { | |
444 | NSString *prefix = [self commonPrefixWithString:other options:0]; | |
445 | size_t length = [prefix length]; | |
446 | ||
447 | NSRange lrange = NSMakeRange(length, [self length] - length); | |
448 | NSRange rrange = NSMakeRange(length, [other length] - length); | |
449 | ||
450 | lrange = [self rangeOfString:@"/" options:0 range:lrange]; | |
451 | rrange = [other rangeOfString:@"/" options:0 range:rrange]; | |
452 | ||
453 | NSComparisonResult value; | |
454 | ||
455 | if (lrange.location == NSNotFound && rrange.location == NSNotFound) | |
456 | value = NSOrderedSame; | |
457 | else if (lrange.location == NSNotFound) | |
458 | value = NSOrderedAscending; | |
459 | else if (rrange.location == NSNotFound) | |
460 | value = NSOrderedDescending; | |
461 | else | |
462 | value = NSOrderedSame; | |
463 | ||
464 | NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] : | |
465 | [self substringWithRange:NSMakeRange(length, lrange.location - length)]; | |
466 | NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] : | |
467 | [other substringWithRange:NSMakeRange(length, rrange.location - length)]; | |
468 | ||
469 | NSComparisonResult result = [lpath compare:rpath]; | |
470 | return result == NSOrderedSame ? value : result; | |
471 | } | |
472 | ||
473 | - (NSString *) stringByAddingPercentEscapesIncludingReserved { | |
474 | return [(id)CFURLCreateStringByAddingPercentEscapes( | |
475 | kCFAllocatorDefault, | |
476 | (CFStringRef) self, | |
477 | NULL, | |
478 | CFSTR(";/?:@&=+$,"), | |
479 | kCFStringEncodingUTF8 | |
480 | ) autorelease]; | |
481 | } | |
482 | ||
483 | @end | |
484 | /* }}} */ | |
485 | ||
486 | /* C++ NSString Wrapper Cache {{{ */ | |
487 | static _finline CFStringRef CYStringCreate(const char *data, size_t size) { | |
488 | return size == 0 ? NULL : | |
489 | CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?: | |
490 | CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull); | |
491 | } | |
492 | ||
493 | static _finline CFStringRef CYStringCreate(const char *data) { | |
494 | return CYStringCreate(data, strlen(data)); | |
495 | } | |
496 | ||
497 | class CYString { | |
498 | private: | |
499 | char *data_; | |
500 | size_t size_; | |
501 | CFStringRef cache_; | |
502 | ||
503 | _finline void clear_() { | |
504 | if (cache_ != NULL) { | |
505 | CFRelease(cache_); | |
506 | cache_ = NULL; | |
507 | } | |
508 | } | |
509 | ||
510 | public: | |
511 | _finline bool empty() const { | |
512 | return size_ == 0; | |
513 | } | |
514 | ||
515 | _finline size_t size() const { | |
516 | return size_; | |
517 | } | |
518 | ||
519 | _finline char *data() const { | |
520 | return data_; | |
521 | } | |
522 | ||
523 | _finline void clear() { | |
524 | size_ = 0; | |
525 | clear_(); | |
526 | } | |
527 | ||
528 | _finline CYString() : | |
529 | data_(0), | |
530 | size_(0), | |
531 | cache_(NULL) | |
532 | { | |
533 | } | |
534 | ||
535 | _finline ~CYString() { | |
536 | clear_(); | |
537 | } | |
538 | ||
539 | void operator =(const CYString &rhs) { | |
540 | data_ = rhs.data_; | |
541 | size_ = rhs.size_; | |
542 | ||
543 | if (rhs.cache_ == nil) | |
544 | cache_ = NULL; | |
545 | else | |
546 | cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_)); | |
547 | } | |
548 | ||
549 | void copy(CYPool *pool) { | |
550 | char *temp(pool->malloc<char>(size_ + 1)); | |
551 | memcpy(temp, data_, size_); | |
552 | temp[size_] = '\0'; | |
553 | data_ = temp; | |
554 | } | |
555 | ||
556 | void set(CYPool *pool, const char *data, size_t size) { | |
557 | if (size == 0) | |
558 | clear(); | |
559 | else { | |
560 | clear_(); | |
561 | ||
562 | data_ = const_cast<char *>(data); | |
563 | size_ = size; | |
564 | ||
565 | if (pool != NULL) | |
566 | copy(pool); | |
567 | } | |
568 | } | |
569 | ||
570 | _finline void set(CYPool *pool, const char *data) { | |
571 | set(pool, data, data == NULL ? 0 : strlen(data)); | |
572 | } | |
573 | ||
574 | _finline void set(CYPool *pool, const std::string &rhs) { | |
575 | set(pool, rhs.data(), rhs.size()); | |
576 | } | |
577 | ||
578 | bool operator ==(const CYString &rhs) const { | |
579 | return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0; | |
580 | } | |
581 | ||
582 | _finline operator CFStringRef() { | |
583 | if (cache_ == NULL) | |
584 | cache_ = CYStringCreate(data_, size_); | |
585 | return cache_; | |
586 | } | |
587 | ||
588 | _finline operator id() { | |
589 | return (NSString *) static_cast<CFStringRef>(*this); | |
590 | } | |
591 | ||
592 | _finline operator const char *() { | |
593 | return reinterpret_cast<const char *>(data_); | |
594 | } | |
595 | }; | |
596 | /* }}} */ | |
597 | /* C++ NSString Algorithm Adapters {{{ */ | |
598 | extern "C" { | |
599 | CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str); | |
600 | } | |
601 | ||
602 | struct NSStringMapHash : | |
603 | std::unary_function<NSString *, size_t> | |
604 | { | |
605 | _finline size_t operator ()(NSString *value) const { | |
606 | return CFStringHashNSString((CFStringRef) value); | |
607 | } | |
608 | }; | |
609 | ||
610 | struct NSStringMapLess : | |
611 | std::binary_function<NSString *, NSString *, bool> | |
612 | { | |
613 | _finline bool operator ()(NSString *lhs, NSString *rhs) const { | |
614 | return [lhs compare:rhs] == NSOrderedAscending; | |
615 | } | |
616 | }; | |
617 | ||
618 | struct NSStringMapEqual : | |
619 | std::binary_function<NSString *, NSString *, bool> | |
620 | { | |
621 | _finline bool operator ()(NSString *lhs, NSString *rhs) const { | |
622 | return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo; | |
623 | //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs); | |
624 | //[lhs isEqualToString:rhs]; | |
625 | } | |
626 | }; | |
627 | /* }}} */ | |
628 | ||
629 | /* CoreGraphics Primitives {{{ */ | |
630 | class CYColor { | |
631 | private: | |
632 | CGColorRef color_; | |
633 | ||
634 | static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) { | |
635 | CGFloat color[] = {red, green, blue, alpha}; | |
636 | return CGColorCreate(space, color); | |
637 | } | |
638 | ||
639 | public: | |
640 | CYColor() : | |
641 | color_(NULL) | |
642 | { | |
643 | } | |
644 | ||
645 | CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) : | |
646 | color_(Create_(space, red, green, blue, alpha)) | |
647 | { | |
648 | Set(space, red, green, blue, alpha); | |
649 | } | |
650 | ||
651 | void Clear() { | |
652 | if (color_ != NULL) | |
653 | CGColorRelease(color_); | |
654 | } | |
655 | ||
656 | ~CYColor() { | |
657 | Clear(); | |
658 | } | |
659 | ||
660 | void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) { | |
661 | Clear(); | |
662 | color_ = Create_(space, red, green, blue, alpha); | |
663 | } | |
664 | ||
665 | operator CGColorRef() { | |
666 | return color_; | |
667 | } | |
668 | }; | |
669 | /* }}} */ | |
670 | ||
671 | /* Random Global Variables {{{ */ | |
672 | static int PulseInterval_ = 500000; | |
673 | ||
674 | static const NSString *UI_; | |
675 | ||
676 | static int Finish_; | |
677 | static bool RestartSubstrate_; | |
678 | static NSArray *Finishes_; | |
679 | ||
680 | #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist" | |
681 | #define NotifyConfig_ "/etc/notify.conf" | |
682 | ||
683 | static bool Queuing_; | |
684 | ||
685 | static CYColor Blue_; | |
686 | static CYColor Blueish_; | |
687 | static CYColor Black_; | |
688 | static CYColor Folder_; | |
689 | static CYColor Off_; | |
690 | static CYColor White_; | |
691 | static CYColor Gray_; | |
692 | static CYColor Green_; | |
693 | static CYColor Purple_; | |
694 | static CYColor Purplish_; | |
695 | ||
696 | static UIColor *InstallingColor_; | |
697 | static UIColor *RemovingColor_; | |
698 | ||
699 | static NSString *App_; | |
700 | ||
701 | static BOOL Advanced_; | |
702 | static BOOL Ignored_; | |
703 | ||
704 | static _H<UIFont> Font12_; | |
705 | static _H<UIFont> Font12Bold_; | |
706 | static _H<UIFont> Font14_; | |
707 | static _H<UIFont> Font18_; | |
708 | static _H<UIFont> Font18Bold_; | |
709 | static _H<UIFont> Font22Bold_; | |
710 | ||
711 | static const char *Machine_ = NULL; | |
712 | static _H<NSString> System_; | |
713 | static NSString *SerialNumber_ = nil; | |
714 | static NSString *ChipID_ = nil; | |
715 | static NSString *BBSNum_ = nil; | |
716 | static _H<NSString> UniqueID_; | |
717 | static _H<NSString> UserAgent_; | |
718 | static _H<NSString> Product_; | |
719 | static _H<NSString> Safari_; | |
720 | ||
721 | static _H<NSLocale> CollationLocale_; | |
722 | static _H<NSArray> CollationThumbs_; | |
723 | static std::vector<NSInteger> CollationOffset_; | |
724 | static _H<NSArray> CollationTitles_; | |
725 | static _H<NSArray> CollationStarts_; | |
726 | static UTransliterator *CollationTransl_; | |
727 | //static Function<NSString *, NSString *> CollationModify_; | |
728 | ||
729 | typedef std::basic_string<UChar> ustring; | |
730 | static ustring CollationString_; | |
731 | ||
732 | #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep)) | |
733 | #define UC ustring &str(*reinterpret_cast<ustring *>(rep)) | |
734 | static struct UReplaceableCallbacks CollationUCalls_ = { | |
735 | .length = [](const UReplaceable *rep) -> int32_t { CUC; | |
736 | return str.size(); | |
737 | }, | |
738 | ||
739 | .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC; | |
740 | //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size()); | |
741 | if (offset >= str.size()) | |
742 | return 0xffff; | |
743 | return str[offset]; | |
744 | }, | |
745 | ||
746 | .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC; | |
747 | //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size()); | |
748 | if (offset >= str.size()) | |
749 | return 0xffff; | |
750 | UChar32 c; | |
751 | U16_GET(str.data(), 0, offset, str.size(), c); | |
752 | return c; | |
753 | }, | |
754 | ||
755 | .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC; | |
756 | //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size()); | |
757 | str.replace(start, limit - start, text, length); | |
758 | }, | |
759 | ||
760 | .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC; | |
761 | //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size()); | |
762 | str.copy(dst, limit - start, start); | |
763 | }, | |
764 | ||
765 | .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC; | |
766 | //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size()); | |
767 | str.replace(dest, 0, str, start, limit - start); | |
768 | }, | |
769 | }; | |
770 | ||
771 | static CFLocaleRef Locale_; | |
772 | static NSArray *Languages_; | |
773 | static CGColorSpaceRef space_; | |
774 | ||
775 | #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist" | |
776 | #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist" | |
777 | ||
778 | static NSDictionary *SectionMap_; | |
779 | static _H<NSDate> Backgrounded_; | |
780 | static _transient NSMutableDictionary *Values_; | |
781 | static _transient NSMutableDictionary *Sections_; | |
782 | _H<NSMutableDictionary> Sources_; | |
783 | static _transient NSNumber *Version_; | |
784 | static time_t now_; | |
785 | ||
786 | bool IsWildcat_; | |
787 | CGFloat ScreenScale_; | |
788 | static NSString *Idiom_; | |
789 | static _H<NSString> Firmware_; | |
790 | static NSString *Major_; | |
791 | ||
792 | static _H<NSMutableDictionary> SessionData_; | |
793 | static _H<NSObject> HostConfig_; | |
794 | static _H<NSMutableSet> BridgedHosts_; | |
795 | static _H<NSMutableSet> InsecureHosts_; | |
796 | static _H<NSMutableSet> PipelinedHosts_; | |
797 | static _H<NSMutableSet> CachedURLs_; | |
798 | ||
799 | static NSString *kCydiaProgressEventTypeError = @"Error"; | |
800 | static NSString *kCydiaProgressEventTypeInformation = @"Information"; | |
801 | static NSString *kCydiaProgressEventTypeStatus = @"Status"; | |
802 | static NSString *kCydiaProgressEventTypeWarning = @"Warning"; | |
803 | /* }}} */ | |
804 | ||
805 | /* Display Helpers {{{ */ | |
806 | inline float Interpolate(float begin, float end, float fraction) { | |
807 | return (end - begin) * fraction + begin; | |
808 | } | |
809 | ||
810 | static inline double Retina(double value) { | |
811 | value *= ScreenScale_; | |
812 | value = round(value); | |
813 | value /= ScreenScale_; | |
814 | return value; | |
815 | } | |
816 | ||
817 | static inline CGRect Retina(CGRect value) { | |
818 | value.origin.x *= ScreenScale_; | |
819 | value.origin.y *= ScreenScale_; | |
820 | value.size.width *= ScreenScale_; | |
821 | value.size.height *= ScreenScale_; | |
822 | value = CGRectIntegral(value); | |
823 | value.origin.x /= ScreenScale_; | |
824 | value.origin.y /= ScreenScale_; | |
825 | value.size.width /= ScreenScale_; | |
826 | value.size.height /= ScreenScale_; | |
827 | return value; | |
828 | } | |
829 | ||
830 | static _finline const char *StripVersion_(const char *version) { | |
831 | const char *colon(strchr(version, ':')); | |
832 | return colon == NULL ? version : colon + 1; | |
833 | } | |
834 | ||
835 | NSString *LocalizeSection(NSString *section) { | |
836 | static RegEx title_r("(.*?) \\((.*)\\)"); | |
837 | if (title_r(section)) { | |
838 | NSString *parent(title_r[1]); | |
839 | NSString *child(title_r[2]); | |
840 | ||
841 | return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), | |
842 | LocalizeSection(parent), | |
843 | LocalizeSection(child) | |
844 | ]; | |
845 | } | |
846 | ||
847 | return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"]; | |
848 | } | |
849 | ||
850 | NSString *Simplify(NSString *title) { | |
851 | const char *data = [title UTF8String]; | |
852 | size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; | |
853 | ||
854 | static RegEx square_r("\\[(.*)\\]"); | |
855 | if (square_r(data, size)) | |
856 | return Simplify(square_r[1]); | |
857 | ||
858 | static RegEx paren_r("\\((.*)\\)"); | |
859 | if (paren_r(data, size)) | |
860 | return Simplify(paren_r[1]); | |
861 | ||
862 | static RegEx title_r("(.*?) \\((.*)\\)"); | |
863 | if (title_r(data, size)) | |
864 | return Simplify(title_r[1]); | |
865 | ||
866 | return title; | |
867 | } | |
868 | /* }}} */ | |
869 | ||
870 | bool isSectionVisible(NSString *section) { | |
871 | NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]); | |
872 | NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]); | |
873 | return hidden == nil || ![hidden boolValue]; | |
874 | } | |
875 | ||
876 | static NSObject *CYIOGetValue(const char *path, NSString *property) { | |
877 | io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path)); | |
878 | if (entry == MACH_PORT_NULL) | |
879 | return nil; | |
880 | ||
881 | CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0)); | |
882 | IOObjectRelease(entry); | |
883 | ||
884 | if (value == NULL) | |
885 | return nil; | |
886 | return [(id) value autorelease]; | |
887 | } | |
888 | ||
889 | static NSString *CYHex(NSData *data, bool reverse = false) { | |
890 | if (data == nil) | |
891 | return nil; | |
892 | ||
893 | size_t length([data length]); | |
894 | uint8_t bytes[length]; | |
895 | [data getBytes:bytes]; | |
896 | ||
897 | char string[length * 2 + 1]; | |
898 | for (size_t i(0); i != length; ++i) | |
899 | sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]); | |
900 | ||
901 | return [NSString stringWithUTF8String:string]; | |
902 | } | |
903 | ||
904 | static NSString *VerifySource(NSString *href) { | |
905 | static RegEx href_r("(http(s?)://|file:///)[^# ]*"); | |
906 | if (!href_r(href)) { | |
907 | [[[[UIAlertView alloc] | |
908 | initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")] | |
909 | message:UCLocalize("INVALID_URL_EX") | |
910 | delegate:nil | |
911 | cancelButtonTitle:UCLocalize("OK") | |
912 | otherButtonTitles:nil | |
913 | ] autorelease] show]; | |
914 | ||
915 | return nil; | |
916 | } | |
917 | ||
918 | if (![href hasSuffix:@"/"]) | |
919 | href = [href stringByAppendingString:@"/"]; | |
920 | return href; | |
921 | } | |
922 | ||
923 | @class Cydia; | |
924 | ||
925 | /* Delegate Prototypes {{{ */ | |
926 | @class Package; | |
927 | @class Source; | |
928 | @class CydiaProgressEvent; | |
929 | ||
930 | @protocol DatabaseDelegate | |
931 | - (void) repairWithSelector:(SEL)selector; | |
932 | - (void) setConfigurationData:(NSString *)data; | |
933 | - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task; | |
934 | @end | |
935 | ||
936 | @class CYPackageController; | |
937 | ||
938 | @protocol SourceDelegate | |
939 | - (void) setFetch:(NSNumber *)fetch; | |
940 | @end | |
941 | ||
942 | @protocol FetchDelegate | |
943 | - (bool) isSourceCancelled; | |
944 | - (void) startSourceFetch:(NSString *)uri; | |
945 | - (void) stopSourceFetch:(NSString *)uri; | |
946 | @end | |
947 | ||
948 | @protocol CydiaDelegate | |
949 | - (void) returnToCydia; | |
950 | - (void) saveState; | |
951 | - (void) retainNetworkActivityIndicator; | |
952 | - (void) releaseNetworkActivityIndicator; | |
953 | - (void) clearPackage:(Package *)package; | |
954 | - (void) installPackage:(Package *)package; | |
955 | - (void) installPackages:(NSArray *)packages; | |
956 | - (void) removePackage:(Package *)package; | |
957 | - (void) beginUpdate; | |
958 | - (BOOL) updating; | |
959 | - (bool) requestUpdate; | |
960 | - (void) distUpgrade; | |
961 | - (void) loadData; | |
962 | - (void) updateData; | |
963 | - (void) _saveConfig; | |
964 | - (void) syncData; | |
965 | - (void) addSource:(NSDictionary *)source; | |
966 | - (BOOL) addTrivialSource:(NSString *)href; | |
967 | - (UIProgressHUD *) addProgressHUD; | |
968 | - (void) removeProgressHUD:(UIProgressHUD *)hud; | |
969 | - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item; | |
970 | - (void) reloadDataWithInvocation:(NSInvocation *)invocation; | |
971 | @end | |
972 | /* }}} */ | |
973 | ||
974 | /* CancelStatus {{{ */ | |
975 | class CancelStatus : | |
976 | public pkgAcquireStatus | |
977 | { | |
978 | private: | |
979 | bool cancelled_; | |
980 | ||
981 | public: | |
982 | CancelStatus() : | |
983 | cancelled_(false) | |
984 | { | |
985 | } | |
986 | ||
987 | virtual bool MediaChange(std::string media, std::string drive) { | |
988 | return false; | |
989 | } | |
990 | ||
991 | virtual void IMSHit(pkgAcquire::ItemDesc &desc) { | |
992 | Done(desc); | |
993 | } | |
994 | ||
995 | virtual bool Pulse_(pkgAcquire *Owner) = 0; | |
996 | ||
997 | virtual bool Pulse(pkgAcquire *Owner) { | |
998 | if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner)) | |
999 | return true; | |
1000 | else { | |
1001 | cancelled_ = true; | |
1002 | return false; | |
1003 | } | |
1004 | } | |
1005 | ||
1006 | _finline bool WasCancelled() const { | |
1007 | return cancelled_; | |
1008 | } | |
1009 | }; | |
1010 | /* }}} */ | |
1011 | /* DelegateStatus {{{ */ | |
1012 | class CydiaStatus : | |
1013 | public CancelStatus | |
1014 | { | |
1015 | private: | |
1016 | _transient NSObject<ProgressDelegate> *delegate_; | |
1017 | ||
1018 | public: | |
1019 | CydiaStatus() : | |
1020 | delegate_(nil) | |
1021 | { | |
1022 | } | |
1023 | ||
1024 | void setDelegate(NSObject<ProgressDelegate> *delegate) { | |
1025 | delegate_ = delegate; | |
1026 | } | |
1027 | ||
1028 | virtual void Fetch(pkgAcquire::ItemDesc &desc) { | |
1029 | NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]); | |
1030 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]); | |
1031 | [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
1032 | } | |
1033 | ||
1034 | virtual void Done(pkgAcquire::ItemDesc &desc) { | |
1035 | NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]); | |
1036 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]); | |
1037 | [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
1038 | } | |
1039 | ||
1040 | virtual void Fail(pkgAcquire::ItemDesc &desc) { | |
1041 | if ( | |
1042 | desc.Owner->Status == pkgAcquire::Item::StatIdle || | |
1043 | desc.Owner->Status == pkgAcquire::Item::StatDone | |
1044 | ) | |
1045 | return; | |
1046 | ||
1047 | std::string &error(desc.Owner->ErrorText); | |
1048 | if (error.empty()) | |
1049 | return; | |
1050 | ||
1051 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]); | |
1052 | [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
1053 | } | |
1054 | ||
1055 | virtual bool Pulse_(pkgAcquire *Owner) { | |
1056 | double percent( | |
1057 | double(CurrentBytes + CurrentItems) / | |
1058 | double(TotalBytes + TotalItems) | |
1059 | ); | |
1060 | ||
1061 | [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys: | |
1062 | [NSNumber numberWithDouble:percent], @"Percent", | |
1063 | ||
1064 | [NSNumber numberWithDouble:CurrentBytes], @"Current", | |
1065 | [NSNumber numberWithDouble:TotalBytes], @"Total", | |
1066 | [NSNumber numberWithDouble:CurrentCPS], @"Speed", | |
1067 | nil] waitUntilDone:YES]; | |
1068 | ||
1069 | return ![delegate_ isProgressCancelled]; | |
1070 | } | |
1071 | ||
1072 | virtual void Start() { | |
1073 | pkgAcquireStatus::Start(); | |
1074 | [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES]; | |
1075 | } | |
1076 | ||
1077 | virtual void Stop() { | |
1078 | pkgAcquireStatus::Stop(); | |
1079 | [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES]; | |
1080 | [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES]; | |
1081 | } | |
1082 | }; | |
1083 | /* }}} */ | |
1084 | /* Database Interface {{{ */ | |
1085 | typedef std::map< unsigned long, _H<Source> > SourceMap; | |
1086 | ||
1087 | @interface Database : NSObject { | |
1088 | NSZone *zone_; | |
1089 | CYPool pool_; | |
1090 | ||
1091 | unsigned era_; | |
1092 | _H<NSDate> delock_; | |
1093 | ||
1094 | pkgCacheFile cache_; | |
1095 | pkgDepCache::Policy *policy_; | |
1096 | pkgRecords *records_; | |
1097 | pkgProblemResolver *resolver_; | |
1098 | pkgAcquire *fetcher_; | |
1099 | FileFd *lock_; | |
1100 | SPtr<pkgPackageManager> manager_; | |
1101 | pkgSourceList *list_; | |
1102 | ||
1103 | SourceMap sourceMap_; | |
1104 | _H<NSMutableArray> sourceList_; | |
1105 | ||
1106 | CFMutableArrayRef packages_; | |
1107 | ||
1108 | _transient NSObject<DatabaseDelegate> *delegate_; | |
1109 | _transient NSObject<ProgressDelegate> *progress_; | |
1110 | ||
1111 | CydiaStatus status_; | |
1112 | ||
1113 | int cydiafd_; | |
1114 | int statusfd_; | |
1115 | FILE *input_; | |
1116 | ||
1117 | std::map<const char *, _H<NSString> > sections_; | |
1118 | } | |
1119 | ||
1120 | + (Database *) sharedInstance; | |
1121 | - (unsigned) era; | |
1122 | ||
1123 | - (void) _readCydia:(NSNumber *)fd; | |
1124 | - (void) _readStatus:(NSNumber *)fd; | |
1125 | - (void) _readOutput:(NSNumber *)fd; | |
1126 | ||
1127 | - (FILE *) input; | |
1128 | ||
1129 | - (Package *) packageWithName:(NSString *)name; | |
1130 | ||
1131 | - (pkgCacheFile &) cache; | |
1132 | - (pkgDepCache::Policy *) policy; | |
1133 | - (pkgRecords *) records; | |
1134 | - (pkgProblemResolver *) resolver; | |
1135 | - (pkgAcquire &) fetcher; | |
1136 | - (pkgSourceList &) list; | |
1137 | - (NSArray *) packages; | |
1138 | - (NSArray *) sources; | |
1139 | - (Source *) sourceWithKey:(NSString *)key; | |
1140 | - (void) reloadDataWithInvocation:(NSInvocation *)invocation; | |
1141 | ||
1142 | - (void) configure; | |
1143 | - (bool) prepare; | |
1144 | - (void) perform; | |
1145 | - (bool) upgrade; | |
1146 | - (void) update; | |
1147 | ||
1148 | - (void) updateWithStatus:(CancelStatus &)status; | |
1149 | ||
1150 | - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate; | |
1151 | ||
1152 | - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate; | |
1153 | - (NSObject<ProgressDelegate> *) progressDelegate; | |
1154 | ||
1155 | - (Source *) getSource:(pkgCache::PkgFileIterator)file; | |
1156 | - (void) setFetch:(bool)fetch forURI:(const char *)uri; | |
1157 | - (void) resetFetch; | |
1158 | ||
1159 | - (NSString *) mappedSectionForPointer:(const char *)pointer; | |
1160 | ||
1161 | @end | |
1162 | /* }}} */ | |
1163 | /* SourceStatus {{{ */ | |
1164 | class SourceStatus : | |
1165 | public CancelStatus | |
1166 | { | |
1167 | private: | |
1168 | _transient NSObject<FetchDelegate> *delegate_; | |
1169 | _transient Database *database_; | |
1170 | std::set<std::string> fetches_; | |
1171 | ||
1172 | public: | |
1173 | SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) : | |
1174 | delegate_(delegate), | |
1175 | database_(database) | |
1176 | { | |
1177 | } | |
1178 | ||
1179 | void Set(bool fetch, const std::string &uri) { | |
1180 | if (fetch) { | |
1181 | if (!fetches_.insert(uri).second) | |
1182 | return; | |
1183 | } else { | |
1184 | if (fetches_.erase(uri) == 0) | |
1185 | return; | |
1186 | } | |
1187 | ||
1188 | //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str()); | |
1189 | [database_ setFetch:fetch forURI:uri.c_str()]; | |
1190 | } | |
1191 | ||
1192 | _finline void Set(bool fetch, pkgAcquire::Item *item) { | |
1193 | /*unsigned long ID(fetch ? 1 : 0); | |
1194 | if (item->ID == ID) | |
1195 | return; | |
1196 | item->ID = ID;*/ | |
1197 | Set(fetch, item->DescURI()); | |
1198 | } | |
1199 | ||
1200 | void Log(const char *tag, pkgAcquire::Item *item) { | |
1201 | //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter); | |
1202 | } | |
1203 | ||
1204 | virtual void Fetch(pkgAcquire::ItemDesc &desc) { | |
1205 | Log("Fetch", desc.Owner); | |
1206 | Set(true, desc.Owner); | |
1207 | } | |
1208 | ||
1209 | virtual void Done(pkgAcquire::ItemDesc &desc) { | |
1210 | Log("Done", desc.Owner); | |
1211 | Set(false, desc.Owner); | |
1212 | } | |
1213 | ||
1214 | virtual void Fail(pkgAcquire::ItemDesc &desc) { | |
1215 | Log("Fail", desc.Owner); | |
1216 | Set(false, desc.Owner); | |
1217 | } | |
1218 | ||
1219 | virtual bool Pulse_(pkgAcquire *Owner) { | |
1220 | std::set<std::string> fetches; | |
1221 | for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) { | |
1222 | bool fetch; | |
1223 | if ((*item)->QueueCounter == 0) | |
1224 | fetch = false; | |
1225 | else switch ((*item)->Status) { | |
1226 | case pkgAcquire::Item::StatFetching: | |
1227 | fetches.insert((*item)->DescURI()); | |
1228 | fetch = true; | |
1229 | break; | |
1230 | ||
1231 | default: | |
1232 | fetch = false; | |
1233 | break; | |
1234 | } | |
1235 | ||
1236 | Log(fetch ? "Pulse<true>" : "Pulse<false>", *item); | |
1237 | Set(fetch, *item); | |
1238 | } | |
1239 | ||
1240 | std::vector<std::string> stops; | |
1241 | std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops)); | |
1242 | for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) { | |
1243 | //printf("Stop(%s)\n", stop->c_str()); | |
1244 | Set(false, *stop); | |
1245 | } | |
1246 | ||
1247 | return ![delegate_ isSourceCancelled]; | |
1248 | } | |
1249 | ||
1250 | virtual void Stop() { | |
1251 | pkgAcquireStatus::Stop(); | |
1252 | [database_ resetFetch]; | |
1253 | } | |
1254 | }; | |
1255 | /* }}} */ | |
1256 | /* ProgressEvent Implementation {{{ */ | |
1257 | @implementation CydiaProgressEvent | |
1258 | ||
1259 | + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type { | |
1260 | return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease]; | |
1261 | } | |
1262 | ||
1263 | + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package { | |
1264 | CydiaProgressEvent *event([self eventWithMessage:message ofType:type]); | |
1265 | [event setPackage:package]; | |
1266 | return event; | |
1267 | } | |
1268 | ||
1269 | + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc { | |
1270 | CydiaProgressEvent *event([self eventWithMessage:message ofType:type]); | |
1271 | ||
1272 | NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]); | |
1273 | NSArray *fields([description componentsSeparatedByString:@" "]); | |
1274 | [event setItem:fields]; | |
1275 | ||
1276 | if ([fields count] > 3) { | |
1277 | [event setPackage:[fields objectAtIndex:2]]; | |
1278 | [event setVersion:[fields objectAtIndex:3]]; | |
1279 | } | |
1280 | ||
1281 | [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]]; | |
1282 | ||
1283 | return event; | |
1284 | } | |
1285 | ||
1286 | + (NSArray *) _attributeKeys { | |
1287 | return [NSArray arrayWithObjects: | |
1288 | @"item", | |
1289 | @"message", | |
1290 | @"package", | |
1291 | @"type", | |
1292 | @"url", | |
1293 | @"version", | |
1294 | nil]; | |
1295 | } | |
1296 | ||
1297 | - (NSArray *) attributeKeys { | |
1298 | return [[self class] _attributeKeys]; | |
1299 | } | |
1300 | ||
1301 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
1302 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
1303 | } | |
1304 | ||
1305 | - (id) initWithMessage:(NSString *)message ofType:(NSString *)type { | |
1306 | if ((self = [super init]) != nil) { | |
1307 | message_ = message; | |
1308 | type_ = type; | |
1309 | } return self; | |
1310 | } | |
1311 | ||
1312 | - (NSString *) message { | |
1313 | return message_; | |
1314 | } | |
1315 | ||
1316 | - (NSString *) type { | |
1317 | return type_; | |
1318 | } | |
1319 | ||
1320 | - (NSArray *) item { | |
1321 | return (id) item_ ?: [NSNull null]; | |
1322 | } | |
1323 | ||
1324 | - (void) setItem:(NSArray *)item { | |
1325 | item_ = item; | |
1326 | } | |
1327 | ||
1328 | - (NSString *) package { | |
1329 | return (id) package_ ?: [NSNull null]; | |
1330 | } | |
1331 | ||
1332 | - (void) setPackage:(NSString *)package { | |
1333 | package_ = package; | |
1334 | } | |
1335 | ||
1336 | - (NSString *) url { | |
1337 | return (id) url_ ?: [NSNull null]; | |
1338 | } | |
1339 | ||
1340 | - (void) setURL:(NSString *)url { | |
1341 | url_ = url; | |
1342 | } | |
1343 | ||
1344 | - (void) setVersion:(NSString *)version { | |
1345 | version_ = version; | |
1346 | } | |
1347 | ||
1348 | - (NSString *) version { | |
1349 | return (id) version_ ?: [NSNull null]; | |
1350 | } | |
1351 | ||
1352 | - (NSString *) compound:(NSString *)value { | |
1353 | if (value != nil) { | |
1354 | NSString *mode(nil); { | |
1355 | NSString *type([self type]); | |
1356 | if ([type isEqualToString:kCydiaProgressEventTypeError]) | |
1357 | mode = UCLocalize("ERROR"); | |
1358 | else if ([type isEqualToString:kCydiaProgressEventTypeWarning]) | |
1359 | mode = UCLocalize("WARNING"); | |
1360 | } | |
1361 | ||
1362 | if (mode != nil) | |
1363 | value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value]; | |
1364 | } | |
1365 | ||
1366 | return value; | |
1367 | } | |
1368 | ||
1369 | - (NSString *) compoundMessage { | |
1370 | return [self compound:[self message]]; | |
1371 | } | |
1372 | ||
1373 | - (NSString *) compoundTitle { | |
1374 | NSString *title; | |
1375 | ||
1376 | if (package_ == nil) | |
1377 | title = nil; | |
1378 | else if (Package *package = [[Database sharedInstance] packageWithName:package_]) | |
1379 | title = [package name]; | |
1380 | else | |
1381 | title = package_; | |
1382 | ||
1383 | return [self compound:title]; | |
1384 | } | |
1385 | ||
1386 | @end | |
1387 | /* }}} */ | |
1388 | ||
1389 | // Cytore Definitions {{{ | |
1390 | struct PackageValue : | |
1391 | Cytore::Block | |
1392 | { | |
1393 | Cytore::Offset<PackageValue> next_; | |
1394 | ||
1395 | uint32_t index_ : 23; | |
1396 | uint32_t subscribed_ : 1; | |
1397 | uint32_t : 8; | |
1398 | ||
1399 | int32_t first_; | |
1400 | int32_t last_; | |
1401 | ||
1402 | uint16_t vhash_; | |
1403 | uint16_t nhash_; | |
1404 | ||
1405 | char version_[8]; | |
1406 | char name_[]; | |
1407 | }; | |
1408 | ||
1409 | struct MetaValue : | |
1410 | Cytore::Block | |
1411 | { | |
1412 | uint32_t active_; | |
1413 | Cytore::Offset<PackageValue> packages_[1 << 16]; | |
1414 | }; | |
1415 | ||
1416 | static Cytore::File<MetaValue> MetaFile_; | |
1417 | // }}} | |
1418 | // Cytore Helper Functions {{{ | |
1419 | static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) { | |
1420 | SplitHash nhash = { hashlittle(name, length) }; | |
1421 | ||
1422 | PackageValue *metadata; | |
1423 | ||
1424 | Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]); | |
1425 | for (;; offset = &metadata->next_) { if (offset->IsNull()) { | |
1426 | *offset = MetaFile_.New<PackageValue>(length + 1); | |
1427 | metadata = &MetaFile_.Get(*offset); | |
1428 | ||
1429 | if (metadata == NULL) { | |
1430 | if (fail != NULL) | |
1431 | *fail = true; | |
1432 | ||
1433 | metadata = new PackageValue(); | |
1434 | memset(metadata, 0, sizeof(*metadata)); | |
1435 | } | |
1436 | ||
1437 | memcpy(metadata->name_, name, length); | |
1438 | metadata->name_[length] = '\0'; | |
1439 | metadata->nhash_ = nhash.u16[1]; | |
1440 | } else { | |
1441 | metadata = &MetaFile_.Get(*offset); | |
1442 | if (metadata->nhash_ != nhash.u16[1]) | |
1443 | continue; | |
1444 | if (strncmp(metadata->name_, name, length) != 0) | |
1445 | continue; | |
1446 | if (metadata->name_[length] != '\0') | |
1447 | continue; | |
1448 | } break; } | |
1449 | ||
1450 | return metadata; | |
1451 | } | |
1452 | ||
1453 | static void PackageImport(const void *key, const void *value, void *context) { | |
1454 | bool &fail(*reinterpret_cast<bool *>(context)); | |
1455 | ||
1456 | char buffer[1024]; | |
1457 | if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) { | |
1458 | NSLog(@"failed to import package %@", key); | |
1459 | return; | |
1460 | } | |
1461 | ||
1462 | PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail)); | |
1463 | NSDictionary *package((NSDictionary *) value); | |
1464 | ||
1465 | if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"]) | |
1466 | if ([subscribed boolValue] && !metadata->subscribed_) | |
1467 | metadata->subscribed_ = true; | |
1468 | ||
1469 | if (NSDate *date = [package objectForKey:@"FirstSeen"]) { | |
1470 | time_t time([date timeIntervalSince1970]); | |
1471 | if (metadata->first_ > time || metadata->first_ == 0) | |
1472 | metadata->first_ = time; | |
1473 | } | |
1474 | ||
1475 | NSDate *date([package objectForKey:@"LastSeen"]); | |
1476 | NSString *version([package objectForKey:@"LastVersion"]); | |
1477 | ||
1478 | if (date != nil && version != nil) { | |
1479 | time_t time([date timeIntervalSince1970]); | |
1480 | if (metadata->last_ < time || metadata->last_ == 0) | |
1481 | if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) { | |
1482 | size_t length(strlen(buffer)); | |
1483 | uint16_t vhash(hashlittle(buffer, length)); | |
1484 | ||
1485 | size_t capped(std::min<size_t>(8, length)); | |
1486 | char *latest(buffer + length - capped); | |
1487 | ||
1488 | strncpy(metadata->version_, latest, sizeof(metadata->version_)); | |
1489 | metadata->vhash_ = vhash; | |
1490 | ||
1491 | metadata->last_ = time; | |
1492 | } | |
1493 | } | |
1494 | } | |
1495 | // }}} | |
1496 | ||
1497 | static NSDate *GetStatusDate() { | |
1498 | return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate]; | |
1499 | } | |
1500 | ||
1501 | static void SaveConfig(NSObject *lock) { | |
1502 | @synchronized (lock) { | |
1503 | _trace(); | |
1504 | MetaFile_.Sync(); | |
1505 | _trace(); | |
1506 | } | |
1507 | ||
1508 | CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys: | |
1509 | Values_, @"CydiaValues", | |
1510 | Sections_, @"CydiaSections", | |
1511 | (id) Sources_, @"CydiaSources", | |
1512 | Version_, @"CydiaVersion", | |
1513 | nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost); | |
1514 | ||
1515 | if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia"))) | |
1516 | NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false"); | |
1517 | ||
1518 | CydiaWriteSources(); | |
1519 | } | |
1520 | ||
1521 | /* Source Class {{{ */ | |
1522 | @interface Source : NSObject { | |
1523 | unsigned era_; | |
1524 | Database *database_; | |
1525 | metaIndex *index_; | |
1526 | ||
1527 | CYString depiction_; | |
1528 | CYString description_; | |
1529 | CYString label_; | |
1530 | CYString origin_; | |
1531 | CYString support_; | |
1532 | ||
1533 | CYString uri_; | |
1534 | CYString distribution_; | |
1535 | CYString type_; | |
1536 | CYString base_; | |
1537 | CYString version_; | |
1538 | ||
1539 | _H<NSString> host_; | |
1540 | _H<NSString> authority_; | |
1541 | ||
1542 | CYString defaultIcon_; | |
1543 | ||
1544 | _H<NSMutableDictionary> record_; | |
1545 | BOOL trusted_; | |
1546 | ||
1547 | std::set<std::string> fetches_; | |
1548 | std::set<std::string> files_; | |
1549 | _transient NSObject<SourceDelegate> *delegate_; | |
1550 | } | |
1551 | ||
1552 | - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool; | |
1553 | ||
1554 | - (NSComparisonResult) compareByName:(Source *)source; | |
1555 | ||
1556 | - (NSString *) depictionForPackage:(NSString *)package; | |
1557 | - (NSString *) supportForPackage:(NSString *)package; | |
1558 | ||
1559 | - (metaIndex *) metaIndex; | |
1560 | - (NSDictionary *) record; | |
1561 | - (BOOL) trusted; | |
1562 | ||
1563 | - (NSString *) rooturi; | |
1564 | - (NSString *) distribution; | |
1565 | - (NSString *) type; | |
1566 | ||
1567 | - (NSString *) key; | |
1568 | - (NSString *) host; | |
1569 | ||
1570 | - (NSString *) name; | |
1571 | - (NSString *) shortDescription; | |
1572 | - (NSString *) label; | |
1573 | - (NSString *) origin; | |
1574 | - (NSString *) version; | |
1575 | ||
1576 | - (NSString *) defaultIcon; | |
1577 | - (NSURL *) iconURL; | |
1578 | ||
1579 | - (void) setFetch:(bool)fetch forURI:(const char *)uri; | |
1580 | - (void) resetFetch; | |
1581 | ||
1582 | @end | |
1583 | ||
1584 | @implementation Source | |
1585 | ||
1586 | + (NSString *) webScriptNameForSelector:(SEL)selector { | |
1587 | if (false); | |
1588 | else if (selector == @selector(addSection:)) | |
1589 | return @"addSection"; | |
1590 | else if (selector == @selector(getField:)) | |
1591 | return @"getField"; | |
1592 | else if (selector == @selector(removeSection:)) | |
1593 | return @"removeSection"; | |
1594 | else if (selector == @selector(remove)) | |
1595 | return @"remove"; | |
1596 | else | |
1597 | return nil; | |
1598 | } | |
1599 | ||
1600 | + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector { | |
1601 | return [self webScriptNameForSelector:selector] == nil; | |
1602 | } | |
1603 | ||
1604 | + (NSArray *) _attributeKeys { | |
1605 | return [NSArray arrayWithObjects: | |
1606 | @"baseuri", | |
1607 | @"distribution", | |
1608 | @"host", | |
1609 | @"key", | |
1610 | @"iconuri", | |
1611 | @"label", | |
1612 | @"name", | |
1613 | @"origin", | |
1614 | @"rooturi", | |
1615 | @"sections", | |
1616 | @"shortDescription", | |
1617 | @"trusted", | |
1618 | @"type", | |
1619 | @"version", | |
1620 | nil]; | |
1621 | } | |
1622 | ||
1623 | - (NSArray *) attributeKeys { | |
1624 | return [[self class] _attributeKeys]; | |
1625 | } | |
1626 | ||
1627 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
1628 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
1629 | } | |
1630 | ||
1631 | - (metaIndex *) metaIndex { | |
1632 | return index_; | |
1633 | } | |
1634 | ||
1635 | - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool { | |
1636 | trusted_ = index->IsTrusted(); | |
1637 | ||
1638 | uri_.set(pool, index->GetURI()); | |
1639 | distribution_.set(pool, index->GetDist()); | |
1640 | type_.set(pool, index->GetType()); | |
1641 | ||
1642 | debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index)); | |
1643 | if (dindex != NULL) { | |
1644 | std::string file(dindex->MetaIndexURI("")); | |
1645 | base_.set(pool, file); | |
1646 | ||
1647 | pkgAcquire acquire; | |
1648 | _profile(Source$setMetaIndex$GetIndexes) | |
1649 | dindex->GetIndexes(&acquire, true); | |
1650 | _end | |
1651 | _profile(Source$setMetaIndex$DescURI) | |
1652 | for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) { | |
1653 | std::string file((*item)->DescURI()); | |
1654 | files_.insert(file); | |
1655 | if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2") | |
1656 | continue; | |
1657 | file = file.substr(0, file.length() - 4); | |
1658 | files_.insert(file); | |
1659 | files_.insert(file + ".gz"); | |
1660 | files_.insert(file + "Index"); | |
1661 | } | |
1662 | _end | |
1663 | ||
1664 | FileFd fd; | |
1665 | if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) | |
1666 | _error->Discard(); | |
1667 | else { | |
1668 | pkgTagFile tags(&fd); | |
1669 | ||
1670 | pkgTagSection section; | |
1671 | tags.Step(section); | |
1672 | ||
1673 | struct { | |
1674 | const char *name_; | |
1675 | CYString *value_; | |
1676 | } names[] = { | |
1677 | {"default-icon", &defaultIcon_}, | |
1678 | {"depiction", &depiction_}, | |
1679 | {"description", &description_}, | |
1680 | {"label", &label_}, | |
1681 | {"origin", &origin_}, | |
1682 | {"support", &support_}, | |
1683 | {"version", &version_}, | |
1684 | }; | |
1685 | ||
1686 | for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) { | |
1687 | const char *start, *end; | |
1688 | ||
1689 | if (section.Find(names[i].name_, start, end)) { | |
1690 | CYString &value(*names[i].value_); | |
1691 | value.set(pool, start, end - start); | |
1692 | } | |
1693 | } | |
1694 | } | |
1695 | } | |
1696 | ||
1697 | record_ = [Sources_ objectForKey:[self key]]; | |
1698 | ||
1699 | NSURL *url([NSURL URLWithString:uri_]); | |
1700 | ||
1701 | host_ = [url host]; | |
1702 | if (host_ != nil) | |
1703 | host_ = [host_ lowercaseString]; | |
1704 | ||
1705 | if (host_ != nil) | |
1706 | authority_ = host_; | |
1707 | else | |
1708 | authority_ = [url path]; | |
1709 | } | |
1710 | ||
1711 | - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool { | |
1712 | if ((self = [super init]) != nil) { | |
1713 | era_ = [database era]; | |
1714 | database_ = database; | |
1715 | index_ = index; | |
1716 | ||
1717 | _profile(Source$initWithMetaIndex$setMetaIndex) | |
1718 | [self setMetaIndex:index inPool:pool]; | |
1719 | _end | |
1720 | } return self; | |
1721 | } | |
1722 | ||
1723 | - (NSString *) getField:(NSString *)name { | |
1724 | @synchronized (database_) { | |
1725 | if ([database_ era] != era_ || index_ == NULL) | |
1726 | return nil; | |
1727 | ||
1728 | debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_)); | |
1729 | if (dindex == NULL) | |
1730 | return nil; | |
1731 | ||
1732 | FileFd fd; | |
1733 | if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) { | |
1734 | _error->Discard(); | |
1735 | return nil; | |
1736 | } | |
1737 | ||
1738 | pkgTagFile tags(&fd); | |
1739 | ||
1740 | pkgTagSection section; | |
1741 | tags.Step(section); | |
1742 | ||
1743 | const char *start, *end; | |
1744 | if (!section.Find([name UTF8String], start, end)) | |
1745 | return (NSString *) [NSNull null]; | |
1746 | ||
1747 | return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]]; | |
1748 | } } | |
1749 | ||
1750 | - (NSComparisonResult) compareByName:(Source *)source { | |
1751 | NSString *lhs = [self name]; | |
1752 | NSString *rhs = [source name]; | |
1753 | ||
1754 | if ([lhs length] != 0 && [rhs length] != 0) { | |
1755 | unichar lhc = [lhs characterAtIndex:0]; | |
1756 | unichar rhc = [rhs characterAtIndex:0]; | |
1757 | ||
1758 | if (isalpha(lhc) && !isalpha(rhc)) | |
1759 | return NSOrderedAscending; | |
1760 | else if (!isalpha(lhc) && isalpha(rhc)) | |
1761 | return NSOrderedDescending; | |
1762 | } | |
1763 | ||
1764 | return [lhs compare:rhs options:LaxCompareOptions_]; | |
1765 | } | |
1766 | ||
1767 | - (NSString *) depictionForPackage:(NSString *)package { | |
1768 | return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package]; | |
1769 | } | |
1770 | ||
1771 | - (NSString *) supportForPackage:(NSString *)package { | |
1772 | return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package]; | |
1773 | } | |
1774 | ||
1775 | - (NSArray *) sections { | |
1776 | return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array]; | |
1777 | } | |
1778 | ||
1779 | - (void) _addSection:(NSString *)section { | |
1780 | if (record_ == nil) | |
1781 | return; | |
1782 | else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) { | |
1783 | if (![sections containsObject:section]) | |
1784 | [sections addObject:section]; | |
1785 | } else | |
1786 | [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"]; | |
1787 | } | |
1788 | ||
1789 | - (bool) addSection:(NSString *)section { | |
1790 | if (record_ == nil) | |
1791 | return false; | |
1792 | ||
1793 | [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO]; | |
1794 | return true; | |
1795 | } | |
1796 | ||
1797 | - (void) _removeSection:(NSString *)section { | |
1798 | if (record_ == nil) | |
1799 | return; | |
1800 | ||
1801 | if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) | |
1802 | if ([sections containsObject:section]) | |
1803 | [sections removeObject:section]; | |
1804 | } | |
1805 | ||
1806 | - (bool) removeSection:(NSString *)section { | |
1807 | if (record_ == nil) | |
1808 | return false; | |
1809 | ||
1810 | [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO]; | |
1811 | return true; | |
1812 | } | |
1813 | ||
1814 | - (void) _remove { | |
1815 | [Sources_ removeObjectForKey:[self key]]; | |
1816 | } | |
1817 | ||
1818 | - (bool) remove { | |
1819 | bool value(record_ != nil); | |
1820 | [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO]; | |
1821 | return value; | |
1822 | } | |
1823 | ||
1824 | - (NSDictionary *) record { | |
1825 | return record_; | |
1826 | } | |
1827 | ||
1828 | - (BOOL) trusted { | |
1829 | return trusted_; | |
1830 | } | |
1831 | ||
1832 | - (NSString *) rooturi { | |
1833 | return uri_; | |
1834 | } | |
1835 | ||
1836 | - (NSString *) distribution { | |
1837 | return distribution_; | |
1838 | } | |
1839 | ||
1840 | - (NSString *) type { | |
1841 | return type_; | |
1842 | } | |
1843 | ||
1844 | - (NSString *) baseuri { | |
1845 | return base_.empty() ? nil : (id) base_; | |
1846 | } | |
1847 | ||
1848 | - (NSString *) iconuri { | |
1849 | if (NSString *base = [self baseuri]) | |
1850 | return [base stringByAppendingString:@"CydiaIcon.png"]; | |
1851 | ||
1852 | return nil; | |
1853 | } | |
1854 | ||
1855 | - (NSURL *) iconURL { | |
1856 | if (NSString *uri = [self iconuri]) | |
1857 | return [NSURL URLWithString:uri]; | |
1858 | return nil; | |
1859 | } | |
1860 | ||
1861 | - (NSString *) key { | |
1862 | return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_]; | |
1863 | } | |
1864 | ||
1865 | - (NSString *) host { | |
1866 | return host_; | |
1867 | } | |
1868 | ||
1869 | - (NSString *) name { | |
1870 | return origin_.empty() ? (id) authority_ : origin_; | |
1871 | } | |
1872 | ||
1873 | - (NSString *) shortDescription { | |
1874 | return description_; | |
1875 | } | |
1876 | ||
1877 | - (NSString *) label { | |
1878 | return label_.empty() ? (id) authority_ : label_; | |
1879 | } | |
1880 | ||
1881 | - (NSString *) origin { | |
1882 | return origin_; | |
1883 | } | |
1884 | ||
1885 | - (NSString *) version { | |
1886 | return version_; | |
1887 | } | |
1888 | ||
1889 | - (NSString *) defaultIcon { | |
1890 | return defaultIcon_; | |
1891 | } | |
1892 | ||
1893 | - (void) setDelegate:(NSObject<SourceDelegate> *)delegate { | |
1894 | delegate_ = delegate; | |
1895 | } | |
1896 | ||
1897 | - (bool) fetch { | |
1898 | return !fetches_.empty(); | |
1899 | } | |
1900 | ||
1901 | - (void) setFetch:(bool)fetch forURI:(const char *)uri { | |
1902 | if (!fetch) { | |
1903 | if (fetches_.erase(uri) == 0) | |
1904 | return; | |
1905 | } else if (files_.find(uri) == files_.end()) | |
1906 | return; | |
1907 | else if (!fetches_.insert(uri).second) | |
1908 | return; | |
1909 | ||
1910 | [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO]; | |
1911 | } | |
1912 | ||
1913 | - (void) resetFetch { | |
1914 | fetches_.clear(); | |
1915 | [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO]; | |
1916 | } | |
1917 | ||
1918 | @end | |
1919 | /* }}} */ | |
1920 | /* CydiaOperation Class {{{ */ | |
1921 | @interface CydiaOperation : NSObject { | |
1922 | _H<NSString> operator_; | |
1923 | _H<NSString> value_; | |
1924 | } | |
1925 | ||
1926 | - (NSString *) operator; | |
1927 | - (NSString *) value; | |
1928 | ||
1929 | @end | |
1930 | ||
1931 | @implementation CydiaOperation | |
1932 | ||
1933 | - (id) initWithOperator:(const char *)_operator value:(const char *)value { | |
1934 | if ((self = [super init]) != nil) { | |
1935 | operator_ = [NSString stringWithUTF8String:_operator]; | |
1936 | value_ = [NSString stringWithUTF8String:value]; | |
1937 | } return self; | |
1938 | } | |
1939 | ||
1940 | + (NSArray *) _attributeKeys { | |
1941 | return [NSArray arrayWithObjects: | |
1942 | @"operator", | |
1943 | @"value", | |
1944 | nil]; | |
1945 | } | |
1946 | ||
1947 | - (NSArray *) attributeKeys { | |
1948 | return [[self class] _attributeKeys]; | |
1949 | } | |
1950 | ||
1951 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
1952 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
1953 | } | |
1954 | ||
1955 | - (NSString *) operator { | |
1956 | return operator_; | |
1957 | } | |
1958 | ||
1959 | - (NSString *) value { | |
1960 | return value_; | |
1961 | } | |
1962 | ||
1963 | @end | |
1964 | /* }}} */ | |
1965 | /* CydiaClause Class {{{ */ | |
1966 | @interface CydiaClause : NSObject { | |
1967 | _H<NSString> package_; | |
1968 | _H<CydiaOperation> version_; | |
1969 | } | |
1970 | ||
1971 | - (NSString *) package; | |
1972 | - (CydiaOperation *) version; | |
1973 | ||
1974 | @end | |
1975 | ||
1976 | @implementation CydiaClause | |
1977 | ||
1978 | - (id) initWithIterator:(pkgCache::DepIterator &)dep { | |
1979 | if ((self = [super init]) != nil) { | |
1980 | package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()]; | |
1981 | ||
1982 | if (const char *version = dep.TargetVer()) | |
1983 | version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease]; | |
1984 | else | |
1985 | version_ = (id) [NSNull null]; | |
1986 | } return self; | |
1987 | } | |
1988 | ||
1989 | + (NSArray *) _attributeKeys { | |
1990 | return [NSArray arrayWithObjects: | |
1991 | @"package", | |
1992 | @"version", | |
1993 | nil]; | |
1994 | } | |
1995 | ||
1996 | - (NSArray *) attributeKeys { | |
1997 | return [[self class] _attributeKeys]; | |
1998 | } | |
1999 | ||
2000 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
2001 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
2002 | } | |
2003 | ||
2004 | - (NSString *) package { | |
2005 | return package_; | |
2006 | } | |
2007 | ||
2008 | - (CydiaOperation *) version { | |
2009 | return version_; | |
2010 | } | |
2011 | ||
2012 | @end | |
2013 | /* }}} */ | |
2014 | /* CydiaRelation Class {{{ */ | |
2015 | @interface CydiaRelation : NSObject { | |
2016 | _H<NSString> relationship_; | |
2017 | _H<NSMutableArray> clauses_; | |
2018 | } | |
2019 | ||
2020 | - (NSString *) relationship; | |
2021 | - (NSArray *) clauses; | |
2022 | ||
2023 | @end | |
2024 | ||
2025 | @implementation CydiaRelation | |
2026 | ||
2027 | - (id) initWithIterator:(pkgCache::DepIterator &)dep { | |
2028 | if ((self = [super init]) != nil) { | |
2029 | relationship_ = [NSString stringWithUTF8String:dep.DepType()]; | |
2030 | clauses_ = [NSMutableArray arrayWithCapacity:8]; | |
2031 | ||
2032 | pkgCache::DepIterator start; | |
2033 | pkgCache::DepIterator end; | |
2034 | dep.GlobOr(start, end); // ++dep | |
2035 | ||
2036 | _forever { | |
2037 | [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]]; | |
2038 | ||
2039 | // yes, seriously. (wtf?) | |
2040 | if (start == end) | |
2041 | break; | |
2042 | ++start; | |
2043 | } | |
2044 | } return self; | |
2045 | } | |
2046 | ||
2047 | + (NSArray *) _attributeKeys { | |
2048 | return [NSArray arrayWithObjects: | |
2049 | @"clauses", | |
2050 | @"relationship", | |
2051 | nil]; | |
2052 | } | |
2053 | ||
2054 | - (NSArray *) attributeKeys { | |
2055 | return [[self class] _attributeKeys]; | |
2056 | } | |
2057 | ||
2058 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
2059 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
2060 | } | |
2061 | ||
2062 | - (NSString *) relationship { | |
2063 | return relationship_; | |
2064 | } | |
2065 | ||
2066 | - (NSArray *) clauses { | |
2067 | return clauses_; | |
2068 | } | |
2069 | ||
2070 | - (void) addClause:(CydiaClause *)clause { | |
2071 | [clauses_ addObject:clause]; | |
2072 | } | |
2073 | ||
2074 | @end | |
2075 | /* }}} */ | |
2076 | /* Package Class {{{ */ | |
2077 | struct ParsedPackage { | |
2078 | CYString md5sum_; | |
2079 | CYString tagline_; | |
2080 | ||
2081 | CYString architecture_; | |
2082 | CYString icon_; | |
2083 | ||
2084 | CYString depiction_; | |
2085 | CYString homepage_; | |
2086 | CYString author_; | |
2087 | ||
2088 | CYString support_; | |
2089 | }; | |
2090 | ||
2091 | @interface Package : NSObject { | |
2092 | uint32_t era_ : 25; | |
2093 | @public uint32_t role_ : 3; | |
2094 | uint32_t essential_ : 1; | |
2095 | uint32_t obsolete_ : 1; | |
2096 | uint32_t ignored_ : 1; | |
2097 | uint32_t pooled_ : 1; | |
2098 | ||
2099 | CYPool *pool_; | |
2100 | ||
2101 | uint32_t rank_; | |
2102 | ||
2103 | _transient Database *database_; | |
2104 | ||
2105 | pkgCache::VerIterator version_; | |
2106 | pkgCache::PkgIterator iterator_; | |
2107 | pkgCache::VerFileIterator file_; | |
2108 | ||
2109 | CYString id_; | |
2110 | CYString name_; | |
2111 | CYString transform_; | |
2112 | ||
2113 | CYString latest_; | |
2114 | CYString installed_; | |
2115 | time_t upgraded_; | |
2116 | ||
2117 | const char *section_; | |
2118 | _transient NSString *section$_; | |
2119 | ||
2120 | _H<Source> source_; | |
2121 | ||
2122 | PackageValue *metadata_; | |
2123 | ParsedPackage *parsed_; | |
2124 | ||
2125 | _H<NSMutableArray> tags_; | |
2126 | } | |
2127 | ||
2128 | - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database; | |
2129 | + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database; | |
2130 | ||
2131 | - (pkgCache::PkgIterator) iterator; | |
2132 | - (void) parse; | |
2133 | ||
2134 | - (NSString *) section; | |
2135 | - (NSString *) simpleSection; | |
2136 | ||
2137 | - (NSString *) longSection; | |
2138 | - (NSString *) shortSection; | |
2139 | ||
2140 | - (NSString *) uri; | |
2141 | ||
2142 | - (MIMEAddress *) maintainer; | |
2143 | - (size_t) size; | |
2144 | - (NSString *) longDescription; | |
2145 | - (NSString *) shortDescription; | |
2146 | - (unichar) index; | |
2147 | ||
2148 | - (PackageValue *) metadata; | |
2149 | - (time_t) seen; | |
2150 | ||
2151 | - (bool) subscribed; | |
2152 | - (bool) setSubscribed:(bool)subscribed; | |
2153 | ||
2154 | - (BOOL) ignored; | |
2155 | ||
2156 | - (NSString *) latest; | |
2157 | - (NSString *) installed; | |
2158 | - (BOOL) uninstalled; | |
2159 | ||
2160 | - (BOOL) valid; | |
2161 | - (BOOL) upgradableAndEssential:(BOOL)essential; | |
2162 | - (BOOL) essential; | |
2163 | - (BOOL) broken; | |
2164 | - (BOOL) unfiltered; | |
2165 | - (BOOL) visible; | |
2166 | ||
2167 | - (BOOL) half; | |
2168 | - (BOOL) halfConfigured; | |
2169 | - (BOOL) halfInstalled; | |
2170 | - (BOOL) hasMode; | |
2171 | - (NSString *) mode; | |
2172 | ||
2173 | - (NSString *) id; | |
2174 | - (NSString *) name; | |
2175 | - (UIImage *) icon; | |
2176 | - (NSString *) homepage; | |
2177 | - (NSString *) depiction; | |
2178 | - (MIMEAddress *) author; | |
2179 | ||
2180 | - (NSString *) support; | |
2181 | ||
2182 | - (NSArray *) files; | |
2183 | - (NSArray *) warnings; | |
2184 | - (NSArray *) applications; | |
2185 | ||
2186 | - (Source *) source; | |
2187 | ||
2188 | - (uint32_t) rank; | |
2189 | - (BOOL) matches:(NSArray *)query; | |
2190 | ||
2191 | - (BOOL) hasTag:(NSString *)tag; | |
2192 | - (NSString *) primaryPurpose; | |
2193 | - (NSArray *) purposes; | |
2194 | - (bool) isCommercial; | |
2195 | ||
2196 | - (void) setIndex:(size_t)index; | |
2197 | ||
2198 | - (CYString &) cyname; | |
2199 | ||
2200 | - (uint32_t) compareBySection:(NSArray *)sections; | |
2201 | ||
2202 | - (void) install; | |
2203 | - (void) remove; | |
2204 | ||
2205 | @end | |
2206 | ||
2207 | uint32_t PackageChangesRadix(Package *self, void *) { | |
2208 | union { | |
2209 | uint32_t key; | |
2210 | ||
2211 | struct { | |
2212 | uint32_t timestamp : 30; | |
2213 | uint32_t ignored : 1; | |
2214 | uint32_t upgradable : 1; | |
2215 | } bits; | |
2216 | } value; | |
2217 | ||
2218 | bool upgradable([self upgradableAndEssential:YES]); | |
2219 | value.bits.upgradable = upgradable ? 1 : 0; | |
2220 | ||
2221 | if (upgradable) { | |
2222 | value.bits.timestamp = 0; | |
2223 | value.bits.ignored = [self ignored] ? 0 : 1; | |
2224 | value.bits.upgradable = 1; | |
2225 | } else { | |
2226 | value.bits.timestamp = [self seen] >> 2; | |
2227 | value.bits.ignored = 0; | |
2228 | value.bits.upgradable = 0; | |
2229 | } | |
2230 | ||
2231 | return _not(uint32_t) - value.key; | |
2232 | } | |
2233 | ||
2234 | CYString &(*PackageName)(Package *self, SEL sel); | |
2235 | ||
2236 | uint32_t PackagePrefixRadix(Package *self, void *context) { | |
2237 | size_t offset(reinterpret_cast<size_t>(context)); | |
2238 | CYString &name(PackageName(self, @selector(cyname))); | |
2239 | ||
2240 | size_t size(name.size()); | |
2241 | if (size == 0) | |
2242 | return 0; | |
2243 | char *text(name.data()); | |
2244 | ||
2245 | size_t zeros; | |
2246 | if (!isdigit(text[0])) | |
2247 | zeros = 0; | |
2248 | else { | |
2249 | size_t digits(1); | |
2250 | while (size != digits && isdigit(text[digits])) | |
2251 | if (++digits == 4) | |
2252 | break; | |
2253 | zeros = 4 - digits; | |
2254 | } | |
2255 | ||
2256 | uint8_t data[4]; | |
2257 | ||
2258 | if (offset == 0 && zeros != 0) { | |
2259 | memset(data, '0', zeros); | |
2260 | memcpy(data + zeros, text, 4 - zeros); | |
2261 | } else { | |
2262 | /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */ | |
2263 | if (size <= offset - zeros) | |
2264 | return 0; | |
2265 | ||
2266 | text += offset - zeros; | |
2267 | size -= offset - zeros; | |
2268 | ||
2269 | if (size >= 4) | |
2270 | memcpy(data, text, 4); | |
2271 | else { | |
2272 | memcpy(data, text, size); | |
2273 | memset(data + size, 0, 4 - size); | |
2274 | } | |
2275 | ||
2276 | for (size_t i(0); i != 4; ++i) | |
2277 | if (isalpha(data[i])) | |
2278 | data[i] |= 0x20; | |
2279 | } | |
2280 | ||
2281 | if (offset == 0) | |
2282 | if (data[0] == '@') | |
2283 | data[0] = 0x7f; | |
2284 | else | |
2285 | data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6]; | |
2286 | ||
2287 | /* XXX: ntohl may be more honest */ | |
2288 | return OSSwapInt32(*reinterpret_cast<uint32_t *>(data)); | |
2289 | } | |
2290 | ||
2291 | CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) { | |
2292 | _profile(PackageNameCompare) | |
2293 | if (lhn == NULL) | |
2294 | return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan; | |
2295 | else if (rhn == NULL) | |
2296 | return kCFCompareGreaterThan; | |
2297 | ||
2298 | CFIndex length(CFStringGetLength(lhn)); | |
2299 | ||
2300 | _profile(PackageNameCompare$NumbersLast) | |
2301 | if (length != 0 && CFStringGetLength(rhn) != 0) { | |
2302 | UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0)); | |
2303 | UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0)); | |
2304 | bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet)); | |
2305 | if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet)) | |
2306 | return lha ? kCFCompareLessThan : kCFCompareGreaterThan; | |
2307 | } | |
2308 | _end | |
2309 | ||
2310 | _profile(PackageNameCompare$Compare) | |
2311 | return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_); | |
2312 | _end | |
2313 | _end | |
2314 | } | |
2315 | ||
2316 | _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) { | |
2317 | return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length); | |
2318 | } | |
2319 | ||
2320 | CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) { | |
2321 | CYString &lhn(PackageName(lhs, @selector(cyname))); | |
2322 | NSString *rhn(PackageName(rhs, @selector(cyname))); | |
2323 | return StringNameCompare(lhn, rhn, lhn.size()); | |
2324 | } | |
2325 | ||
2326 | CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) { | |
2327 | return PackageNameCompare(*lhs, *rhs, arg); | |
2328 | } | |
2329 | ||
2330 | struct PackageNameOrdering : | |
2331 | std::binary_function<Package *, Package *, bool> | |
2332 | { | |
2333 | _finline bool operator ()(Package *lhs, Package *rhs) const { | |
2334 | return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan; | |
2335 | } | |
2336 | }; | |
2337 | ||
2338 | @implementation Package | |
2339 | ||
2340 | - (NSString *) description { | |
2341 | return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)]; | |
2342 | } | |
2343 | ||
2344 | - (void) dealloc { | |
2345 | if (!pooled_) | |
2346 | delete pool_; | |
2347 | if (parsed_ != NULL) | |
2348 | delete parsed_; | |
2349 | [super dealloc]; | |
2350 | } | |
2351 | ||
2352 | + (NSString *) webScriptNameForSelector:(SEL)selector { | |
2353 | if (false); | |
2354 | else if (selector == @selector(clear)) | |
2355 | return @"clear"; | |
2356 | else if (selector == @selector(getField:)) | |
2357 | return @"getField"; | |
2358 | else if (selector == @selector(getRecord)) | |
2359 | return @"getRecord"; | |
2360 | else if (selector == @selector(hasTag:)) | |
2361 | return @"hasTag"; | |
2362 | else if (selector == @selector(install)) | |
2363 | return @"install"; | |
2364 | else if (selector == @selector(remove)) | |
2365 | return @"remove"; | |
2366 | else | |
2367 | return nil; | |
2368 | } | |
2369 | ||
2370 | + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector { | |
2371 | return [self webScriptNameForSelector:selector] == nil; | |
2372 | } | |
2373 | ||
2374 | + (NSArray *) _attributeKeys { | |
2375 | return [NSArray arrayWithObjects: | |
2376 | @"applications", | |
2377 | @"architecture", | |
2378 | @"author", | |
2379 | @"depiction", | |
2380 | @"essential", | |
2381 | @"homepage", | |
2382 | @"icon", | |
2383 | @"id", | |
2384 | @"installed", | |
2385 | @"latest", | |
2386 | @"longDescription", | |
2387 | @"longSection", | |
2388 | @"maintainer", | |
2389 | @"md5sum", | |
2390 | @"mode", | |
2391 | @"name", | |
2392 | @"purposes", | |
2393 | @"relations", | |
2394 | @"section", | |
2395 | @"selection", | |
2396 | @"shortDescription", | |
2397 | @"shortSection", | |
2398 | @"simpleSection", | |
2399 | @"size", | |
2400 | @"source", | |
2401 | @"state", | |
2402 | @"support", | |
2403 | @"tags", | |
2404 | @"upgraded", | |
2405 | @"warnings", | |
2406 | nil]; | |
2407 | } | |
2408 | ||
2409 | - (NSArray *) attributeKeys { | |
2410 | return [[self class] _attributeKeys]; | |
2411 | } | |
2412 | ||
2413 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
2414 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
2415 | } | |
2416 | ||
2417 | - (NSArray *) relations { | |
2418 | @synchronized (database_) { | |
2419 | NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]); | |
2420 | for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep) | |
2421 | [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]]; | |
2422 | return relations; | |
2423 | } } | |
2424 | ||
2425 | - (NSString *) architecture { | |
2426 | [self parse]; | |
2427 | @synchronized (database_) { | |
2428 | return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_; | |
2429 | } } | |
2430 | ||
2431 | - (NSString *) getField:(NSString *)name { | |
2432 | @synchronized (database_) { | |
2433 | if ([database_ era] != era_ || file_.end()) | |
2434 | return nil; | |
2435 | ||
2436 | pkgRecords::Parser &parser([database_ records]->Lookup(file_)); | |
2437 | ||
2438 | const char *start, *end; | |
2439 | if (!parser.Find([name UTF8String], start, end)) | |
2440 | return (NSString *) [NSNull null]; | |
2441 | ||
2442 | return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]]; | |
2443 | } } | |
2444 | ||
2445 | - (NSString *) getRecord { | |
2446 | @synchronized (database_) { | |
2447 | if ([database_ era] != era_ || file_.end()) | |
2448 | return nil; | |
2449 | ||
2450 | pkgRecords::Parser &parser([database_ records]->Lookup(file_)); | |
2451 | ||
2452 | const char *start, *end; | |
2453 | parser.GetRec(start, end); | |
2454 | ||
2455 | return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]]; | |
2456 | } } | |
2457 | ||
2458 | - (void) parse { | |
2459 | if (parsed_ != NULL) | |
2460 | return; | |
2461 | @synchronized (database_) { | |
2462 | if ([database_ era] != era_ || file_.end()) | |
2463 | return; | |
2464 | ||
2465 | ParsedPackage *parsed(new ParsedPackage); | |
2466 | parsed_ = parsed; | |
2467 | ||
2468 | _profile(Package$parse) | |
2469 | pkgRecords::Parser *parser; | |
2470 | ||
2471 | _profile(Package$parse$Lookup) | |
2472 | parser = &[database_ records]->Lookup(file_); | |
2473 | _end | |
2474 | ||
2475 | CYString bugs; | |
2476 | CYString website; | |
2477 | ||
2478 | _profile(Package$parse$Find) | |
2479 | struct { | |
2480 | const char *name_; | |
2481 | CYString *value_; | |
2482 | } names[] = { | |
2483 | {"architecture", &parsed->architecture_}, | |
2484 | {"icon", &parsed->icon_}, | |
2485 | {"depiction", &parsed->depiction_}, | |
2486 | {"homepage", &parsed->homepage_}, | |
2487 | {"website", &website}, | |
2488 | {"bugs", &bugs}, | |
2489 | {"support", &parsed->support_}, | |
2490 | {"author", &parsed->author_}, | |
2491 | {"md5sum", &parsed->md5sum_}, | |
2492 | }; | |
2493 | ||
2494 | for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) { | |
2495 | const char *start, *end; | |
2496 | ||
2497 | if (parser->Find(names[i].name_, start, end)) { | |
2498 | CYString &value(*names[i].value_); | |
2499 | _profile(Package$parse$Value) | |
2500 | value.set(pool_, start, end - start); | |
2501 | _end | |
2502 | } | |
2503 | } | |
2504 | _end | |
2505 | ||
2506 | _profile(Package$parse$Tagline) | |
2507 | const char *start, *end; | |
2508 | if (parser->ShortDesc(start, end)) { | |
2509 | const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start))); | |
2510 | if (stop == NULL) | |
2511 | stop = end; | |
2512 | while (stop != start && stop[-1] == '\r') | |
2513 | --stop; | |
2514 | parsed->tagline_.set(pool_, start, stop - start); | |
2515 | } | |
2516 | _end | |
2517 | ||
2518 | _profile(Package$parse$Retain) | |
2519 | if (parsed->homepage_.empty()) | |
2520 | parsed->homepage_ = website; | |
2521 | if (parsed->homepage_ == parsed->depiction_) | |
2522 | parsed->homepage_.clear(); | |
2523 | if (parsed->support_.empty()) | |
2524 | parsed->support_ = bugs; | |
2525 | _end | |
2526 | _end | |
2527 | } } | |
2528 | ||
2529 | - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database { | |
2530 | if ((self = [super init]) != nil) { | |
2531 | _profile(Package$initWithVersion) | |
2532 | if (pool == NULL) | |
2533 | pool_ = new CYPool(); | |
2534 | else { | |
2535 | pool_ = pool; | |
2536 | pooled_ = true; | |
2537 | } | |
2538 | ||
2539 | database_ = database; | |
2540 | era_ = [database era]; | |
2541 | ||
2542 | version_ = version; | |
2543 | ||
2544 | pkgCache::PkgIterator iterator(version.ParentPkg()); | |
2545 | iterator_ = iterator; | |
2546 | ||
2547 | _profile(Package$initWithVersion$Version) | |
2548 | if (!version_.end()) | |
2549 | file_ = version_.FileList(); | |
2550 | else { | |
2551 | pkgCache &cache([database_ cache]); | |
2552 | file_ = pkgCache::VerFileIterator(cache, cache.VerFileP); | |
2553 | } | |
2554 | _end | |
2555 | ||
2556 | _profile(Package$initWithVersion$Cache) | |
2557 | name_.set(NULL, iterator.Display()); | |
2558 | ||
2559 | latest_.set(NULL, StripVersion_(version_.VerStr())); | |
2560 | ||
2561 | pkgCache::VerIterator current(iterator.CurrentVer()); | |
2562 | if (!current.end()) | |
2563 | installed_.set(NULL, StripVersion_(current.VerStr())); | |
2564 | _end | |
2565 | ||
2566 | _profile(Package$initWithVersion$Transliterate) do { | |
2567 | if (CollationTransl_ == NULL) | |
2568 | break; | |
2569 | if (name_.empty()) | |
2570 | break; | |
2571 | ||
2572 | _profile(Package$initWithVersion$Transliterate$utf8) | |
2573 | const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data())); | |
2574 | for (size_t i(0), e(name_.size()); i != e; ++i) | |
2575 | if (data[i] >= 0x80) | |
2576 | goto extended; | |
2577 | break; extended:; | |
2578 | _end | |
2579 | ||
2580 | UErrorCode code(U_ZERO_ERROR); | |
2581 | int32_t length; | |
2582 | ||
2583 | _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub) | |
2584 | CollationString_.resize(name_.size()); | |
2585 | u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code); | |
2586 | if (!U_SUCCESS(code)) | |
2587 | break; | |
2588 | CollationString_.resize(length); | |
2589 | _end | |
2590 | ||
2591 | _profile(Package$initWithVersion$Transliterate$utrans_trans) | |
2592 | length = CollationString_.size(); | |
2593 | utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code); | |
2594 | if (!U_SUCCESS(code)) | |
2595 | break; | |
2596 | _assert(CollationString_.size() == length); | |
2597 | _end | |
2598 | ||
2599 | _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight) | |
2600 | u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code); | |
2601 | if (code == U_BUFFER_OVERFLOW_ERROR) | |
2602 | code = U_ZERO_ERROR; | |
2603 | else if (!U_SUCCESS(code)) | |
2604 | break; | |
2605 | _end | |
2606 | ||
2607 | char *transform; | |
2608 | _profile(Package$initWithVersion$Transliterate$apr_palloc) | |
2609 | transform = pool_->malloc<char>(length); | |
2610 | _end | |
2611 | _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform) | |
2612 | u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code); | |
2613 | if (!U_SUCCESS(code)) | |
2614 | break; | |
2615 | _end | |
2616 | ||
2617 | transform_.set(NULL, transform, length); | |
2618 | } while (false); _end | |
2619 | ||
2620 | _profile(Package$initWithVersion$Tags) | |
2621 | pkgCache::TagIterator tag(iterator.TagList()); | |
2622 | if (!tag.end()) { | |
2623 | tags_ = [NSMutableArray arrayWithCapacity:8]; | |
2624 | ||
2625 | goto tag; for (; !tag.end(); ++tag) tag: { | |
2626 | const char *name(tag.Name()); | |
2627 | NSString *string((NSString *) CYStringCreate(name)); | |
2628 | if (string == nil) | |
2629 | continue; | |
2630 | ||
2631 | [tags_ addObject:[string autorelease]]; | |
2632 | ||
2633 | if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) { | |
2634 | if (strcmp(name + 6, "enduser") == 0) | |
2635 | role_ = 1; | |
2636 | else if (strcmp(name + 6, "hacker") == 0) | |
2637 | role_ = 2; | |
2638 | else if (strcmp(name + 6, "developer") == 0) | |
2639 | role_ = 3; | |
2640 | else if (strcmp(name + 6, "cydia") == 0) | |
2641 | role_ = 7; | |
2642 | else | |
2643 | role_ = 4; | |
2644 | } | |
2645 | ||
2646 | if (strncmp(name, "cydia::", 7) == 0) { | |
2647 | if (strcmp(name + 7, "essential") == 0) | |
2648 | essential_ = true; | |
2649 | else if (strcmp(name + 7, "obsolete") == 0) | |
2650 | obsolete_ = true; | |
2651 | } | |
2652 | } | |
2653 | } | |
2654 | _end | |
2655 | ||
2656 | _profile(Package$initWithVersion$Metadata) | |
2657 | const char *mixed(iterator.Name()); | |
2658 | size_t size(strlen(mixed)); | |
2659 | static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1); | |
2660 | char lower[prefix + size + 5 + 1]; | |
2661 | ||
2662 | for (size_t i(0); i != size; ++i) | |
2663 | lower[prefix + i] = mixed[i] | 0x20; | |
2664 | ||
2665 | if (!installed_.empty()) { | |
2666 | memcpy(lower, "/var/lib/dpkg/info/", prefix); | |
2667 | memcpy(lower + prefix + size, ".list", 6); | |
2668 | struct stat info; | |
2669 | if (stat(lower, &info) != -1) | |
2670 | upgraded_ = info.st_birthtime; | |
2671 | } | |
2672 | ||
2673 | PackageValue *metadata(PackageFind(lower + prefix, size)); | |
2674 | metadata_ = metadata; | |
2675 | ||
2676 | id_.set(NULL, metadata->name_, size); | |
2677 | ||
2678 | const char *latest(version_.VerStr()); | |
2679 | size_t length(strlen(latest)); | |
2680 | ||
2681 | uint16_t vhash(hashlittle(latest, length)); | |
2682 | ||
2683 | size_t capped(std::min<size_t>(8, length)); | |
2684 | latest = latest + length - capped; | |
2685 | ||
2686 | if (metadata->first_ == 0) | |
2687 | metadata->first_ = now_; | |
2688 | ||
2689 | if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) { | |
2690 | strncpy(metadata->version_, latest, sizeof(metadata->version_)); | |
2691 | metadata->vhash_ = vhash; | |
2692 | metadata->last_ = now_; | |
2693 | } else if (metadata->last_ == 0) | |
2694 | metadata->last_ = metadata->first_; | |
2695 | _end | |
2696 | ||
2697 | _profile(Package$initWithVersion$Section) | |
2698 | section_ = version_.Section(); | |
2699 | _end | |
2700 | ||
2701 | _profile(Package$initWithVersion$Flags) | |
2702 | essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES); | |
2703 | ignored_ = iterator->SelectedState == pkgCache::State::Hold; | |
2704 | _end | |
2705 | _end } return self; | |
2706 | } | |
2707 | ||
2708 | + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database { | |
2709 | pkgCache::VerIterator version; | |
2710 | ||
2711 | _profile(Package$packageWithIterator$GetCandidateVer) | |
2712 | version = [database policy]->GetCandidateVer(iterator); | |
2713 | _end | |
2714 | ||
2715 | if (version.end()) | |
2716 | return nil; | |
2717 | ||
2718 | Package *package; | |
2719 | ||
2720 | _profile(Package$packageWithIterator$Allocate) | |
2721 | package = [Package allocWithZone:zone]; | |
2722 | _end | |
2723 | ||
2724 | _profile(Package$packageWithIterator$Initialize) | |
2725 | package = [package | |
2726 | initWithVersion:version | |
2727 | withZone:zone | |
2728 | inPool:pool | |
2729 | database:database | |
2730 | ]; | |
2731 | _end | |
2732 | ||
2733 | _profile(Package$packageWithIterator$Autorelease) | |
2734 | package = [package autorelease]; | |
2735 | _end | |
2736 | ||
2737 | return package; | |
2738 | } | |
2739 | ||
2740 | - (pkgCache::PkgIterator) iterator { | |
2741 | return iterator_; | |
2742 | } | |
2743 | ||
2744 | - (NSString *) section { | |
2745 | if (section$_ == nil) { | |
2746 | if (section_ == NULL) | |
2747 | return nil; | |
2748 | ||
2749 | _profile(Package$section$mappedSectionForPointer) | |
2750 | section$_ = [database_ mappedSectionForPointer:section_]; | |
2751 | _end | |
2752 | } return section$_; | |
2753 | } | |
2754 | ||
2755 | - (NSString *) simpleSection { | |
2756 | if (NSString *section = [self section]) | |
2757 | return Simplify(section); | |
2758 | else | |
2759 | return nil; | |
2760 | } | |
2761 | ||
2762 | - (NSString *) longSection { | |
2763 | return LocalizeSection([self section]); | |
2764 | } | |
2765 | ||
2766 | - (NSString *) shortSection { | |
2767 | return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"]; | |
2768 | } | |
2769 | ||
2770 | - (NSString *) uri { | |
2771 | return nil; | |
2772 | #if 0 | |
2773 | pkgIndexFile *index; | |
2774 | pkgCache::PkgFileIterator file(file_.File()); | |
2775 | if (![database_ list].FindIndex(file, index)) | |
2776 | return nil; | |
2777 | return [NSString stringWithUTF8String:iterator_->Path]; | |
2778 | //return [NSString stringWithUTF8String:file.Site()]; | |
2779 | //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()]; | |
2780 | #endif | |
2781 | } | |
2782 | ||
2783 | - (MIMEAddress *) maintainer { | |
2784 | @synchronized (database_) { | |
2785 | if ([database_ era] != era_ || file_.end()) | |
2786 | return nil; | |
2787 | ||
2788 | pkgRecords::Parser *parser = &[database_ records]->Lookup(file_); | |
2789 | const std::string &maintainer(parser->Maintainer()); | |
2790 | return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]]; | |
2791 | } } | |
2792 | ||
2793 | - (NSString *) md5sum { | |
2794 | return parsed_ == NULL ? nil : (id) parsed_->md5sum_; | |
2795 | } | |
2796 | ||
2797 | - (size_t) size { | |
2798 | @synchronized (database_) { | |
2799 | if ([database_ era] != era_ || version_.end()) | |
2800 | return 0; | |
2801 | ||
2802 | return version_->InstalledSize; | |
2803 | } } | |
2804 | ||
2805 | - (NSString *) longDescription { | |
2806 | @synchronized (database_) { | |
2807 | if ([database_ era] != era_ || file_.end()) | |
2808 | return nil; | |
2809 | ||
2810 | pkgRecords::Parser *parser = &[database_ records]->Lookup(file_); | |
2811 | NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]); | |
2812 | ||
2813 | NSArray *lines = [description componentsSeparatedByString:@"\n"]; | |
2814 | NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)]; | |
2815 | if ([lines count] < 2) | |
2816 | return nil; | |
2817 | ||
2818 | NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet]; | |
2819 | for (size_t i(1), e([lines count]); i != e; ++i) { | |
2820 | NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace]; | |
2821 | [trimmed addObject:trim]; | |
2822 | } | |
2823 | ||
2824 | return [trimmed componentsJoinedByString:@"\n"]; | |
2825 | } } | |
2826 | ||
2827 | - (NSString *) shortDescription { | |
2828 | if (parsed_ != NULL) | |
2829 | return static_cast<NSString *>(parsed_->tagline_); | |
2830 | ||
2831 | @synchronized (database_) { | |
2832 | pkgRecords::Parser &parser([database_ records]->Lookup(file_)); | |
2833 | ||
2834 | const char *start, *end; | |
2835 | if (!parser.ShortDesc(start, end)) | |
2836 | return nil; | |
2837 | ||
2838 | if (end - start > 200) | |
2839 | end = start + 200; | |
2840 | ||
2841 | /* | |
2842 | if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start))) | |
2843 | end = stop; | |
2844 | ||
2845 | while (end != start && end[-1] == '\r') | |
2846 | --end; | |
2847 | */ | |
2848 | ||
2849 | return [(id) CYStringCreate(start, end - start) autorelease]; | |
2850 | } } | |
2851 | ||
2852 | - (unichar) index { | |
2853 | _profile(Package$index) | |
2854 | CFStringRef name((CFStringRef) [self name]); | |
2855 | if (CFStringGetLength(name) == 0) | |
2856 | return '#'; | |
2857 | UniChar character(CFStringGetCharacterAtIndex(name, 0)); | |
2858 | if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet)) | |
2859 | return '#'; | |
2860 | return toupper(character); | |
2861 | _end | |
2862 | } | |
2863 | ||
2864 | - (PackageValue *) metadata { | |
2865 | return metadata_; | |
2866 | } | |
2867 | ||
2868 | - (time_t) seen { | |
2869 | PackageValue *metadata([self metadata]); | |
2870 | return metadata->subscribed_ ? metadata->last_ : metadata->first_; | |
2871 | } | |
2872 | ||
2873 | - (bool) subscribed { | |
2874 | return [self metadata]->subscribed_; | |
2875 | } | |
2876 | ||
2877 | - (bool) setSubscribed:(bool)subscribed { | |
2878 | PackageValue *metadata([self metadata]); | |
2879 | if (metadata->subscribed_ == subscribed) | |
2880 | return false; | |
2881 | metadata->subscribed_ = subscribed; | |
2882 | return true; | |
2883 | } | |
2884 | ||
2885 | - (BOOL) ignored { | |
2886 | return ignored_; | |
2887 | } | |
2888 | ||
2889 | - (NSString *) latest { | |
2890 | return latest_; | |
2891 | } | |
2892 | ||
2893 | - (NSString *) installed { | |
2894 | return installed_; | |
2895 | } | |
2896 | ||
2897 | - (BOOL) uninstalled { | |
2898 | return installed_.empty(); | |
2899 | } | |
2900 | ||
2901 | - (BOOL) valid { | |
2902 | return !version_.end(); | |
2903 | } | |
2904 | ||
2905 | - (BOOL) upgradableAndEssential:(BOOL)essential { | |
2906 | _profile(Package$upgradableAndEssential) | |
2907 | pkgCache::VerIterator current(iterator_.CurrentVer()); | |
2908 | if (current.end()) | |
2909 | return essential && essential_; | |
2910 | else | |
2911 | return !version_.end() && version_ != current; | |
2912 | _end | |
2913 | } | |
2914 | ||
2915 | - (BOOL) essential { | |
2916 | return essential_; | |
2917 | } | |
2918 | ||
2919 | - (BOOL) broken { | |
2920 | return [database_ cache][iterator_].InstBroken(); | |
2921 | } | |
2922 | ||
2923 | - (BOOL) unfiltered { | |
2924 | _profile(Package$unfiltered$obsolete) | |
2925 | if (_unlikely(obsolete_)) | |
2926 | return false; | |
2927 | _end | |
2928 | ||
2929 | _profile(Package$unfiltered$role) | |
2930 | if (_unlikely(role_ > 3)) | |
2931 | return false; | |
2932 | _end | |
2933 | ||
2934 | return true; | |
2935 | } | |
2936 | ||
2937 | - (BOOL) visible { | |
2938 | if (![self unfiltered]) | |
2939 | return false; | |
2940 | ||
2941 | NSString *section; | |
2942 | ||
2943 | _profile(Package$visible$section) | |
2944 | section = [self section]; | |
2945 | _end | |
2946 | ||
2947 | _profile(Package$visible$isSectionVisible) | |
2948 | if (!isSectionVisible(section)) | |
2949 | return false; | |
2950 | _end | |
2951 | ||
2952 | return true; | |
2953 | } | |
2954 | ||
2955 | - (BOOL) half { | |
2956 | unsigned char current(iterator_->CurrentState); | |
2957 | return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled; | |
2958 | } | |
2959 | ||
2960 | - (BOOL) halfConfigured { | |
2961 | return iterator_->CurrentState == pkgCache::State::HalfConfigured; | |
2962 | } | |
2963 | ||
2964 | - (BOOL) halfInstalled { | |
2965 | return iterator_->CurrentState == pkgCache::State::HalfInstalled; | |
2966 | } | |
2967 | ||
2968 | - (BOOL) hasMode { | |
2969 | @synchronized (database_) { | |
2970 | if ([database_ era] != era_ || iterator_.end()) | |
2971 | return NO; | |
2972 | ||
2973 | pkgDepCache::StateCache &state([database_ cache][iterator_]); | |
2974 | return state.Mode != pkgDepCache::ModeKeep; | |
2975 | } } | |
2976 | ||
2977 | - (NSString *) mode { | |
2978 | @synchronized (database_) { | |
2979 | if ([database_ era] != era_ || iterator_.end()) | |
2980 | return nil; | |
2981 | ||
2982 | pkgDepCache::StateCache &state([database_ cache][iterator_]); | |
2983 | ||
2984 | switch (state.Mode) { | |
2985 | case pkgDepCache::ModeDelete: | |
2986 | if ((state.iFlags & pkgDepCache::Purge) != 0) | |
2987 | return @"PURGE"; | |
2988 | else | |
2989 | return @"REMOVE"; | |
2990 | case pkgDepCache::ModeKeep: | |
2991 | if ((state.iFlags & pkgDepCache::ReInstall) != 0) | |
2992 | return @"REINSTALL"; | |
2993 | /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0) | |
2994 | return nil;*/ | |
2995 | else | |
2996 | return nil; | |
2997 | case pkgDepCache::ModeInstall: | |
2998 | /*if ((state.iFlags & pkgDepCache::ReInstall) != 0) | |
2999 | return @"REINSTALL"; | |
3000 | else*/ switch (state.Status) { | |
3001 | case -1: | |
3002 | return @"DOWNGRADE"; | |
3003 | case 0: | |
3004 | return @"INSTALL"; | |
3005 | case 1: | |
3006 | return @"UPGRADE"; | |
3007 | case 2: | |
3008 | return @"NEW_INSTALL"; | |
3009 | _nodefault | |
3010 | } | |
3011 | _nodefault | |
3012 | } | |
3013 | } } | |
3014 | ||
3015 | - (NSString *) id { | |
3016 | return id_; | |
3017 | } | |
3018 | ||
3019 | - (NSString *) name { | |
3020 | return name_.empty() ? id_ : name_; | |
3021 | } | |
3022 | ||
3023 | - (UIImage *) icon { | |
3024 | NSString *section = [self simpleSection]; | |
3025 | ||
3026 | UIImage *icon(nil); | |
3027 | if (parsed_ != NULL) | |
3028 | if (NSString *href = parsed_->icon_) | |
3029 | if ([href hasPrefix:@"file:///"]) | |
3030 | icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; | |
3031 | if (icon == nil) if (section != nil) | |
3032 | icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]; | |
3033 | if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon]) | |
3034 | if ([dicon hasPrefix:@"file:///"]) | |
3035 | icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; | |
3036 | if (icon == nil) | |
3037 | icon = [UIImage imageNamed:@"unknown.png"]; | |
3038 | return icon; | |
3039 | } | |
3040 | ||
3041 | - (NSString *) homepage { | |
3042 | return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_); | |
3043 | } | |
3044 | ||
3045 | - (NSString *) depiction { | |
3046 | return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_]; | |
3047 | } | |
3048 | ||
3049 | - (MIMEAddress *) author { | |
3050 | return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_]; | |
3051 | } | |
3052 | ||
3053 | - (NSString *) support { | |
3054 | return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_]; | |
3055 | } | |
3056 | ||
3057 | - (NSArray *) files { | |
3058 | NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)]; | |
3059 | NSMutableArray *files = [NSMutableArray arrayWithCapacity:128]; | |
3060 | ||
3061 | std::ifstream fin; | |
3062 | fin.open([path UTF8String]); | |
3063 | if (!fin.is_open()) | |
3064 | return nil; | |
3065 | ||
3066 | std::string line; | |
3067 | while (std::getline(fin, line)) | |
3068 | [files addObject:[NSString stringWithUTF8String:line.c_str()]]; | |
3069 | ||
3070 | return files; | |
3071 | } | |
3072 | ||
3073 | - (NSString *) state { | |
3074 | @synchronized (database_) { | |
3075 | if ([database_ era] != era_ || file_.end()) | |
3076 | return nil; | |
3077 | ||
3078 | switch (iterator_->CurrentState) { | |
3079 | case pkgCache::State::NotInstalled: | |
3080 | return @"NotInstalled"; | |
3081 | case pkgCache::State::UnPacked: | |
3082 | return @"UnPacked"; | |
3083 | case pkgCache::State::HalfConfigured: | |
3084 | return @"HalfConfigured"; | |
3085 | case pkgCache::State::HalfInstalled: | |
3086 | return @"HalfInstalled"; | |
3087 | case pkgCache::State::ConfigFiles: | |
3088 | return @"ConfigFiles"; | |
3089 | case pkgCache::State::Installed: | |
3090 | return @"Installed"; | |
3091 | case pkgCache::State::TriggersAwaited: | |
3092 | return @"TriggersAwaited"; | |
3093 | case pkgCache::State::TriggersPending: | |
3094 | return @"TriggersPending"; | |
3095 | } | |
3096 | ||
3097 | return (NSString *) [NSNull null]; | |
3098 | } } | |
3099 | ||
3100 | - (NSString *) selection { | |
3101 | @synchronized (database_) { | |
3102 | if ([database_ era] != era_ || file_.end()) | |
3103 | return nil; | |
3104 | ||
3105 | switch (iterator_->SelectedState) { | |
3106 | case pkgCache::State::Unknown: | |
3107 | return @"Unknown"; | |
3108 | case pkgCache::State::Install: | |
3109 | return @"Install"; | |
3110 | case pkgCache::State::Hold: | |
3111 | return @"Hold"; | |
3112 | case pkgCache::State::DeInstall: | |
3113 | return @"DeInstall"; | |
3114 | case pkgCache::State::Purge: | |
3115 | return @"Purge"; | |
3116 | } | |
3117 | ||
3118 | return (NSString *) [NSNull null]; | |
3119 | } } | |
3120 | ||
3121 | - (NSArray *) warnings { | |
3122 | @synchronized (database_) { | |
3123 | if ([database_ era] != era_ || file_.end()) | |
3124 | return nil; | |
3125 | ||
3126 | NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]); | |
3127 | const char *name(iterator_.Name()); | |
3128 | ||
3129 | size_t length(strlen(name)); | |
3130 | if (length < 2) invalid: | |
3131 | [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")]; | |
3132 | else for (size_t i(0); i != length; ++i) | |
3133 | if ( | |
3134 | /* XXX: technically this is not allowed */ | |
3135 | (name[i] < 'A' || name[i] > 'Z') && | |
3136 | (name[i] < 'a' || name[i] > 'z') && | |
3137 | (name[i] < '0' || name[i] > '9') && | |
3138 | (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.') | |
3139 | ) goto invalid; | |
3140 | ||
3141 | if (strcmp(name, "cydia") != 0) { | |
3142 | bool cydia = false; | |
3143 | bool user = false; | |
3144 | bool _private = false; | |
3145 | bool stash = false; | |
3146 | bool dbstash = false; | |
3147 | bool dsstore = false; | |
3148 | ||
3149 | bool repository = [[self section] isEqualToString:@"Repositories"]; | |
3150 | ||
3151 | if (NSArray *files = [self files]) | |
3152 | for (NSString *file in files) | |
3153 | if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"]) | |
3154 | cydia = true; | |
3155 | else if (!user && [file isEqualToString:@"/User"]) | |
3156 | user = true; | |
3157 | else if (!_private && [file isEqualToString:@"/private"]) | |
3158 | _private = true; | |
3159 | else if (!stash && [file isEqualToString:@"/var/stash"]) | |
3160 | stash = true; | |
3161 | else if (!dbstash && [file isEqualToString:@"/var/db/stash"]) | |
3162 | dbstash = true; | |
3163 | else if (!dsstore && [file hasSuffix:@"/.DS_Store"]) | |
3164 | dsstore = true; | |
3165 | ||
3166 | /* XXX: this is not sensitive enough. only some folders are valid. */ | |
3167 | if (cydia && !repository) | |
3168 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]]; | |
3169 | if (user) | |
3170 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]]; | |
3171 | if (_private) | |
3172 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]]; | |
3173 | if (stash) | |
3174 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]]; | |
3175 | if (dbstash) | |
3176 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]]; | |
3177 | if (dsstore) | |
3178 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]]; | |
3179 | } | |
3180 | ||
3181 | return [warnings count] == 0 ? nil : warnings; | |
3182 | } } | |
3183 | ||
3184 | - (NSArray *) applications { | |
3185 | NSString *me([[NSBundle mainBundle] bundleIdentifier]); | |
3186 | ||
3187 | NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]); | |
3188 | ||
3189 | static RegEx application_r("/Applications/(.*)\\.app/Info.plist"); | |
3190 | if (NSArray *files = [self files]) | |
3191 | for (NSString *file in files) | |
3192 | if (application_r(file)) { | |
3193 | NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]); | |
3194 | if (info == nil) | |
3195 | continue; | |
3196 | NSString *id([info objectForKey:@"CFBundleIdentifier"]); | |
3197 | if (id == nil || [id isEqualToString:me]) | |
3198 | continue; | |
3199 | ||
3200 | NSString *display([info objectForKey:@"CFBundleDisplayName"]); | |
3201 | if (display == nil) | |
3202 | display = application_r[1]; | |
3203 | ||
3204 | NSString *bundle([file stringByDeletingLastPathComponent]); | |
3205 | NSString *icon([info objectForKey:@"CFBundleIconFile"]); | |
3206 | // XXX: maybe this should check if this is really a string, not just for length | |
3207 | if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0) | |
3208 | icon = @"icon.png"; | |
3209 | NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]); | |
3210 | ||
3211 | NSMutableArray *application([NSMutableArray arrayWithCapacity:2]); | |
3212 | [applications addObject:application]; | |
3213 | ||
3214 | [application addObject:id]; | |
3215 | [application addObject:display]; | |
3216 | [application addObject:url]; | |
3217 | } | |
3218 | ||
3219 | return [applications count] == 0 ? nil : applications; | |
3220 | } | |
3221 | ||
3222 | - (Source *) source { | |
3223 | if (source_ == nil) { | |
3224 | @synchronized (database_) { | |
3225 | if ([database_ era] != era_ || file_.end()) | |
3226 | source_ = (Source *) [NSNull null]; | |
3227 | else | |
3228 | source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null]; | |
3229 | } | |
3230 | } | |
3231 | ||
3232 | return source_ == (Source *) [NSNull null] ? nil : source_; | |
3233 | } | |
3234 | ||
3235 | - (time_t) upgraded { | |
3236 | return upgraded_; | |
3237 | } | |
3238 | ||
3239 | - (uint32_t) recent { | |
3240 | return std::numeric_limits<uint32_t>::max() - upgraded_; | |
3241 | } | |
3242 | ||
3243 | - (uint32_t) rank { | |
3244 | return rank_; | |
3245 | } | |
3246 | ||
3247 | - (BOOL) matches:(NSArray *)query { | |
3248 | if (query == nil || [query count] == 0) | |
3249 | return NO; | |
3250 | ||
3251 | rank_ = 0; | |
3252 | ||
3253 | NSString *string; | |
3254 | NSRange range; | |
3255 | NSUInteger length; | |
3256 | ||
3257 | string = [self name]; | |
3258 | length = [string length]; | |
3259 | ||
3260 | if (length != 0) | |
3261 | for (NSString *term in query) { | |
3262 | range = [string rangeOfString:term options:MatchCompareOptions_]; | |
3263 | if (range.location != NSNotFound) | |
3264 | rank_ -= 6 * 1000000 / length; | |
3265 | } | |
3266 | ||
3267 | if (rank_ == 0) { | |
3268 | string = [self id]; | |
3269 | length = [string length]; | |
3270 | ||
3271 | if (length != 0) | |
3272 | for (NSString *term in query) { | |
3273 | range = [string rangeOfString:term options:MatchCompareOptions_]; | |
3274 | if (range.location != NSNotFound) | |
3275 | rank_ -= 6 * 1000000 / length; | |
3276 | } | |
3277 | } | |
3278 | ||
3279 | string = [self shortDescription]; | |
3280 | length = [string length]; | |
3281 | NSUInteger stop(std::min<NSUInteger>(length, 200)); | |
3282 | ||
3283 | if (length != 0) | |
3284 | for (NSString *term in query) { | |
3285 | range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)]; | |
3286 | if (range.location != NSNotFound) | |
3287 | rank_ -= 2 * 100000; | |
3288 | } | |
3289 | ||
3290 | return rank_ != 0; | |
3291 | } | |
3292 | ||
3293 | - (NSArray *) tags { | |
3294 | return tags_; | |
3295 | } | |
3296 | ||
3297 | - (BOOL) hasTag:(NSString *)tag { | |
3298 | return tags_ == nil ? NO : [tags_ containsObject:tag]; | |
3299 | } | |
3300 | ||
3301 | - (NSString *) primaryPurpose { | |
3302 | for (NSString *tag in (NSArray *) tags_) | |
3303 | if ([tag hasPrefix:@"purpose::"]) | |
3304 | return [tag substringFromIndex:9]; | |
3305 | return nil; | |
3306 | } | |
3307 | ||
3308 | - (NSArray *) purposes { | |
3309 | NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]); | |
3310 | for (NSString *tag in (NSArray *) tags_) | |
3311 | if ([tag hasPrefix:@"purpose::"]) | |
3312 | [purposes addObject:[tag substringFromIndex:9]]; | |
3313 | return [purposes count] == 0 ? nil : purposes; | |
3314 | } | |
3315 | ||
3316 | - (bool) isCommercial { | |
3317 | return [self hasTag:@"cydia::commercial"]; | |
3318 | } | |
3319 | ||
3320 | - (void) setIndex:(size_t)index { | |
3321 | if (metadata_->index_ != index) | |
3322 | metadata_->index_ = index; | |
3323 | } | |
3324 | ||
3325 | - (CYString &) cyname { | |
3326 | return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_; | |
3327 | } | |
3328 | ||
3329 | - (uint32_t) compareBySection:(NSArray *)sections { | |
3330 | NSString *section([self section]); | |
3331 | for (size_t i(0), e([sections count]); i != e; ++i) { | |
3332 | if ([section isEqualToString:[[sections objectAtIndex:i] name]]) | |
3333 | return i; | |
3334 | } | |
3335 | ||
3336 | return _not(uint32_t); | |
3337 | } | |
3338 | ||
3339 | - (void) clear { | |
3340 | @synchronized (database_) { | |
3341 | pkgProblemResolver *resolver = [database_ resolver]; | |
3342 | resolver->Clear(iterator_); | |
3343 | ||
3344 | pkgCacheFile &cache([database_ cache]); | |
3345 | cache->SetReInstall(iterator_, false); | |
3346 | cache->MarkKeep(iterator_, false); | |
3347 | } } | |
3348 | ||
3349 | - (void) install { | |
3350 | @synchronized (database_) { | |
3351 | pkgProblemResolver *resolver = [database_ resolver]; | |
3352 | resolver->Clear(iterator_); | |
3353 | resolver->Protect(iterator_); | |
3354 | ||
3355 | pkgCacheFile &cache([database_ cache]); | |
3356 | cache->SetReInstall(iterator_, false); | |
3357 | cache->MarkInstall(iterator_, false); | |
3358 | ||
3359 | pkgDepCache::StateCache &state((*cache)[iterator_]); | |
3360 | if (!state.Install()) | |
3361 | cache->SetReInstall(iterator_, true); | |
3362 | } } | |
3363 | ||
3364 | - (void) remove { | |
3365 | @synchronized (database_) { | |
3366 | pkgProblemResolver *resolver = [database_ resolver]; | |
3367 | resolver->Clear(iterator_); | |
3368 | resolver->Remove(iterator_); | |
3369 | resolver->Protect(iterator_); | |
3370 | ||
3371 | pkgCacheFile &cache([database_ cache]); | |
3372 | cache->SetReInstall(iterator_, false); | |
3373 | cache->MarkDelete(iterator_, true); | |
3374 | } } | |
3375 | ||
3376 | @end | |
3377 | /* }}} */ | |
3378 | /* Section Class {{{ */ | |
3379 | @interface Section : NSObject { | |
3380 | _H<NSString> name_; | |
3381 | size_t row_; | |
3382 | size_t count_; | |
3383 | _H<NSString> localized_; | |
3384 | } | |
3385 | ||
3386 | - (NSComparisonResult) compareByLocalized:(Section *)section; | |
3387 | - (Section *) initWithName:(NSString *)name localized:(NSString *)localized; | |
3388 | - (Section *) initWithName:(NSString *)name localize:(BOOL)localize; | |
3389 | - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize; | |
3390 | ||
3391 | - (NSString *) name; | |
3392 | - (void) setName:(NSString *)name; | |
3393 | ||
3394 | - (size_t) row; | |
3395 | - (size_t) count; | |
3396 | ||
3397 | - (void) addToRow; | |
3398 | - (void) addToCount; | |
3399 | ||
3400 | - (void) setCount:(size_t)count; | |
3401 | - (NSString *) localized; | |
3402 | ||
3403 | @end | |
3404 | ||
3405 | @implementation Section | |
3406 | ||
3407 | - (NSComparisonResult) compareByLocalized:(Section *)section { | |
3408 | NSString *lhs(localized_); | |
3409 | NSString *rhs([section localized]); | |
3410 | ||
3411 | /*if ([lhs length] != 0 && [rhs length] != 0) { | |
3412 | unichar lhc = [lhs characterAtIndex:0]; | |
3413 | unichar rhc = [rhs characterAtIndex:0]; | |
3414 | ||
3415 | if (isalpha(lhc) && !isalpha(rhc)) | |
3416 | return NSOrderedAscending; | |
3417 | else if (!isalpha(lhc) && isalpha(rhc)) | |
3418 | return NSOrderedDescending; | |
3419 | }*/ | |
3420 | ||
3421 | return [lhs compare:rhs options:LaxCompareOptions_]; | |
3422 | } | |
3423 | ||
3424 | - (Section *) initWithName:(NSString *)name localized:(NSString *)localized { | |
3425 | if ((self = [self initWithName:name localize:NO]) != nil) { | |
3426 | if (localized != nil) | |
3427 | localized_ = localized; | |
3428 | } return self; | |
3429 | } | |
3430 | ||
3431 | - (Section *) initWithName:(NSString *)name localize:(BOOL)localize { | |
3432 | return [self initWithName:name row:0 localize:localize]; | |
3433 | } | |
3434 | ||
3435 | - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize { | |
3436 | if ((self = [super init]) != nil) { | |
3437 | name_ = name; | |
3438 | row_ = row; | |
3439 | if (localize) | |
3440 | localized_ = LocalizeSection(name_); | |
3441 | } return self; | |
3442 | } | |
3443 | ||
3444 | - (NSString *) name { | |
3445 | return name_; | |
3446 | } | |
3447 | ||
3448 | - (void) setName:(NSString *)name { | |
3449 | name_ = name; | |
3450 | } | |
3451 | ||
3452 | - (size_t) row { | |
3453 | return row_; | |
3454 | } | |
3455 | ||
3456 | - (size_t) count { | |
3457 | return count_; | |
3458 | } | |
3459 | ||
3460 | - (void) addToRow { | |
3461 | ++row_; | |
3462 | } | |
3463 | ||
3464 | - (void) addToCount { | |
3465 | ++count_; | |
3466 | } | |
3467 | ||
3468 | - (void) setCount:(size_t)count { | |
3469 | count_ = count; | |
3470 | } | |
3471 | ||
3472 | - (NSString *) localized { | |
3473 | return localized_; | |
3474 | } | |
3475 | ||
3476 | @end | |
3477 | /* }}} */ | |
3478 | ||
3479 | class CydiaLogCleaner : | |
3480 | public pkgArchiveCleaner | |
3481 | { | |
3482 | protected: | |
3483 | virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) { | |
3484 | unlink(File); | |
3485 | } | |
3486 | }; | |
3487 | ||
3488 | /* Database Implementation {{{ */ | |
3489 | @implementation Database | |
3490 | ||
3491 | + (Database *) sharedInstance { | |
3492 | static _H<Database> instance; | |
3493 | if (instance == nil) | |
3494 | instance = [[[Database alloc] init] autorelease]; | |
3495 | return instance; | |
3496 | } | |
3497 | ||
3498 | - (unsigned) era { | |
3499 | return era_; | |
3500 | } | |
3501 | ||
3502 | - (void) releasePackages { | |
3503 | CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL); | |
3504 | CFArrayRemoveAllValues(packages_); | |
3505 | } | |
3506 | ||
3507 | - (void) dealloc { | |
3508 | // XXX: actually implement this thing | |
3509 | _assert(false); | |
3510 | [self releasePackages]; | |
3511 | NSRecycleZone(zone_); | |
3512 | [super dealloc]; | |
3513 | } | |
3514 | ||
3515 | - (void) _readCydia:(NSNumber *)fd { | |
3516 | __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in); | |
3517 | std::istream is(&ib); | |
3518 | std::string line; | |
3519 | ||
3520 | static RegEx finish_r("finish:([^:]*)"); | |
3521 | ||
3522 | while (std::getline(is, line)) { | |
3523 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
3524 | ||
3525 | const char *data(line.c_str()); | |
3526 | size_t size = line.size(); | |
3527 | lprintf("C:%s\n", data); | |
3528 | ||
3529 | if (finish_r(data, size)) { | |
3530 | NSString *finish = finish_r[1]; | |
3531 | int index = [Finishes_ indexOfObject:finish]; | |
3532 | if (index != INT_MAX && index > Finish_) | |
3533 | Finish_ = index; | |
3534 | } | |
3535 | ||
3536 | [pool release]; | |
3537 | } | |
3538 | ||
3539 | _assume(false); | |
3540 | } | |
3541 | ||
3542 | - (void) _readStatus:(NSNumber *)fd { | |
3543 | __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in); | |
3544 | std::istream is(&ib); | |
3545 | std::string line; | |
3546 | ||
3547 | static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *"); | |
3548 | static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)"); | |
3549 | ||
3550 | while (std::getline(is, line)) { | |
3551 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
3552 | ||
3553 | const char *data(line.c_str()); | |
3554 | size_t size(line.size()); | |
3555 | lprintf("S:%s\n", data); | |
3556 | ||
3557 | if (conffile_r(data, size)) { | |
3558 | // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1 | |
3559 | [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES]; | |
3560 | } else if (strncmp(data, "status: ", 8) == 0) { | |
3561 | // status: <package>: {unpacked,half-configured,installed} | |
3562 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]); | |
3563 | [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
3564 | } else if (strncmp(data, "processing: ", 12) == 0) { | |
3565 | // processing: configure: config-test | |
3566 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]); | |
3567 | [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
3568 | } else if (pmstatus_r(data, size)) { | |
3569 | std::string type([pmstatus_r[1] UTF8String]); | |
3570 | ||
3571 | NSString *package = pmstatus_r[2]; | |
3572 | if ([package isEqualToString:@"dpkg-exec"]) | |
3573 | package = nil; | |
3574 | ||
3575 | float percent([pmstatus_r[3] floatValue]); | |
3576 | [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES]; | |
3577 | ||
3578 | NSString *string = pmstatus_r[4]; | |
3579 | ||
3580 | if (type == "pmerror") { | |
3581 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]); | |
3582 | [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
3583 | } else if (type == "pmstatus") { | |
3584 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]); | |
3585 | [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
3586 | } else if (type == "pmconffile") | |
3587 | [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES]; | |
3588 | else | |
3589 | lprintf("E:unknown pmstatus\n"); | |
3590 | } else | |
3591 | lprintf("E:unknown status\n"); | |
3592 | ||
3593 | [pool release]; | |
3594 | } | |
3595 | ||
3596 | _assume(false); | |
3597 | } | |
3598 | ||
3599 | - (void) _readOutput:(NSNumber *)fd { | |
3600 | __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in); | |
3601 | std::istream is(&ib); | |
3602 | std::string line; | |
3603 | ||
3604 | while (std::getline(is, line)) { | |
3605 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
3606 | ||
3607 | lprintf("O:%s\n", line.c_str()); | |
3608 | ||
3609 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]); | |
3610 | [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
3611 | ||
3612 | [pool release]; | |
3613 | } | |
3614 | ||
3615 | _assume(false); | |
3616 | } | |
3617 | ||
3618 | - (FILE *) input { | |
3619 | return input_; | |
3620 | } | |
3621 | ||
3622 | - (Package *) packageWithName:(NSString *)name { | |
3623 | if (name == nil) | |
3624 | return nil; | |
3625 | @synchronized (self) { | |
3626 | if (static_cast<pkgDepCache *>(cache_) == NULL) | |
3627 | return nil; | |
3628 | pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String])); | |
3629 | return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self]; | |
3630 | } } | |
3631 | ||
3632 | - (id) init { | |
3633 | if ((self = [super init]) != nil) { | |
3634 | policy_ = NULL; | |
3635 | records_ = NULL; | |
3636 | resolver_ = NULL; | |
3637 | fetcher_ = NULL; | |
3638 | lock_ = NULL; | |
3639 | ||
3640 | zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO); | |
3641 | ||
3642 | size_t capacity(MetaFile_->active_); | |
3643 | if (capacity == 0) | |
3644 | capacity = 16384; | |
3645 | else | |
3646 | capacity += 1024; | |
3647 | ||
3648 | packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL); | |
3649 | sourceList_ = [NSMutableArray arrayWithCapacity:16]; | |
3650 | ||
3651 | int fds[2]; | |
3652 | ||
3653 | _assert(pipe(fds) != -1); | |
3654 | cydiafd_ = fds[1]; | |
3655 | ||
3656 | _config->Set("APT::Keep-Fds::", cydiafd_); | |
3657 | setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int)); | |
3658 | ||
3659 | [NSThread | |
3660 | detachNewThreadSelector:@selector(_readCydia:) | |
3661 | toTarget:self | |
3662 | withObject:[NSNumber numberWithInt:fds[0]] | |
3663 | ]; | |
3664 | ||
3665 | _assert(pipe(fds) != -1); | |
3666 | statusfd_ = fds[1]; | |
3667 | ||
3668 | [NSThread | |
3669 | detachNewThreadSelector:@selector(_readStatus:) | |
3670 | toTarget:self | |
3671 | withObject:[NSNumber numberWithInt:fds[0]] | |
3672 | ]; | |
3673 | ||
3674 | _assert(pipe(fds) != -1); | |
3675 | _assert(dup2(fds[0], 0) != -1); | |
3676 | _assert(close(fds[0]) != -1); | |
3677 | ||
3678 | input_ = fdopen(fds[1], "a"); | |
3679 | ||
3680 | _assert(pipe(fds) != -1); | |
3681 | _assert(dup2(fds[1], 1) != -1); | |
3682 | _assert(close(fds[1]) != -1); | |
3683 | ||
3684 | [NSThread | |
3685 | detachNewThreadSelector:@selector(_readOutput:) | |
3686 | toTarget:self | |
3687 | withObject:[NSNumber numberWithInt:fds[0]] | |
3688 | ]; | |
3689 | } return self; | |
3690 | } | |
3691 | ||
3692 | - (pkgCacheFile &) cache { | |
3693 | return cache_; | |
3694 | } | |
3695 | ||
3696 | - (pkgDepCache::Policy *) policy { | |
3697 | return policy_; | |
3698 | } | |
3699 | ||
3700 | - (pkgRecords *) records { | |
3701 | return records_; | |
3702 | } | |
3703 | ||
3704 | - (pkgProblemResolver *) resolver { | |
3705 | return resolver_; | |
3706 | } | |
3707 | ||
3708 | - (pkgAcquire &) fetcher { | |
3709 | return *fetcher_; | |
3710 | } | |
3711 | ||
3712 | - (pkgSourceList &) list { | |
3713 | return *list_; | |
3714 | } | |
3715 | ||
3716 | - (NSArray *) packages { | |
3717 | return (NSArray *) packages_; | |
3718 | } | |
3719 | ||
3720 | - (NSArray *) sources { | |
3721 | return sourceList_; | |
3722 | } | |
3723 | ||
3724 | - (Source *) sourceWithKey:(NSString *)key { | |
3725 | for (Source *source in [self sources]) { | |
3726 | if ([[source key] isEqualToString:key]) | |
3727 | return source; | |
3728 | } return nil; | |
3729 | } | |
3730 | ||
3731 | - (bool) popErrorWithTitle:(NSString *)title { | |
3732 | bool fatal(false); | |
3733 | ||
3734 | while (!_error->empty()) { | |
3735 | std::string error; | |
3736 | bool warning(!_error->PopMessage(error)); | |
3737 | if (!warning) | |
3738 | fatal = true; | |
3739 | ||
3740 | for (;;) { | |
3741 | size_t size(error.size()); | |
3742 | if (size == 0 || error[size - 1] != '\n') | |
3743 | break; | |
3744 | error.resize(size - 1); | |
3745 | } | |
3746 | ||
3747 | lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str()); | |
3748 | ||
3749 | static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*"); | |
3750 | if (warning && no_pubkey(error.c_str())) | |
3751 | continue; | |
3752 | ||
3753 | [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title]; | |
3754 | } | |
3755 | ||
3756 | return fatal; | |
3757 | } | |
3758 | ||
3759 | - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success { | |
3760 | return [self popErrorWithTitle:title] || !success; | |
3761 | } | |
3762 | ||
3763 | - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list { | |
3764 | if ([self popErrorWithTitle:title forOperation:list.ReadMainList()]) | |
3765 | return true; | |
3766 | return false; | |
3767 | ||
3768 | list.Reset(); | |
3769 | ||
3770 | bool error(false); | |
3771 | ||
3772 | if (access("/etc/apt/sources.list", F_OK) == 0) | |
3773 | error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")]; | |
3774 | ||
3775 | std::string base("/etc/apt/sources.list.d"); | |
3776 | if (DIR *sources = opendir(base.c_str())) { | |
3777 | while (dirent *source = readdir(sources)) | |
3778 | if (source->d_name[0] != '.' && source->d_namlen > 5 && strcmp(source->d_name + source->d_namlen - 5, ".list") == 0 && strcmp(source->d_name, "cydia.list") != 0) | |
3779 | error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())]; | |
3780 | closedir(sources); | |
3781 | } | |
3782 | ||
3783 | error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)]; | |
3784 | ||
3785 | return error; | |
3786 | } | |
3787 | ||
3788 | - (void) reloadDataWithInvocation:(NSInvocation *)invocation { | |
3789 | @synchronized (self) { | |
3790 | ++era_; | |
3791 | ||
3792 | [self releasePackages]; | |
3793 | ||
3794 | sourceMap_.clear(); | |
3795 | [sourceList_ removeAllObjects]; | |
3796 | ||
3797 | _error->Discard(); | |
3798 | ||
3799 | delete list_; | |
3800 | list_ = NULL; | |
3801 | manager_ = NULL; | |
3802 | delete lock_; | |
3803 | lock_ = NULL; | |
3804 | delete fetcher_; | |
3805 | fetcher_ = NULL; | |
3806 | delete resolver_; | |
3807 | resolver_ = NULL; | |
3808 | delete records_; | |
3809 | records_ = NULL; | |
3810 | delete policy_; | |
3811 | policy_ = NULL; | |
3812 | ||
3813 | cache_.Close(); | |
3814 | ||
3815 | pool_.~CYPool(); | |
3816 | new (&pool_) CYPool(); | |
3817 | ||
3818 | NSRecycleZone(zone_); | |
3819 | zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO); | |
3820 | ||
3821 | int chk(creat("/tmp/cydia.chk", 0644)); | |
3822 | if (chk != -1) | |
3823 | close(chk); | |
3824 | ||
3825 | if (invocation != nil) | |
3826 | [invocation invoke]; | |
3827 | ||
3828 | NSString *title(UCLocalize("DATABASE")); | |
3829 | ||
3830 | list_ = new pkgSourceList(); | |
3831 | _profile(reloadDataWithInvocation$ReadMainList) | |
3832 | if ([self popErrorWithTitle:title forReadList:*list_]) | |
3833 | return; | |
3834 | _end | |
3835 | ||
3836 | _profile(reloadDataWithInvocation$Source$initWithMetaIndex) | |
3837 | for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) { | |
3838 | Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]); | |
3839 | [sourceList_ addObject:object]; | |
3840 | } | |
3841 | _end | |
3842 | ||
3843 | _trace(); | |
3844 | OpProgress progress; | |
3845 | bool opened; | |
3846 | open: | |
3847 | delock_ = GetStatusDate(); | |
3848 | _profile(reloadDataWithInvocation$pkgCacheFile) | |
3849 | opened = cache_.Open(progress, false); | |
3850 | _end | |
3851 | if (!opened) { | |
3852 | // XXX: what if there are errors, but Open() == true? this should be merged with popError: | |
3853 | while (!_error->empty()) { | |
3854 | std::string error; | |
3855 | bool warning(!_error->PopMessage(error)); | |
3856 | ||
3857 | lprintf("cache_.Open():[%s]\n", error.c_str()); | |
3858 | ||
3859 | [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title]; | |
3860 | ||
3861 | SEL repair(NULL); | |
3862 | if (false); | |
3863 | else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ") | |
3864 | repair = @selector(configure); | |
3865 | //else if (error == "The package lists or status file could not be parsed or opened.") | |
3866 | // repair = @selector(update); | |
3867 | // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)") | |
3868 | // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)") | |
3869 | // else if (error == "Malformed Status line") | |
3870 | // else if (error == "The list of sources could not be read.") | |
3871 | ||
3872 | if (repair != NULL) { | |
3873 | _error->Discard(); | |
3874 | [delegate_ repairWithSelector:repair]; | |
3875 | goto open; | |
3876 | } | |
3877 | } | |
3878 | ||
3879 | return; | |
3880 | } | |
3881 | _trace(); | |
3882 | ||
3883 | unlink("/tmp/cydia.chk"); | |
3884 | ||
3885 | now_ = [[NSDate date] timeIntervalSince1970]; | |
3886 | ||
3887 | policy_ = new pkgDepCache::Policy(); | |
3888 | records_ = new pkgRecords(cache_); | |
3889 | resolver_ = new pkgProblemResolver(cache_); | |
3890 | fetcher_ = new pkgAcquire(&status_); | |
3891 | lock_ = NULL; | |
3892 | ||
3893 | if (cache_->DelCount() != 0 || cache_->InstCount() != 0) { | |
3894 | [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title]; | |
3895 | return; | |
3896 | } | |
3897 | ||
3898 | _profile(reloadDataWithInvocation$pkgApplyStatus) | |
3899 | if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)]) | |
3900 | return; | |
3901 | _end | |
3902 | ||
3903 | if (cache_->BrokenCount() != 0) { | |
3904 | _profile(pkgApplyStatus$pkgFixBroken) | |
3905 | if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)]) | |
3906 | return; | |
3907 | _end | |
3908 | ||
3909 | if (cache_->BrokenCount() != 0) { | |
3910 | [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title]; | |
3911 | return; | |
3912 | } | |
3913 | ||
3914 | _profile(pkgApplyStatus$pkgMinimizeUpgrade) | |
3915 | if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)]) | |
3916 | return; | |
3917 | _end | |
3918 | } | |
3919 | ||
3920 | for (Source *object in (id) sourceList_) { | |
3921 | metaIndex *source([object metaIndex]); | |
3922 | std::vector<pkgIndexFile *> *indices = source->GetIndexFiles(); | |
3923 | for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index) | |
3924 | // XXX: this could be more intelligent | |
3925 | if (dynamic_cast<debPackagesIndex *>(*index) != NULL) { | |
3926 | pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_)); | |
3927 | if (!cached.end()) | |
3928 | sourceMap_[cached->ID] = object; | |
3929 | } | |
3930 | } | |
3931 | ||
3932 | { | |
3933 | /*std::vector<Package *> packages; | |
3934 | packages.reserve(std::max(10000U, [packages_ count] + 1000)); | |
3935 | packages_ = nil;*/ | |
3936 | ||
3937 | _profile(reloadDataWithInvocation$packageWithIterator) | |
3938 | for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator) | |
3939 | if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) | |
3940 | //packages.push_back(package); | |
3941 | CFArrayAppendValue(packages_, CFRetain(package)); | |
3942 | _end | |
3943 | ||
3944 | ||
3945 | /*if (packages.empty()) | |
3946 | packages_ = [[NSArray alloc] init]; | |
3947 | else | |
3948 | packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()]; | |
3949 | _trace();*/ | |
3950 | ||
3951 | _profile(reloadDataWithInvocation$radix$8) | |
3952 | [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)]; | |
3953 | _end | |
3954 | ||
3955 | _profile(reloadDataWithInvocation$radix$4) | |
3956 | [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)]; | |
3957 | _end | |
3958 | ||
3959 | _profile(reloadDataWithInvocation$radix$0) | |
3960 | [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)]; | |
3961 | _end | |
3962 | ||
3963 | _profile(reloadDataWithInvocation$insertion) | |
3964 | CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL); | |
3965 | _end | |
3966 | ||
3967 | /*_profile(reloadDataWithInvocation$CFQSortArray) | |
3968 | CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL); | |
3969 | _end*/ | |
3970 | ||
3971 | /*_profile(reloadDataWithInvocation$stdsort) | |
3972 | std::sort(packages.begin(), packages.end(), PackageNameOrdering()); | |
3973 | _end*/ | |
3974 | ||
3975 | /*_profile(reloadDataWithInvocation$CFArraySortValues) | |
3976 | CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL); | |
3977 | _end*/ | |
3978 | ||
3979 | /*_profile(reloadDataWithInvocation$sortUsingFunction) | |
3980 | [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL]; | |
3981 | _end*/ | |
3982 | ||
3983 | ||
3984 | size_t count(CFArrayGetCount(packages_)); | |
3985 | MetaFile_->active_ = count; | |
3986 | for (size_t index(0); index != count; ++index) | |
3987 | [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index]; | |
3988 | } | |
3989 | } } | |
3990 | ||
3991 | - (void) clear { | |
3992 | @synchronized (self) { | |
3993 | delete resolver_; | |
3994 | resolver_ = new pkgProblemResolver(cache_); | |
3995 | ||
3996 | for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) | |
3997 | if (!cache_[iterator].Keep()) | |
3998 | cache_->MarkKeep(iterator, false); | |
3999 | else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0) | |
4000 | cache_->SetReInstall(iterator, false); | |
4001 | } } | |
4002 | ||
4003 | - (void) configure { | |
4004 | NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_]; | |
4005 | _trace(); | |
4006 | system([dpkg UTF8String]); | |
4007 | _trace(); | |
4008 | } | |
4009 | ||
4010 | - (bool) clean { | |
4011 | @synchronized (self) { | |
4012 | // XXX: I don't remember this condition | |
4013 | if (lock_ != NULL) | |
4014 | return false; | |
4015 | ||
4016 | FileFd Lock; | |
4017 | Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock")); | |
4018 | ||
4019 | NSString *title(UCLocalize("CLEAN_ARCHIVES")); | |
4020 | ||
4021 | if ([self popErrorWithTitle:title]) | |
4022 | return false; | |
4023 | ||
4024 | pkgAcquire fetcher; | |
4025 | fetcher.Clean(_config->FindDir("Dir::Cache::Archives")); | |
4026 | ||
4027 | CydiaLogCleaner cleaner; | |
4028 | if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)]) | |
4029 | return false; | |
4030 | ||
4031 | return true; | |
4032 | } } | |
4033 | ||
4034 | - (bool) prepare { | |
4035 | fetcher_->Shutdown(); | |
4036 | ||
4037 | pkgRecords records(cache_); | |
4038 | ||
4039 | lock_ = new FileFd(); | |
4040 | lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock")); | |
4041 | ||
4042 | NSString *title(UCLocalize("PREPARE_ARCHIVES")); | |
4043 | ||
4044 | if ([self popErrorWithTitle:title]) | |
4045 | return false; | |
4046 | ||
4047 | pkgSourceList list; | |
4048 | if ([self popErrorWithTitle:title forReadList:list]) | |
4049 | return false; | |
4050 | ||
4051 | manager_ = (_system->CreatePM(cache_)); | |
4052 | if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)]) | |
4053 | return false; | |
4054 | ||
4055 | return true; | |
4056 | } | |
4057 | ||
4058 | - (void) perform { | |
4059 | bool substrate(RestartSubstrate_); | |
4060 | RestartSubstrate_ = false; | |
4061 | ||
4062 | NSString *title(UCLocalize("PERFORM_SELECTIONS")); | |
4063 | ||
4064 | NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; { | |
4065 | pkgSourceList list; | |
4066 | if ([self popErrorWithTitle:title forReadList:list]) | |
4067 | return; | |
4068 | for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source) | |
4069 | [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]]; | |
4070 | } | |
4071 | ||
4072 | [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES]; | |
4073 | ||
4074 | if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) { | |
4075 | _trace(); | |
4076 | [self popErrorWithTitle:title]; | |
4077 | return; | |
4078 | } | |
4079 | ||
4080 | bool failed = false; | |
4081 | for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) { | |
4082 | if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete) | |
4083 | continue; | |
4084 | if ((*item)->Status == pkgAcquire::Item::StatIdle) | |
4085 | continue; | |
4086 | ||
4087 | std::string uri = (*item)->DescURI(); | |
4088 | std::string error = (*item)->ErrorText; | |
4089 | ||
4090 | lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str()); | |
4091 | failed = true; | |
4092 | ||
4093 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]); | |
4094 | [delegate_ addProgressEventOnMainThread:event forTask:title]; | |
4095 | } | |
4096 | ||
4097 | [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES]; | |
4098 | ||
4099 | if (failed) { | |
4100 | _trace(); | |
4101 | return; | |
4102 | } | |
4103 | ||
4104 | if (substrate) | |
4105 | RestartSubstrate_ = true; | |
4106 | ||
4107 | if (![delock_ isEqual:GetStatusDate()]) { | |
4108 | [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title]; | |
4109 | return; | |
4110 | } | |
4111 | ||
4112 | delock_ = nil; | |
4113 | ||
4114 | pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_)); | |
4115 | ||
4116 | NSString *oextended(@"/var/lib/apt/extended_states"); | |
4117 | NSString *nextended(Cache("extended_states")); | |
4118 | ||
4119 | struct stat info; | |
4120 | if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG) { | |
4121 | system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/mv -f %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]); | |
4122 | system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/chown 0:0 %@", ShellEscape(oextended)] UTF8String]); | |
4123 | } | |
4124 | ||
4125 | unlink([nextended UTF8String]); | |
4126 | symlink([oextended UTF8String], [nextended UTF8String]); | |
4127 | ||
4128 | if ([self popErrorWithTitle:title]) | |
4129 | return; | |
4130 | ||
4131 | if (result == pkgPackageManager::Failed) { | |
4132 | _trace(); | |
4133 | return; | |
4134 | } | |
4135 | ||
4136 | if (result != pkgPackageManager::Completed) { | |
4137 | _trace(); | |
4138 | return; | |
4139 | } | |
4140 | ||
4141 | NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; { | |
4142 | pkgSourceList list; | |
4143 | if ([self popErrorWithTitle:title forReadList:list]) | |
4144 | return; | |
4145 | for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source) | |
4146 | [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]]; | |
4147 | } | |
4148 | ||
4149 | if (![before isEqualToArray:after]) | |
4150 | [self update]; | |
4151 | } | |
4152 | ||
4153 | - (bool) delocked { | |
4154 | return ![delock_ isEqual:GetStatusDate()]; | |
4155 | } | |
4156 | ||
4157 | - (bool) upgrade { | |
4158 | NSString *title(UCLocalize("UPGRADE")); | |
4159 | if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)]) | |
4160 | return false; | |
4161 | return true; | |
4162 | } | |
4163 | ||
4164 | - (void) update { | |
4165 | [self updateWithStatus:status_]; | |
4166 | } | |
4167 | ||
4168 | - (void) updateWithStatus:(CancelStatus &)status { | |
4169 | NSString *title(UCLocalize("REFRESHING_DATA")); | |
4170 | ||
4171 | pkgSourceList list; | |
4172 | if ([self popErrorWithTitle:title forReadList:list]) | |
4173 | return; | |
4174 | ||
4175 | FileFd lock; | |
4176 | lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock")); | |
4177 | if ([self popErrorWithTitle:title]) | |
4178 | return; | |
4179 | ||
4180 | [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES]; | |
4181 | ||
4182 | bool success(ListUpdate(status, list, PulseInterval_)); | |
4183 | if (status.WasCancelled()) | |
4184 | _error->Discard(); | |
4185 | else { | |
4186 | [self popErrorWithTitle:title forOperation:success]; | |
4187 | ||
4188 | [[NSDictionary dictionaryWithObjectsAndKeys: | |
4189 | [NSDate date], @"LastUpdate", | |
4190 | nil] writeToFile:@ CacheState_ atomically:YES]; | |
4191 | } | |
4192 | ||
4193 | [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES]; | |
4194 | } | |
4195 | ||
4196 | - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate { | |
4197 | delegate_ = delegate; | |
4198 | } | |
4199 | ||
4200 | - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate { | |
4201 | progress_ = delegate; | |
4202 | status_.setDelegate(delegate); | |
4203 | } | |
4204 | ||
4205 | - (NSObject<ProgressDelegate> *) progressDelegate { | |
4206 | return progress_; | |
4207 | } | |
4208 | ||
4209 | - (Source *) getSource:(pkgCache::PkgFileIterator)file { | |
4210 | SourceMap::const_iterator i(sourceMap_.find(file->ID)); | |
4211 | return i == sourceMap_.end() ? nil : i->second; | |
4212 | } | |
4213 | ||
4214 | - (void) setFetch:(bool)fetch forURI:(const char *)uri { | |
4215 | for (Source *source in (id) sourceList_) | |
4216 | [source setFetch:fetch forURI:uri]; | |
4217 | } | |
4218 | ||
4219 | - (void) resetFetch { | |
4220 | for (Source *source in (id) sourceList_) | |
4221 | [source resetFetch]; | |
4222 | } | |
4223 | ||
4224 | - (NSString *) mappedSectionForPointer:(const char *)section { | |
4225 | _H<NSString> *mapped; | |
4226 | ||
4227 | _profile(Database$mappedSectionForPointer$Cache) | |
4228 | mapped = §ions_[section]; | |
4229 | _end | |
4230 | ||
4231 | if (*mapped == NULL) { | |
4232 | size_t length(strlen(section)); | |
4233 | char spaced[length + 1]; | |
4234 | ||
4235 | _profile(Database$mappedSectionForPointer$Replace) | |
4236 | for (size_t index(0); index != length; ++index) | |
4237 | spaced[index] = section[index] == '_' ? ' ' : section[index]; | |
4238 | spaced[length] = '\0'; | |
4239 | _end | |
4240 | ||
4241 | NSString *string; | |
4242 | ||
4243 | _profile(Database$mappedSectionForPointer$stringWithUTF8String) | |
4244 | string = [NSString stringWithUTF8String:spaced]; | |
4245 | _end | |
4246 | ||
4247 | _profile(Database$mappedSectionForPointer$Map) | |
4248 | string = [SectionMap_ objectForKey:string] ?: string; | |
4249 | _end | |
4250 | ||
4251 | *mapped = string; | |
4252 | } return *mapped; | |
4253 | } | |
4254 | ||
4255 | @end | |
4256 | /* }}} */ | |
4257 | ||
4258 | static _H<NSMutableSet> Diversions_; | |
4259 | ||
4260 | @interface Diversion : NSObject { | |
4261 | RegEx pattern_; | |
4262 | _H<NSString> key_; | |
4263 | _H<NSString> format_; | |
4264 | } | |
4265 | ||
4266 | @end | |
4267 | ||
4268 | @implementation Diversion | |
4269 | ||
4270 | - (id) initWithFrom:(NSString *)from to:(NSString *)to { | |
4271 | if ((self = [super init]) != nil) { | |
4272 | pattern_ = [from UTF8String]; | |
4273 | key_ = from; | |
4274 | format_ = to; | |
4275 | } return self; | |
4276 | } | |
4277 | ||
4278 | - (NSString *) divert:(NSString *)url { | |
4279 | return !pattern_(url) ? nil : pattern_->*format_; | |
4280 | } | |
4281 | ||
4282 | + (NSURL *) divertURL:(NSURL *)url { | |
4283 | divert: | |
4284 | NSString *href([url absoluteString]); | |
4285 | ||
4286 | for (Diversion *diversion in (id) Diversions_) | |
4287 | if (NSString *diverted = [diversion divert:href]) { | |
4288 | #if !ForRelease | |
4289 | NSLog(@"div: %@", diverted); | |
4290 | #endif | |
4291 | url = [NSURL URLWithString:diverted]; | |
4292 | goto divert; | |
4293 | } | |
4294 | ||
4295 | return url; | |
4296 | } | |
4297 | ||
4298 | - (NSString *) key { | |
4299 | return key_; | |
4300 | } | |
4301 | ||
4302 | - (NSUInteger) hash { | |
4303 | return [key_ hash]; | |
4304 | } | |
4305 | ||
4306 | - (BOOL) isEqual:(Diversion *)object { | |
4307 | return self == object || [self class] == [object class] && [key_ isEqual:[object key]]; | |
4308 | } | |
4309 | ||
4310 | @end | |
4311 | ||
4312 | @interface CydiaObject : NSObject { | |
4313 | _H<CyteWebViewController> indirect_; | |
4314 | _transient id delegate_; | |
4315 | } | |
4316 | ||
4317 | - (id) initWithDelegate:(IndirectDelegate *)indirect; | |
4318 | ||
4319 | @end | |
4320 | ||
4321 | @class CydiaObject; | |
4322 | ||
4323 | @interface CydiaWebViewController : CyteWebViewController { | |
4324 | _H<CydiaObject> cydia_; | |
4325 | } | |
4326 | ||
4327 | + (void) addDiversion:(Diversion *)diversion; | |
4328 | + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request; | |
4329 | + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia; | |
4330 | - (void) setDelegate:(id)delegate; | |
4331 | ||
4332 | @end | |
4333 | ||
4334 | /* Web Scripting {{{ */ | |
4335 | @implementation CydiaObject | |
4336 | ||
4337 | - (id) initWithDelegate:(IndirectDelegate *)indirect { | |
4338 | if ((self = [super init]) != nil) { | |
4339 | indirect_ = (CyteWebViewController *) indirect; | |
4340 | } return self; | |
4341 | } | |
4342 | ||
4343 | - (void) setDelegate:(id)delegate { | |
4344 | delegate_ = delegate; | |
4345 | } | |
4346 | ||
4347 | + (NSArray *) _attributeKeys { | |
4348 | return [NSArray arrayWithObjects: | |
4349 | @"bbsnum", | |
4350 | @"build", | |
4351 | @"coreFoundationVersionNumber", | |
4352 | @"device", | |
4353 | @"ecid", | |
4354 | @"firmware", | |
4355 | @"hostname", | |
4356 | @"idiom", | |
4357 | @"mcc", | |
4358 | @"mnc", | |
4359 | @"model", | |
4360 | @"operator", | |
4361 | @"role", | |
4362 | @"serial", | |
4363 | @"version", | |
4364 | nil]; | |
4365 | } | |
4366 | ||
4367 | - (NSArray *) attributeKeys { | |
4368 | return [[self class] _attributeKeys]; | |
4369 | } | |
4370 | ||
4371 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
4372 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
4373 | } | |
4374 | ||
4375 | - (NSString *) version { | |
4376 | return Cydia_; | |
4377 | } | |
4378 | ||
4379 | - (NSString *) build { | |
4380 | return System_; | |
4381 | } | |
4382 | ||
4383 | - (NSString *) coreFoundationVersionNumber { | |
4384 | return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber]; | |
4385 | } | |
4386 | ||
4387 | - (NSString *) device { | |
4388 | return UniqueIdentifier(); | |
4389 | } | |
4390 | ||
4391 | - (NSString *) firmware { | |
4392 | return [[UIDevice currentDevice] systemVersion]; | |
4393 | } | |
4394 | ||
4395 | - (NSString *) hostname { | |
4396 | return [[UIDevice currentDevice] name]; | |
4397 | } | |
4398 | ||
4399 | - (NSString *) idiom { | |
4400 | return (id) Idiom_ ?: [NSNull null]; | |
4401 | } | |
4402 | ||
4403 | - (NSString *) mcc { | |
4404 | if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"))) | |
4405 | return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease]; | |
4406 | return nil; | |
4407 | } | |
4408 | ||
4409 | - (NSString *) mnc { | |
4410 | if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode"))) | |
4411 | return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease]; | |
4412 | return nil; | |
4413 | } | |
4414 | ||
4415 | - (NSString *) operator { | |
4416 | if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName"))) | |
4417 | return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease]; | |
4418 | return nil; | |
4419 | } | |
4420 | ||
4421 | - (NSString *) bbsnum { | |
4422 | return (id) BBSNum_ ?: [NSNull null]; | |
4423 | } | |
4424 | ||
4425 | - (NSString *) ecid { | |
4426 | return (id) ChipID_ ?: [NSNull null]; | |
4427 | } | |
4428 | ||
4429 | - (NSString *) serial { | |
4430 | return SerialNumber_; | |
4431 | } | |
4432 | ||
4433 | - (NSString *) role { | |
4434 | return (id) [NSNull null]; | |
4435 | } | |
4436 | ||
4437 | - (NSString *) model { | |
4438 | return [NSString stringWithUTF8String:Machine_]; | |
4439 | } | |
4440 | ||
4441 | + (NSString *) webScriptNameForSelector:(SEL)selector { | |
4442 | if (false); | |
4443 | else if (selector == @selector(addBridgedHost:)) | |
4444 | return @"addBridgedHost"; | |
4445 | else if (selector == @selector(addInsecureHost:)) | |
4446 | return @"addInsecureHost"; | |
4447 | else if (selector == @selector(addInternalRedirect::)) | |
4448 | return @"addInternalRedirect"; | |
4449 | else if (selector == @selector(addPipelinedHost:scheme:)) | |
4450 | return @"addPipelinedHost"; | |
4451 | else if (selector == @selector(addSource:::)) | |
4452 | return @"addSource"; | |
4453 | else if (selector == @selector(addTrivialSource:)) | |
4454 | return @"addTrivialSource"; | |
4455 | else if (selector == @selector(close)) | |
4456 | return @"close"; | |
4457 | else if (selector == @selector(du:)) | |
4458 | return @"du"; | |
4459 | else if (selector == @selector(stringWithFormat:arguments:)) | |
4460 | return @"format"; | |
4461 | else if (selector == @selector(getAllSources)) | |
4462 | return @"getAllSources"; | |
4463 | else if (selector == @selector(getApplicationInfo:value:)) | |
4464 | return @"getApplicationInfoValue"; | |
4465 | else if (selector == @selector(getDisplayIdentifiers)) | |
4466 | return @"getDisplayIdentifiers"; | |
4467 | else if (selector == @selector(getLocalizedNameForDisplayIdentifier:)) | |
4468 | return @"getLocalizedNameForDisplayIdentifier"; | |
4469 | else if (selector == @selector(getKernelNumber:)) | |
4470 | return @"getKernelNumber"; | |
4471 | else if (selector == @selector(getKernelString:)) | |
4472 | return @"getKernelString"; | |
4473 | else if (selector == @selector(getInstalledPackages)) | |
4474 | return @"getInstalledPackages"; | |
4475 | else if (selector == @selector(getIORegistryEntry::)) | |
4476 | return @"getIORegistryEntry"; | |
4477 | else if (selector == @selector(getLocaleIdentifier)) | |
4478 | return @"getLocaleIdentifier"; | |
4479 | else if (selector == @selector(getPreferredLanguages)) | |
4480 | return @"getPreferredLanguages"; | |
4481 | else if (selector == @selector(getPackageById:)) | |
4482 | return @"getPackageById"; | |
4483 | else if (selector == @selector(getMetadataKeys)) | |
4484 | return @"getMetadataKeys"; | |
4485 | else if (selector == @selector(getMetadataValue:)) | |
4486 | return @"getMetadataValue"; | |
4487 | else if (selector == @selector(getSessionValue:)) | |
4488 | return @"getSessionValue"; | |
4489 | else if (selector == @selector(installPackages:)) | |
4490 | return @"installPackages"; | |
4491 | else if (selector == @selector(isReachable:)) | |
4492 | return @"isReachable"; | |
4493 | else if (selector == @selector(localizedStringForKey:value:table:)) | |
4494 | return @"localize"; | |
4495 | else if (selector == @selector(popViewController:)) | |
4496 | return @"popViewController"; | |
4497 | else if (selector == @selector(refreshSources)) | |
4498 | return @"refreshSources"; | |
4499 | else if (selector == @selector(registerFrame:)) | |
4500 | return @"registerFrame"; | |
4501 | else if (selector == @selector(removeButton)) | |
4502 | return @"removeButton"; | |
4503 | else if (selector == @selector(saveConfig)) | |
4504 | return @"saveConfig"; | |
4505 | else if (selector == @selector(setMetadataValue::)) | |
4506 | return @"setMetadataValue"; | |
4507 | else if (selector == @selector(setSessionValue::)) | |
4508 | return @"setSessionValue"; | |
4509 | else if (selector == @selector(substitutePackageNames:)) | |
4510 | return @"substitutePackageNames"; | |
4511 | else if (selector == @selector(scrollToBottom:)) | |
4512 | return @"scrollToBottom"; | |
4513 | else if (selector == @selector(setAllowsNavigationAction:)) | |
4514 | return @"setAllowsNavigationAction"; | |
4515 | else if (selector == @selector(setBadgeValue:)) | |
4516 | return @"setBadgeValue"; | |
4517 | else if (selector == @selector(setButtonImage:withStyle:toFunction:)) | |
4518 | return @"setButtonImage"; | |
4519 | else if (selector == @selector(setButtonTitle:withStyle:toFunction:)) | |
4520 | return @"setButtonTitle"; | |
4521 | else if (selector == @selector(setHidesBackButton:)) | |
4522 | return @"setHidesBackButton"; | |
4523 | else if (selector == @selector(setHidesNavigationBar:)) | |
4524 | return @"setHidesNavigationBar"; | |
4525 | else if (selector == @selector(setNavigationBarStyle:)) | |
4526 | return @"setNavigationBarStyle"; | |
4527 | else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:)) | |
4528 | return @"setNavigationBarTintColor"; | |
4529 | else if (selector == @selector(setPasteboardString:)) | |
4530 | return @"setPasteboardString"; | |
4531 | else if (selector == @selector(setPasteboardURL:)) | |
4532 | return @"setPasteboardURL"; | |
4533 | else if (selector == @selector(setScrollAlwaysBounceVertical:)) | |
4534 | return @"setScrollAlwaysBounceVertical"; | |
4535 | else if (selector == @selector(setScrollIndicatorStyle:)) | |
4536 | return @"setScrollIndicatorStyle"; | |
4537 | else if (selector == @selector(setToken:)) | |
4538 | return @"setToken"; | |
4539 | else if (selector == @selector(setViewportWidth:)) | |
4540 | return @"setViewportWidth"; | |
4541 | else if (selector == @selector(statfs:)) | |
4542 | return @"statfs"; | |
4543 | else if (selector == @selector(supports:)) | |
4544 | return @"supports"; | |
4545 | else if (selector == @selector(unload)) | |
4546 | return @"unload"; | |
4547 | else | |
4548 | return nil; | |
4549 | } | |
4550 | ||
4551 | + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector { | |
4552 | return [self webScriptNameForSelector:selector] == nil; | |
4553 | } | |
4554 | ||
4555 | - (BOOL) supports:(NSString *)feature { | |
4556 | return [feature isEqualToString:@"window.open"]; | |
4557 | } | |
4558 | ||
4559 | - (void) unload { | |
4560 | [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO]; | |
4561 | } | |
4562 | ||
4563 | - (void) setScrollAlwaysBounceVertical:(NSNumber *)value { | |
4564 | [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO]; | |
4565 | } | |
4566 | ||
4567 | - (void) setScrollIndicatorStyle:(NSString *)style { | |
4568 | [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO]; | |
4569 | } | |
4570 | ||
4571 | - (void) addInternalRedirect:(NSString *)from :(NSString *)to { | |
4572 | [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO]; | |
4573 | } | |
4574 | ||
4575 | - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key { | |
4576 | char path[1024]; | |
4577 | if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0) | |
4578 | return (id) [NSNull null]; | |
4579 | NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]); | |
4580 | if (info == nil) | |
4581 | return (id) [NSNull null]; | |
4582 | return [info objectForKey:key]; | |
4583 | } | |
4584 | ||
4585 | - (NSArray *) getDisplayIdentifiers { | |
4586 | NSSet *set([SBSCopyDisplayIdentifiers() autorelease]); | |
4587 | if (set == nil || ![set isKindOfClass:[NSSet class]]) | |
4588 | return [NSArray array]; | |
4589 | return [set allObjects]; | |
4590 | } | |
4591 | ||
4592 | - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier { | |
4593 | return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null]; | |
4594 | } | |
4595 | ||
4596 | - (NSNumber *) getKernelNumber:(NSString *)name { | |
4597 | const char *string([name UTF8String]); | |
4598 | ||
4599 | size_t size; | |
4600 | if (sysctlbyname(string, NULL, &size, NULL, 0) == -1) | |
4601 | return (id) [NSNull null]; | |
4602 | ||
4603 | if (size != sizeof(int)) | |
4604 | return (id) [NSNull null]; | |
4605 | ||
4606 | int value; | |
4607 | if (sysctlbyname(string, &value, &size, NULL, 0) == -1) | |
4608 | return (id) [NSNull null]; | |
4609 | ||
4610 | return [NSNumber numberWithInt:value]; | |
4611 | } | |
4612 | ||
4613 | - (NSString *) getKernelString:(NSString *)name { | |
4614 | const char *string([name UTF8String]); | |
4615 | ||
4616 | size_t size; | |
4617 | if (sysctlbyname(string, NULL, &size, NULL, 0) == -1) | |
4618 | return (id) [NSNull null]; | |
4619 | ||
4620 | char value[size + 1]; | |
4621 | if (sysctlbyname(string, value, &size, NULL, 0) == -1) | |
4622 | return (id) [NSNull null]; | |
4623 | ||
4624 | // XXX: just in case you request something ludicrous | |
4625 | value[size] = '\0'; | |
4626 | ||
4627 | return [NSString stringWithCString:value]; | |
4628 | } | |
4629 | ||
4630 | - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry { | |
4631 | NSObject *value(CYIOGetValue([path UTF8String], entry)); | |
4632 | ||
4633 | if (value != nil) | |
4634 | if ([value isKindOfClass:[NSData class]]) | |
4635 | value = CYHex((NSData *) value); | |
4636 | ||
4637 | return value; | |
4638 | } | |
4639 | ||
4640 | - (NSArray *) getMetadataKeys { | |
4641 | @synchronized (Values_) { | |
4642 | return [Values_ allKeys]; | |
4643 | } } | |
4644 | ||
4645 | - (void) registerFrame:(DOMHTMLIFrameElement *)iframe { | |
4646 | WebFrame *frame([iframe contentFrame]); | |
4647 | [indirect_ registerFrame:frame]; | |
4648 | } | |
4649 | ||
4650 | - (id) getMetadataValue:(NSString *)key { | |
4651 | @synchronized (Values_) { | |
4652 | return [Values_ objectForKey:key]; | |
4653 | } } | |
4654 | ||
4655 | - (void) setMetadataValue:(NSString *)key :(NSString *)value { | |
4656 | @synchronized (Values_) { | |
4657 | if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null]) | |
4658 | [Values_ removeObjectForKey:key]; | |
4659 | else | |
4660 | [Values_ setObject:value forKey:key]; | |
4661 | } } | |
4662 | ||
4663 | - (id) getSessionValue:(NSString *)key { | |
4664 | @synchronized (SessionData_) { | |
4665 | return [SessionData_ objectForKey:key]; | |
4666 | } } | |
4667 | ||
4668 | - (void) setSessionValue:(NSString *)key :(NSString *)value { | |
4669 | @synchronized (SessionData_) { | |
4670 | if (value == (id) [WebUndefined undefined]) | |
4671 | [SessionData_ removeObjectForKey:key]; | |
4672 | else | |
4673 | [SessionData_ setObject:value forKey:key]; | |
4674 | } } | |
4675 | ||
4676 | - (void) addBridgedHost:(NSString *)host { | |
4677 | @synchronized (HostConfig_) { | |
4678 | [BridgedHosts_ addObject:host]; | |
4679 | } } | |
4680 | ||
4681 | - (void) addInsecureHost:(NSString *)host { | |
4682 | @synchronized (HostConfig_) { | |
4683 | [InsecureHosts_ addObject:host]; | |
4684 | } } | |
4685 | ||
4686 | - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme { | |
4687 | @synchronized (HostConfig_) { | |
4688 | if (scheme != (id) [WebUndefined undefined]) | |
4689 | host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host]; | |
4690 | ||
4691 | [PipelinedHosts_ addObject:host]; | |
4692 | } } | |
4693 | ||
4694 | - (void) popViewController:(NSNumber *)value { | |
4695 | if (value == (id) [WebUndefined undefined]) | |
4696 | value = [NSNumber numberWithBool:YES]; | |
4697 | [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO]; | |
4698 | } | |
4699 | ||
4700 | - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections { | |
4701 | NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]); | |
4702 | ||
4703 | for (NSString *section in sections) | |
4704 | [array addObject:section]; | |
4705 | ||
4706 | [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys: | |
4707 | @"deb", @"Type", | |
4708 | href, @"URI", | |
4709 | distribution, @"Distribution", | |
4710 | array, @"Sections", | |
4711 | nil] waitUntilDone:NO]; | |
4712 | } | |
4713 | ||
4714 | - (BOOL) addTrivialSource:(NSString *)href { | |
4715 | href = VerifySource(href); | |
4716 | if (href == nil) | |
4717 | return NO; | |
4718 | [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO]; | |
4719 | return YES; | |
4720 | } | |
4721 | ||
4722 | - (void) refreshSources { | |
4723 | [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO]; | |
4724 | } | |
4725 | ||
4726 | - (void) saveConfig { | |
4727 | [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO]; | |
4728 | } | |
4729 | ||
4730 | - (NSArray *) getAllSources { | |
4731 | return [[Database sharedInstance] sources]; | |
4732 | } | |
4733 | ||
4734 | - (NSArray *) getInstalledPackages { | |
4735 | Database *database([Database sharedInstance]); | |
4736 | @synchronized (database) { | |
4737 | NSArray *packages([database packages]); | |
4738 | NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]); | |
4739 | for (Package *package in packages) | |
4740 | if (![package uninstalled]) | |
4741 | [installed addObject:package]; | |
4742 | return installed; | |
4743 | } } | |
4744 | ||
4745 | - (Package *) getPackageById:(NSString *)id { | |
4746 | if (Package *package = [[Database sharedInstance] packageWithName:id]) { | |
4747 | [package parse]; | |
4748 | return package; | |
4749 | } else | |
4750 | return (Package *) [NSNull null]; | |
4751 | } | |
4752 | ||
4753 | - (NSString *) getLocaleIdentifier { | |
4754 | return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_); | |
4755 | } | |
4756 | ||
4757 | - (NSArray *) getPreferredLanguages { | |
4758 | return Languages_; | |
4759 | } | |
4760 | ||
4761 | - (NSArray *) statfs:(NSString *)path { | |
4762 | struct statfs stat; | |
4763 | ||
4764 | if (path == nil || statfs([path UTF8String], &stat) == -1) | |
4765 | return nil; | |
4766 | ||
4767 | return [NSArray arrayWithObjects: | |
4768 | [NSNumber numberWithUnsignedLong:stat.f_bsize], | |
4769 | [NSNumber numberWithUnsignedLong:stat.f_blocks], | |
4770 | [NSNumber numberWithUnsignedLong:stat.f_bfree], | |
4771 | nil]; | |
4772 | } | |
4773 | ||
4774 | - (NSNumber *) du:(NSString *)path { | |
4775 | NSNumber *value(nil); | |
4776 | ||
4777 | FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r")); | |
4778 | if (du != NULL) { | |
4779 | char line[1024]; | |
4780 | while (fgets(line, sizeof(line), du) != NULL) { | |
4781 | size_t length(strlen(line)); | |
4782 | while (length != 0 && line[length - 1] == '\n') | |
4783 | line[--length] = '\0'; | |
4784 | if (char *tab = strchr(line, '\t')) { | |
4785 | *tab = '\0'; | |
4786 | value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)]; | |
4787 | } | |
4788 | } | |
4789 | pclose(du); | |
4790 | } | |
4791 | ||
4792 | return value; | |
4793 | } | |
4794 | ||
4795 | - (void) close { | |
4796 | [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO]; | |
4797 | } | |
4798 | ||
4799 | - (NSNumber *) isReachable:(NSString *)name { | |
4800 | return [NSNumber numberWithBool:IsReachable([name UTF8String])]; | |
4801 | } | |
4802 | ||
4803 | - (void) installPackages:(NSArray *)packages { | |
4804 | [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO]; | |
4805 | } | |
4806 | ||
4807 | - (NSString *) substitutePackageNames:(NSString *)message { | |
4808 | NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]); | |
4809 | for (size_t i(0), e([words count]); i != e; ++i) { | |
4810 | NSString *word([words objectAtIndex:i]); | |
4811 | if (Package *package = [[Database sharedInstance] packageWithName:word]) | |
4812 | [words replaceObjectAtIndex:i withObject:[package name]]; | |
4813 | } | |
4814 | ||
4815 | return [words componentsJoinedByString:@" "]; | |
4816 | } | |
4817 | ||
4818 | - (void) removeButton { | |
4819 | [indirect_ removeButton]; | |
4820 | } | |
4821 | ||
4822 | - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function { | |
4823 | [indirect_ setButtonImage:button withStyle:style toFunction:function]; | |
4824 | } | |
4825 | ||
4826 | - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function { | |
4827 | [indirect_ setButtonTitle:button withStyle:style toFunction:function]; | |
4828 | } | |
4829 | ||
4830 | - (void) setBadgeValue:(id)value { | |
4831 | [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO]; | |
4832 | } | |
4833 | ||
4834 | - (void) setAllowsNavigationAction:(NSString *)value { | |
4835 | [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO]; | |
4836 | } | |
4837 | ||
4838 | - (void) setHidesBackButton:(NSString *)value { | |
4839 | [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO]; | |
4840 | } | |
4841 | ||
4842 | - (void) setHidesNavigationBar:(NSString *)value { | |
4843 | [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO]; | |
4844 | } | |
4845 | ||
4846 | - (void) setNavigationBarStyle:(NSString *)value { | |
4847 | [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO]; | |
4848 | } | |
4849 | ||
4850 | - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha { | |
4851 | float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]); | |
4852 | UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]); | |
4853 | [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO]; | |
4854 | } | |
4855 | ||
4856 | - (void) setPasteboardString:(NSString *)value { | |
4857 | [[objc_getClass("UIPasteboard") generalPasteboard] setString:value]; | |
4858 | } | |
4859 | ||
4860 | - (void) setPasteboardURL:(NSString *)value { | |
4861 | [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]]; | |
4862 | } | |
4863 | ||
4864 | - (void) setToken:(NSString *)token { | |
4865 | // XXX: the website expects this :/ | |
4866 | } | |
4867 | ||
4868 | - (void) scrollToBottom:(NSNumber *)animated { | |
4869 | [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO]; | |
4870 | } | |
4871 | ||
4872 | - (void) setViewportWidth:(float)width { | |
4873 | [indirect_ setViewportWidthOnMainThread:width]; | |
4874 | } | |
4875 | ||
4876 | - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments { | |
4877 | //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]); | |
4878 | unsigned count([arguments count]); | |
4879 | id values[count]; | |
4880 | for (unsigned i(0); i != count; ++i) | |
4881 | values[i] = [arguments objectAtIndex:i]; | |
4882 | return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease]; | |
4883 | } | |
4884 | ||
4885 | - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table { | |
4886 | if (reinterpret_cast<id>(value) == [WebUndefined undefined]) | |
4887 | value = nil; | |
4888 | if (reinterpret_cast<id>(table) == [WebUndefined undefined]) | |
4889 | table = nil; | |
4890 | return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table]; | |
4891 | } | |
4892 | ||
4893 | @end | |
4894 | /* }}} */ | |
4895 | ||
4896 | @interface NSURL (CydiaSecure) | |
4897 | @end | |
4898 | ||
4899 | @implementation NSURL (CydiaSecure) | |
4900 | ||
4901 | - (bool) isCydiaSecure { | |
4902 | if ([[[self scheme] lowercaseString] isEqualToString:@"https"]) | |
4903 | return true; | |
4904 | ||
4905 | @synchronized (HostConfig_) { | |
4906 | if ([InsecureHosts_ containsObject:[self host]]) | |
4907 | return true; | |
4908 | } | |
4909 | ||
4910 | return false; | |
4911 | } | |
4912 | ||
4913 | @end | |
4914 | ||
4915 | /* Cydia Browser Controller {{{ */ | |
4916 | @implementation CydiaWebViewController | |
4917 | ||
4918 | - (NSURL *) navigationURL { | |
4919 | return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]]; | |
4920 | } | |
4921 | ||
4922 | + (void) _initialize { | |
4923 | [super _initialize]; | |
4924 | ||
4925 | Diversions_ = [NSMutableSet setWithCapacity:0]; | |
4926 | } | |
4927 | ||
4928 | + (void) addDiversion:(Diversion *)diversion { | |
4929 | [Diversions_ addObject:diversion]; | |
4930 | } | |
4931 | ||
4932 | - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame { | |
4933 | [super webView:view didClearWindowObject:window forFrame:frame]; | |
4934 | [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_]; | |
4935 | } | |
4936 | ||
4937 | + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia { | |
4938 | WebDataSource *source([frame dataSource]); | |
4939 | NSURLResponse *response([source response]); | |
4940 | NSURL *url([response URL]); | |
4941 | NSString *scheme([[url scheme] lowercaseString]); | |
4942 | ||
4943 | bool bridged(false); | |
4944 | ||
4945 | @synchronized (HostConfig_) { | |
4946 | if ([scheme isEqualToString:@"file"]) | |
4947 | bridged = true; | |
4948 | else if ([scheme isEqualToString:@"https"]) | |
4949 | if ([BridgedHosts_ containsObject:[url host]]) | |
4950 | bridged = true; | |
4951 | } | |
4952 | ||
4953 | if (bridged) | |
4954 | [window setValue:cydia forKey:@"cydia"]; | |
4955 | } | |
4956 | ||
4957 | - (void) _setupMail:(MFMailComposeViewController *)controller { | |
4958 | [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"]; | |
4959 | ||
4960 | system("/usr/bin/dpkg -l >/tmp/dpkgl.log"); | |
4961 | [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"]; | |
4962 | } | |
4963 | ||
4964 | - (NSURL *) URLWithURL:(NSURL *)url { | |
4965 | return [Diversion divertURL:url]; | |
4966 | } | |
4967 | ||
4968 | - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source { | |
4969 | return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]]; | |
4970 | } | |
4971 | ||
4972 | - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source { | |
4973 | return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]]; | |
4974 | } | |
4975 | ||
4976 | + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request { | |
4977 | NSMutableURLRequest *copy([[request mutableCopy] autorelease]); | |
4978 | ||
4979 | NSURL *url([copy URL]); | |
4980 | NSString *href([url absoluteString]); | |
4981 | NSString *host([url host]); | |
4982 | ||
4983 | if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) { | |
4984 | if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) { | |
4985 | [copy setValue:agent forHTTPHeaderField:@"User-Agent"]; | |
4986 | [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"]; | |
4987 | } | |
4988 | ||
4989 | [copy setValue:nil forHTTPHeaderField:@"Referer"]; | |
4990 | [copy setValue:nil forHTTPHeaderField:@"Origin"]; | |
4991 | ||
4992 | [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]]; | |
4993 | return copy; | |
4994 | } | |
4995 | ||
4996 | if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil) | |
4997 | [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"]; | |
4998 | if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil) | |
4999 | [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"]; | |
5000 | ||
5001 | bool bridged; @synchronized (HostConfig_) { | |
5002 | bridged = [BridgedHosts_ containsObject:host]; | |
5003 | } | |
5004 | ||
5005 | if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil) | |
5006 | [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"]; | |
5007 | ||
5008 | return copy; | |
5009 | } | |
5010 | ||
5011 | - (void) setDelegate:(id)delegate { | |
5012 | [super setDelegate:delegate]; | |
5013 | [cydia_ setDelegate:delegate]; | |
5014 | } | |
5015 | ||
5016 | - (NSString *) applicationNameForUserAgent { | |
5017 | return UserAgent_; | |
5018 | } | |
5019 | ||
5020 | - (id) init { | |
5021 | if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) { | |
5022 | cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease]; | |
5023 | } return self; | |
5024 | } | |
5025 | ||
5026 | @end | |
5027 | ||
5028 | @interface AppCacheController : CydiaWebViewController { | |
5029 | } | |
5030 | ||
5031 | @end | |
5032 | ||
5033 | @implementation AppCacheController | |
5034 | ||
5035 | - (void) didReceiveMemoryWarning { | |
5036 | // XXX: this doesn't work | |
5037 | } | |
5038 | ||
5039 | - (bool) retainsNetworkActivityIndicator { | |
5040 | return false; | |
5041 | } | |
5042 | ||
5043 | @end | |
5044 | /* }}} */ | |
5045 | ||
5046 | // CydiaScript {{{ | |
5047 | @interface NSObject (CydiaScript) | |
5048 | - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context; | |
5049 | @end | |
5050 | ||
5051 | @implementation NSObject (CydiaScript) | |
5052 | ||
5053 | - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context { | |
5054 | return self; | |
5055 | } | |
5056 | ||
5057 | @end | |
5058 | ||
5059 | @implementation NSArray (CydiaScript) | |
5060 | ||
5061 | - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context { | |
5062 | WebScriptObject *object([context evaluateWebScript:@"[]"]); | |
5063 | for (size_t i(0), e([self count]); i != e; ++i) | |
5064 | [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]]; | |
5065 | return object; | |
5066 | } | |
5067 | ||
5068 | @end | |
5069 | ||
5070 | @implementation NSDictionary (CydiaScript) | |
5071 | ||
5072 | - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context { | |
5073 | WebScriptObject *object([context evaluateWebScript:@"({})"]); | |
5074 | for (id i in self) | |
5075 | [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i]; | |
5076 | return object; | |
5077 | } | |
5078 | ||
5079 | @end | |
5080 | // }}} | |
5081 | ||
5082 | /* Confirmation Controller {{{ */ | |
5083 | bool DepSubstrate(const pkgCache::VerIterator &iterator) { | |
5084 | if (!iterator.end()) | |
5085 | for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) { | |
5086 | if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends) | |
5087 | continue; | |
5088 | pkgCache::PkgIterator package(dep.TargetPkg()); | |
5089 | if (package.end()) | |
5090 | continue; | |
5091 | if (strcmp(package.Name(), "mobilesubstrate") == 0) | |
5092 | return true; | |
5093 | } | |
5094 | ||
5095 | return false; | |
5096 | } | |
5097 | ||
5098 | @protocol ConfirmationControllerDelegate | |
5099 | - (void) cancelAndClear:(bool)clear; | |
5100 | - (void) confirmWithNavigationController:(UINavigationController *)navigation; | |
5101 | - (void) queue; | |
5102 | @end | |
5103 | ||
5104 | @interface ConfirmationController : CydiaWebViewController { | |
5105 | _transient Database *database_; | |
5106 | ||
5107 | _H<UIAlertView> essential_; | |
5108 | ||
5109 | _H<NSDictionary> changes_; | |
5110 | _H<NSMutableArray> issues_; | |
5111 | _H<NSDictionary> sizes_; | |
5112 | ||
5113 | BOOL substrate_; | |
5114 | } | |
5115 | ||
5116 | - (id) initWithDatabase:(Database *)database; | |
5117 | ||
5118 | @end | |
5119 | ||
5120 | @implementation ConfirmationController | |
5121 | ||
5122 | - (void) complete { | |
5123 | if (substrate_) | |
5124 | RestartSubstrate_ = true; | |
5125 | [delegate_ confirmWithNavigationController:[self navigationController]]; | |
5126 | } | |
5127 | ||
5128 | - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { | |
5129 | NSString *context([alert context]); | |
5130 | ||
5131 | if ([context isEqualToString:@"remove"]) { | |
5132 | if (button == [alert cancelButtonIndex]) | |
5133 | [self _doContinue]; | |
5134 | else if (button == [alert firstOtherButtonIndex]) { | |
5135 | [self performSelector:@selector(complete) withObject:nil afterDelay:0]; | |
5136 | } | |
5137 | ||
5138 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
5139 | } else if ([context isEqualToString:@"unable"]) { | |
5140 | [self dismissModalViewControllerAnimated:YES]; | |
5141 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
5142 | } else { | |
5143 | [super alertView:alert clickedButtonAtIndex:button]; | |
5144 | } | |
5145 | } | |
5146 | ||
5147 | - (void) _doContinue { | |
5148 | [delegate_ cancelAndClear:NO]; | |
5149 | [self dismissModalViewControllerAnimated:YES]; | |
5150 | } | |
5151 | ||
5152 | - (id) invokeDefaultMethodWithArguments:(NSArray *)args { | |
5153 | [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO]; | |
5154 | return nil; | |
5155 | } | |
5156 | ||
5157 | - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame { | |
5158 | [super webView:view didClearWindowObject:window forFrame:frame]; | |
5159 | ||
5160 | [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys: | |
5161 | (id) changes_, @"changes", | |
5162 | (id) issues_, @"issues", | |
5163 | (id) sizes_, @"sizes", | |
5164 | self, @"queue", | |
5165 | nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"]; | |
5166 | } | |
5167 | ||
5168 | - (id) initWithDatabase:(Database *)database { | |
5169 | if ((self = [super init]) != nil) { | |
5170 | database_ = database; | |
5171 | ||
5172 | NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]); | |
5173 | NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]); | |
5174 | NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]); | |
5175 | NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]); | |
5176 | NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]); | |
5177 | ||
5178 | bool remove(false); | |
5179 | ||
5180 | pkgCacheFile &cache([database_ cache]); | |
5181 | NSArray *packages([database_ packages]); | |
5182 | pkgDepCache::Policy *policy([database_ policy]); | |
5183 | ||
5184 | issues_ = [NSMutableArray arrayWithCapacity:4]; | |
5185 | ||
5186 | for (Package *package in packages) { | |
5187 | pkgCache::PkgIterator iterator([package iterator]); | |
5188 | NSString *name([package id]); | |
5189 | ||
5190 | if ([package broken]) { | |
5191 | NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]); | |
5192 | ||
5193 | [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys: | |
5194 | name, @"package", | |
5195 | reasons, @"reasons", | |
5196 | nil]]; | |
5197 | ||
5198 | pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache)); | |
5199 | if (ver.end()) | |
5200 | continue; | |
5201 | ||
5202 | for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) { | |
5203 | pkgCache::DepIterator start; | |
5204 | pkgCache::DepIterator end; | |
5205 | dep.GlobOr(start, end); // ++dep | |
5206 | ||
5207 | if (!cache->IsImportantDep(end)) | |
5208 | continue; | |
5209 | if ((cache[end] & pkgDepCache::DepGInstall) != 0) | |
5210 | continue; | |
5211 | ||
5212 | NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]); | |
5213 | ||
5214 | [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys: | |
5215 | [NSString stringWithUTF8String:start.DepType()], @"relationship", | |
5216 | clauses, @"clauses", | |
5217 | nil]]; | |
5218 | ||
5219 | _forever { | |
5220 | NSString *reason, *installed((NSString *) [WebUndefined undefined]); | |
5221 | ||
5222 | pkgCache::PkgIterator target(start.TargetPkg()); | |
5223 | if (target->ProvidesList != 0) | |
5224 | reason = @"missing"; | |
5225 | else { | |
5226 | pkgCache::VerIterator ver(cache[target].InstVerIter(cache)); | |
5227 | if (!ver.end()) { | |
5228 | reason = @"installed"; | |
5229 | installed = [NSString stringWithUTF8String:ver.VerStr()]; | |
5230 | } else if (!cache[target].CandidateVerIter(cache).end()) | |
5231 | reason = @"uninstalled"; | |
5232 | else if (target->ProvidesList == 0) | |
5233 | reason = @"uninstallable"; | |
5234 | else | |
5235 | reason = @"virtual"; | |
5236 | } | |
5237 | ||
5238 | NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys: | |
5239 | [NSString stringWithUTF8String:start.CompType()], @"operator", | |
5240 | [NSString stringWithUTF8String:start.TargetVer()], @"value", | |
5241 | nil]); | |
5242 | ||
5243 | [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys: | |
5244 | [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package", | |
5245 | version, @"version", | |
5246 | reason, @"reason", | |
5247 | installed, @"installed", | |
5248 | nil]]; | |
5249 | ||
5250 | // yes, seriously. (wtf?) | |
5251 | if (start == end) | |
5252 | break; | |
5253 | ++start; | |
5254 | } | |
5255 | } | |
5256 | } | |
5257 | ||
5258 | pkgDepCache::StateCache &state(cache[iterator]); | |
5259 | ||
5260 | static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)"); | |
5261 | ||
5262 | if (state.NewInstall()) | |
5263 | [installs addObject:name]; | |
5264 | // XXX: else if (state.Install()) | |
5265 | else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall) | |
5266 | [reinstalls addObject:name]; | |
5267 | // XXX: move before previous if | |
5268 | else if (state.Upgrade()) | |
5269 | [upgrades addObject:name]; | |
5270 | else if (state.Downgrade()) | |
5271 | [downgrades addObject:name]; | |
5272 | else if (!state.Delete()) | |
5273 | // XXX: _assert(state.Keep()); | |
5274 | continue; | |
5275 | else if (special_r(name)) | |
5276 | [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys: | |
5277 | [NSNull null], @"package", | |
5278 | [NSArray arrayWithObjects: | |
5279 | [NSDictionary dictionaryWithObjectsAndKeys: | |
5280 | @"Conflicts", @"relationship", | |
5281 | [NSArray arrayWithObjects: | |
5282 | [NSDictionary dictionaryWithObjectsAndKeys: | |
5283 | name, @"package", | |
5284 | [NSNull null], @"version", | |
5285 | @"installed", @"reason", | |
5286 | nil], | |
5287 | nil], @"clauses", | |
5288 | nil], | |
5289 | nil], @"reasons", | |
5290 | nil]]; | |
5291 | else { | |
5292 | if ([package essential]) | |
5293 | remove = true; | |
5294 | [removes addObject:name]; | |
5295 | } | |
5296 | ||
5297 | substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator)); | |
5298 | substrate_ |= DepSubstrate(iterator.CurrentVer()); | |
5299 | } | |
5300 | ||
5301 | if (!remove) | |
5302 | essential_ = nil; | |
5303 | else if (Advanced_) { | |
5304 | NSString *parenthetical(UCLocalize("PARENTHETICAL")); | |
5305 | ||
5306 | essential_ = [[[UIAlertView alloc] | |
5307 | initWithTitle:UCLocalize("REMOVING_ESSENTIALS") | |
5308 | message:UCLocalize("REMOVING_ESSENTIALS_EX") | |
5309 | delegate:self | |
5310 | cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")] | |
5311 | otherButtonTitles: | |
5312 | [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], | |
5313 | nil | |
5314 | ] autorelease]; | |
5315 | ||
5316 | [essential_ setContext:@"remove"]; | |
5317 | [essential_ setNumberOfRows:2]; | |
5318 | } else { | |
5319 | essential_ = [[[UIAlertView alloc] | |
5320 | initWithTitle:UCLocalize("UNABLE_TO_COMPLY") | |
5321 | message:UCLocalize("UNABLE_TO_COMPLY_EX") | |
5322 | delegate:self | |
5323 | cancelButtonTitle:UCLocalize("OKAY") | |
5324 | otherButtonTitles:nil | |
5325 | ] autorelease]; | |
5326 | ||
5327 | [essential_ setContext:@"unable"]; | |
5328 | } | |
5329 | ||
5330 | changes_ = [NSDictionary dictionaryWithObjectsAndKeys: | |
5331 | installs, @"installs", | |
5332 | reinstalls, @"reinstalls", | |
5333 | upgrades, @"upgrades", | |
5334 | downgrades, @"downgrades", | |
5335 | removes, @"removes", | |
5336 | nil]; | |
5337 | ||
5338 | sizes_ = [NSDictionary dictionaryWithObjectsAndKeys: | |
5339 | [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading", | |
5340 | [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming", | |
5341 | nil]; | |
5342 | ||
5343 | [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]]; | |
5344 | } return self; | |
5345 | } | |
5346 | ||
5347 | - (UIBarButtonItem *) leftButton { | |
5348 | return [[[UIBarButtonItem alloc] | |
5349 | initWithTitle:UCLocalize("CANCEL") | |
5350 | style:UIBarButtonItemStylePlain | |
5351 | target:self | |
5352 | action:@selector(cancelButtonClicked) | |
5353 | ] autorelease]; | |
5354 | } | |
5355 | ||
5356 | #if !AlwaysReload | |
5357 | - (void) applyRightButton { | |
5358 | if ([issues_ count] == 0 && ![self isLoading]) | |
5359 | [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] | |
5360 | initWithTitle:UCLocalize("CONFIRM") | |
5361 | style:UIBarButtonItemStyleDone | |
5362 | target:self | |
5363 | action:@selector(confirmButtonClicked) | |
5364 | ] autorelease]]; | |
5365 | else | |
5366 | [[self navigationItem] setRightBarButtonItem:nil]; | |
5367 | } | |
5368 | #endif | |
5369 | ||
5370 | - (void) cancelButtonClicked { | |
5371 | [delegate_ cancelAndClear:YES]; | |
5372 | [self dismissModalViewControllerAnimated:YES]; | |
5373 | } | |
5374 | ||
5375 | #if !AlwaysReload | |
5376 | - (void) confirmButtonClicked { | |
5377 | if (essential_ != nil) | |
5378 | [essential_ show]; | |
5379 | else | |
5380 | [self complete]; | |
5381 | } | |
5382 | #endif | |
5383 | ||
5384 | @end | |
5385 | /* }}} */ | |
5386 | ||
5387 | /* Progress Data {{{ */ | |
5388 | @interface CydiaProgressData : NSObject { | |
5389 | _transient id delegate_; | |
5390 | ||
5391 | bool running_; | |
5392 | float percent_; | |
5393 | ||
5394 | float current_; | |
5395 | float total_; | |
5396 | float speed_; | |
5397 | ||
5398 | _H<NSMutableArray> events_; | |
5399 | _H<NSString> title_; | |
5400 | ||
5401 | _H<NSString> status_; | |
5402 | _H<NSString> finish_; | |
5403 | } | |
5404 | ||
5405 | @end | |
5406 | ||
5407 | @implementation CydiaProgressData | |
5408 | ||
5409 | + (NSArray *) _attributeKeys { | |
5410 | return [NSArray arrayWithObjects: | |
5411 | @"current", | |
5412 | @"events", | |
5413 | @"finish", | |
5414 | @"percent", | |
5415 | @"running", | |
5416 | @"speed", | |
5417 | @"title", | |
5418 | @"total", | |
5419 | nil]; | |
5420 | } | |
5421 | ||
5422 | - (NSArray *) attributeKeys { | |
5423 | return [[self class] _attributeKeys]; | |
5424 | } | |
5425 | ||
5426 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
5427 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
5428 | } | |
5429 | ||
5430 | - (id) init { | |
5431 | if ((self = [super init]) != nil) { | |
5432 | events_ = [NSMutableArray arrayWithCapacity:32]; | |
5433 | } return self; | |
5434 | } | |
5435 | ||
5436 | - (id) delegate { | |
5437 | return delegate_; | |
5438 | } | |
5439 | ||
5440 | - (void) setDelegate:(id)delegate { | |
5441 | delegate_ = delegate; | |
5442 | } | |
5443 | ||
5444 | - (void) setPercent:(float)value { | |
5445 | percent_ = value; | |
5446 | } | |
5447 | ||
5448 | - (NSNumber *) percent { | |
5449 | return [NSNumber numberWithFloat:percent_]; | |
5450 | } | |
5451 | ||
5452 | - (void) setCurrent:(float)value { | |
5453 | current_ = value; | |
5454 | } | |
5455 | ||
5456 | - (NSNumber *) current { | |
5457 | return [NSNumber numberWithFloat:current_]; | |
5458 | } | |
5459 | ||
5460 | - (void) setTotal:(float)value { | |
5461 | total_ = value; | |
5462 | } | |
5463 | ||
5464 | - (NSNumber *) total { | |
5465 | return [NSNumber numberWithFloat:total_]; | |
5466 | } | |
5467 | ||
5468 | - (void) setSpeed:(float)value { | |
5469 | speed_ = value; | |
5470 | } | |
5471 | ||
5472 | - (NSNumber *) speed { | |
5473 | return [NSNumber numberWithFloat:speed_]; | |
5474 | } | |
5475 | ||
5476 | - (NSArray *) events { | |
5477 | return events_; | |
5478 | } | |
5479 | ||
5480 | - (void) removeAllEvents { | |
5481 | [events_ removeAllObjects]; | |
5482 | } | |
5483 | ||
5484 | - (void) addEvent:(CydiaProgressEvent *)event { | |
5485 | [events_ addObject:event]; | |
5486 | } | |
5487 | ||
5488 | - (void) setTitle:(NSString *)text { | |
5489 | title_ = text; | |
5490 | } | |
5491 | ||
5492 | - (NSString *) title { | |
5493 | return title_; | |
5494 | } | |
5495 | ||
5496 | - (void) setFinish:(NSString *)text { | |
5497 | finish_ = text; | |
5498 | } | |
5499 | ||
5500 | - (NSString *) finish { | |
5501 | return (id) finish_ ?: [NSNull null]; | |
5502 | } | |
5503 | ||
5504 | - (void) setRunning:(bool)running { | |
5505 | running_ = running; | |
5506 | } | |
5507 | ||
5508 | - (NSNumber *) running { | |
5509 | return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse; | |
5510 | } | |
5511 | ||
5512 | @end | |
5513 | /* }}} */ | |
5514 | /* Progress Controller {{{ */ | |
5515 | @interface ProgressController : CydiaWebViewController < | |
5516 | ProgressDelegate | |
5517 | > { | |
5518 | _transient Database *database_; | |
5519 | _H<CydiaProgressData, 1> progress_; | |
5520 | unsigned cancel_; | |
5521 | } | |
5522 | ||
5523 | - (id) initWithDatabase:(Database *)database delegate:(id)delegate; | |
5524 | ||
5525 | - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title; | |
5526 | ||
5527 | - (void) setTitle:(NSString *)title; | |
5528 | - (void) setCancellable:(bool)cancellable; | |
5529 | ||
5530 | @end | |
5531 | ||
5532 | @implementation ProgressController | |
5533 | ||
5534 | - (void) dealloc { | |
5535 | [database_ setProgressDelegate:nil]; | |
5536 | [super dealloc]; | |
5537 | } | |
5538 | ||
5539 | - (UIBarButtonItem *) leftButton { | |
5540 | return cancel_ == 1 ? [[[UIBarButtonItem alloc] | |
5541 | initWithTitle:UCLocalize("CANCEL") | |
5542 | style:UIBarButtonItemStylePlain | |
5543 | target:self | |
5544 | action:@selector(cancel) | |
5545 | ] autorelease] : nil; | |
5546 | } | |
5547 | ||
5548 | - (void) updateCancel { | |
5549 | [super applyLeftButton]; | |
5550 | } | |
5551 | ||
5552 | - (id) initWithDatabase:(Database *)database delegate:(id)delegate { | |
5553 | if ((self = [super init]) != nil) { | |
5554 | database_ = database; | |
5555 | delegate_ = delegate; | |
5556 | ||
5557 | [database_ setProgressDelegate:self]; | |
5558 | ||
5559 | progress_ = [[[CydiaProgressData alloc] init] autorelease]; | |
5560 | [progress_ setDelegate:self]; | |
5561 | ||
5562 | [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]]; | |
5563 | ||
5564 | [scroller_ setBackgroundColor:[UIColor blackColor]]; | |
5565 | ||
5566 | [[self navigationItem] setHidesBackButton:YES]; | |
5567 | ||
5568 | [self updateCancel]; | |
5569 | } return self; | |
5570 | } | |
5571 | ||
5572 | - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame { | |
5573 | [super webView:view didClearWindowObject:window forFrame:frame]; | |
5574 | [window setValue:progress_ forKey:@"cydiaProgress"]; | |
5575 | } | |
5576 | ||
5577 | - (void) updateProgress { | |
5578 | [self dispatchEvent:@"CydiaProgressUpdate"]; | |
5579 | } | |
5580 | ||
5581 | - (void) viewWillAppear:(BOOL)animated { | |
5582 | [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack]; | |
5583 | [super viewWillAppear:animated]; | |
5584 | } | |
5585 | ||
5586 | - (void) close { | |
5587 | UpdateExternalStatus(0); | |
5588 | ||
5589 | if (Finish_ > 1) | |
5590 | [delegate_ saveState]; | |
5591 | ||
5592 | switch (Finish_) { | |
5593 | case 0: | |
5594 | [delegate_ returnToCydia]; | |
5595 | break; | |
5596 | ||
5597 | case 1: | |
5598 | [delegate_ terminateWithSuccess]; | |
5599 | /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)]) | |
5600 | [delegate_ suspendWithAnimation:YES]; | |
5601 | else | |
5602 | [delegate_ suspend];*/ | |
5603 | break; | |
5604 | ||
5605 | case 2: | |
5606 | _trace(); | |
5607 | goto reload; | |
5608 | ||
5609 | case 3: | |
5610 | _trace(); | |
5611 | goto reload; | |
5612 | ||
5613 | reload: { | |
5614 | UIProgressHUD *hud([delegate_ addProgressHUD]); | |
5615 | [hud setText:UCLocalize("LOADING")]; | |
5616 | [delegate_ performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5]; | |
5617 | return; | |
5618 | } | |
5619 | ||
5620 | case 4: | |
5621 | _trace(); | |
5622 | if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot"))) | |
5623 | SBReboot(SBSSpringBoardServerPort()); | |
5624 | else | |
5625 | reboot2(RB_AUTOBOOT); | |
5626 | break; | |
5627 | } | |
5628 | ||
5629 | [super close]; | |
5630 | } | |
5631 | ||
5632 | - (void) setTitle:(NSString *)title { | |
5633 | [progress_ setTitle:title]; | |
5634 | [self updateProgress]; | |
5635 | } | |
5636 | ||
5637 | - (UIBarButtonItem *) rightButton { | |
5638 | return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc] | |
5639 | initWithTitle:UCLocalize("CLOSE") | |
5640 | style:UIBarButtonItemStylePlain | |
5641 | target:self | |
5642 | action:@selector(close) | |
5643 | ] autorelease]; | |
5644 | } | |
5645 | ||
5646 | - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title { | |
5647 | UpdateExternalStatus(1); | |
5648 | ||
5649 | [progress_ setRunning:true]; | |
5650 | [self setTitle:title]; | |
5651 | // implicit updateProgress | |
5652 | ||
5653 | SHA1SumValue notifyconf; { | |
5654 | FileFd file; | |
5655 | if (!file.Open(NotifyConfig_, FileFd::ReadOnly)) | |
5656 | _error->Discard(); | |
5657 | else { | |
5658 | MMap mmap(file, MMap::ReadOnly); | |
5659 | SHA1Summation sha1; | |
5660 | sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size()); | |
5661 | notifyconf = sha1.Result(); | |
5662 | } | |
5663 | } | |
5664 | ||
5665 | SHA1SumValue springlist; { | |
5666 | FileFd file; | |
5667 | if (!file.Open(SpringBoard_, FileFd::ReadOnly)) | |
5668 | _error->Discard(); | |
5669 | else { | |
5670 | MMap mmap(file, MMap::ReadOnly); | |
5671 | SHA1Summation sha1; | |
5672 | sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size()); | |
5673 | springlist = sha1.Result(); | |
5674 | } | |
5675 | } | |
5676 | ||
5677 | if (invocation != nil) { | |
5678 | [invocation yieldToSelector:@selector(invoke)]; | |
5679 | [self setTitle:@"COMPLETE"]; | |
5680 | } | |
5681 | ||
5682 | if (Finish_ < 4) { | |
5683 | FileFd file; | |
5684 | if (!file.Open(NotifyConfig_, FileFd::ReadOnly)) | |
5685 | _error->Discard(); | |
5686 | else { | |
5687 | MMap mmap(file, MMap::ReadOnly); | |
5688 | SHA1Summation sha1; | |
5689 | sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size()); | |
5690 | if (!(notifyconf == sha1.Result())) | |
5691 | Finish_ = 4; | |
5692 | } | |
5693 | } | |
5694 | ||
5695 | if (Finish_ < 3) { | |
5696 | FileFd file; | |
5697 | if (!file.Open(SpringBoard_, FileFd::ReadOnly)) | |
5698 | _error->Discard(); | |
5699 | else { | |
5700 | MMap mmap(file, MMap::ReadOnly); | |
5701 | SHA1Summation sha1; | |
5702 | sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size()); | |
5703 | if (!(springlist == sha1.Result())) | |
5704 | Finish_ = 3; | |
5705 | } | |
5706 | } | |
5707 | ||
5708 | if (Finish_ < 2) { | |
5709 | if (RestartSubstrate_) | |
5710 | Finish_ = 2; | |
5711 | } | |
5712 | ||
5713 | RestartSubstrate_ = false; | |
5714 | ||
5715 | switch (Finish_) { | |
5716 | case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */ | |
5717 | case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break; | |
5718 | case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break; | |
5719 | case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break; | |
5720 | case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break; | |
5721 | } | |
5722 | ||
5723 | UpdateExternalStatus(Finish_ == 0 ? 0 : 2); | |
5724 | ||
5725 | [progress_ setRunning:false]; | |
5726 | [self updateProgress]; | |
5727 | ||
5728 | [self applyRightButton]; | |
5729 | } | |
5730 | ||
5731 | - (void) addProgressEvent:(CydiaProgressEvent *)event { | |
5732 | [progress_ addEvent:event]; | |
5733 | [self updateProgress]; | |
5734 | } | |
5735 | ||
5736 | - (bool) isProgressCancelled { | |
5737 | return cancel_ == 2; | |
5738 | } | |
5739 | ||
5740 | - (void) cancel { | |
5741 | cancel_ = 2; | |
5742 | [self updateCancel]; | |
5743 | } | |
5744 | ||
5745 | - (void) setCancellable:(bool)cancellable { | |
5746 | unsigned cancel(cancel_); | |
5747 | ||
5748 | if (!cancellable) | |
5749 | cancel_ = 0; | |
5750 | else if (cancel_ == 0) | |
5751 | cancel_ = 1; | |
5752 | ||
5753 | if (cancel != cancel_) | |
5754 | [self updateCancel]; | |
5755 | } | |
5756 | ||
5757 | - (void) setProgressCancellable:(NSNumber *)cancellable { | |
5758 | [self setCancellable:[cancellable boolValue]]; | |
5759 | } | |
5760 | ||
5761 | - (void) setProgressPercent:(NSNumber *)percent { | |
5762 | [progress_ setPercent:[percent floatValue]]; | |
5763 | [self updateProgress]; | |
5764 | } | |
5765 | ||
5766 | - (void) setProgressStatus:(NSDictionary *)status { | |
5767 | if (status == nil) { | |
5768 | [progress_ setCurrent:0]; | |
5769 | [progress_ setTotal:0]; | |
5770 | [progress_ setSpeed:0]; | |
5771 | } else { | |
5772 | [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]]; | |
5773 | ||
5774 | [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]]; | |
5775 | [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]]; | |
5776 | [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]]; | |
5777 | } | |
5778 | ||
5779 | [self updateProgress]; | |
5780 | } | |
5781 | ||
5782 | @end | |
5783 | /* }}} */ | |
5784 | ||
5785 | /* Package Cell {{{ */ | |
5786 | @interface PackageCell : CyteTableViewCell < | |
5787 | CyteTableViewCellDelegate | |
5788 | > { | |
5789 | _H<UIImage> icon_; | |
5790 | _H<NSString> name_; | |
5791 | _H<NSString> description_; | |
5792 | bool commercial_; | |
5793 | _H<NSString> source_; | |
5794 | _H<UIImage> badge_; | |
5795 | _H<UIImage> placard_; | |
5796 | bool summarized_; | |
5797 | } | |
5798 | ||
5799 | - (PackageCell *) init; | |
5800 | - (void) setPackage:(Package *)package asSummary:(bool)summary; | |
5801 | ||
5802 | - (void) drawContentRect:(CGRect)rect; | |
5803 | ||
5804 | @end | |
5805 | ||
5806 | @implementation PackageCell | |
5807 | ||
5808 | - (PackageCell *) init { | |
5809 | CGRect frame(CGRectMake(0, 0, 320, 74)); | |
5810 | if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) { | |
5811 | UIView *content([self contentView]); | |
5812 | CGRect bounds([content bounds]); | |
5813 | ||
5814 | content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease]; | |
5815 | [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
5816 | [content addSubview:content_]; | |
5817 | ||
5818 | [content_ setDelegate:self]; | |
5819 | [content_ setOpaque:YES]; | |
5820 | } return self; | |
5821 | } | |
5822 | ||
5823 | - (NSString *) accessibilityLabel { | |
5824 | return name_; | |
5825 | } | |
5826 | ||
5827 | - (void) setPackage:(Package *)package asSummary:(bool)summary { | |
5828 | summarized_ = summary; | |
5829 | ||
5830 | icon_ = nil; | |
5831 | name_ = nil; | |
5832 | description_ = nil; | |
5833 | source_ = nil; | |
5834 | badge_ = nil; | |
5835 | placard_ = nil; | |
5836 | ||
5837 | if (package == nil) | |
5838 | [content_ setBackgroundColor:[UIColor whiteColor]]; | |
5839 | else { | |
5840 | [package parse]; | |
5841 | ||
5842 | Source *source = [package source]; | |
5843 | ||
5844 | icon_ = [package icon]; | |
5845 | ||
5846 | if (NSString *name = [package name]) | |
5847 | name_ = [NSString stringWithString:name]; | |
5848 | ||
5849 | if (NSString *description = [package shortDescription]) | |
5850 | description_ = [NSString stringWithString:description]; | |
5851 | ||
5852 | commercial_ = [package isCommercial]; | |
5853 | ||
5854 | NSString *label = nil; | |
5855 | bool trusted = false; | |
5856 | ||
5857 | if (source != nil) { | |
5858 | label = [source label]; | |
5859 | trusted = [source trusted]; | |
5860 | } else if ([[package id] isEqualToString:@"firmware"]) | |
5861 | label = UCLocalize("APPLE"); | |
5862 | else | |
5863 | label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")]; | |
5864 | ||
5865 | NSString *from(label); | |
5866 | ||
5867 | NSString *section = [package simpleSection]; | |
5868 | if (section != nil && ![section isEqualToString:label]) { | |
5869 | section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"]; | |
5870 | from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section]; | |
5871 | } | |
5872 | ||
5873 | source_ = [NSString stringWithFormat:UCLocalize("FROM"), from]; | |
5874 | ||
5875 | if (NSString *purpose = [package primaryPurpose]) | |
5876 | badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]; | |
5877 | ||
5878 | UIColor *color; | |
5879 | NSString *placard; | |
5880 | ||
5881 | if (NSString *mode = [package mode]) { | |
5882 | if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) { | |
5883 | color = RemovingColor_; | |
5884 | placard = @"removing"; | |
5885 | } else { | |
5886 | color = InstallingColor_; | |
5887 | placard = @"installing"; | |
5888 | } | |
5889 | } else { | |
5890 | color = [UIColor whiteColor]; | |
5891 | ||
5892 | if ([package installed] != nil) | |
5893 | placard = @"installed"; | |
5894 | else | |
5895 | placard = nil; | |
5896 | } | |
5897 | ||
5898 | [content_ setBackgroundColor:color]; | |
5899 | ||
5900 | if (placard != nil) | |
5901 | placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]; | |
5902 | } | |
5903 | ||
5904 | [self setNeedsDisplay]; | |
5905 | [content_ setNeedsDisplay]; | |
5906 | } | |
5907 | ||
5908 | - (void) drawSummaryContentRect:(CGRect)rect { | |
5909 | bool highlighted(highlighted_); | |
5910 | float width([self bounds].size.width); | |
5911 | ||
5912 | if (icon_ != nil) { | |
5913 | CGRect rect; | |
5914 | rect.size = [(UIImage *) icon_ size]; | |
5915 | ||
5916 | while (rect.size.width > 16 || rect.size.height > 16) { | |
5917 | rect.size.width /= 2; | |
5918 | rect.size.height /= 2; | |
5919 | } | |
5920 | ||
5921 | rect.origin.x = 19 - rect.size.width / 2; | |
5922 | rect.origin.y = 19 - rect.size.height / 2; | |
5923 | ||
5924 | [icon_ drawInRect:Retina(rect)]; | |
5925 | } | |
5926 | ||
5927 | if (badge_ != nil) { | |
5928 | CGRect rect; | |
5929 | rect.size = [(UIImage *) badge_ size]; | |
5930 | ||
5931 | rect.size.width /= 4; | |
5932 | rect.size.height /= 4; | |
5933 | ||
5934 | rect.origin.x = 25 - rect.size.width / 2; | |
5935 | rect.origin.y = 25 - rect.size.height / 2; | |
5936 | ||
5937 | [badge_ drawInRect:Retina(rect)]; | |
5938 | } | |
5939 | ||
5940 | if (highlighted && kCFCoreFoundationVersionNumber < 800) | |
5941 | UISetColor(White_); | |
5942 | ||
5943 | if (!highlighted) | |
5944 | UISetColor(commercial_ ? Purple_ : Black_); | |
5945 | [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
5946 | ||
5947 | if (placard_ != nil) | |
5948 | [placard_ drawAtPoint:CGPointMake(width - 52, 11)]; | |
5949 | } | |
5950 | ||
5951 | - (void) drawNormalContentRect:(CGRect)rect { | |
5952 | bool highlighted(highlighted_); | |
5953 | float width([self bounds].size.width); | |
5954 | ||
5955 | if (icon_ != nil) { | |
5956 | CGRect rect; | |
5957 | rect.size = [(UIImage *) icon_ size]; | |
5958 | ||
5959 | while (rect.size.width > 32 || rect.size.height > 32) { | |
5960 | rect.size.width /= 2; | |
5961 | rect.size.height /= 2; | |
5962 | } | |
5963 | ||
5964 | rect.origin.x = 25 - rect.size.width / 2; | |
5965 | rect.origin.y = 25 - rect.size.height / 2; | |
5966 | ||
5967 | [icon_ drawInRect:Retina(rect)]; | |
5968 | } | |
5969 | ||
5970 | if (badge_ != nil) { | |
5971 | CGRect rect; | |
5972 | rect.size = [(UIImage *) badge_ size]; | |
5973 | ||
5974 | rect.size.width /= 2; | |
5975 | rect.size.height /= 2; | |
5976 | ||
5977 | rect.origin.x = 36 - rect.size.width / 2; | |
5978 | rect.origin.y = 36 - rect.size.height / 2; | |
5979 | ||
5980 | [badge_ drawInRect:Retina(rect)]; | |
5981 | } | |
5982 | ||
5983 | if (highlighted && kCFCoreFoundationVersionNumber < 800) | |
5984 | UISetColor(White_); | |
5985 | ||
5986 | if (!highlighted) | |
5987 | UISetColor(commercial_ ? Purple_ : Black_); | |
5988 | [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
5989 | [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
5990 | ||
5991 | if (!highlighted) | |
5992 | UISetColor(commercial_ ? Purplish_ : Gray_); | |
5993 | [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
5994 | ||
5995 | if (placard_ != nil) | |
5996 | [placard_ drawAtPoint:CGPointMake(width - 52, 9)]; | |
5997 | } | |
5998 | ||
5999 | - (void) drawContentRect:(CGRect)rect { | |
6000 | if (summarized_) | |
6001 | [self drawSummaryContentRect:rect]; | |
6002 | else | |
6003 | [self drawNormalContentRect:rect]; | |
6004 | } | |
6005 | ||
6006 | @end | |
6007 | /* }}} */ | |
6008 | /* Section Cell {{{ */ | |
6009 | @interface SectionCell : CyteTableViewCell < | |
6010 | CyteTableViewCellDelegate | |
6011 | > { | |
6012 | _H<NSString> basic_; | |
6013 | _H<NSString> section_; | |
6014 | _H<NSString> name_; | |
6015 | _H<NSString> count_; | |
6016 | _H<UIImage> icon_; | |
6017 | _H<UISwitch> switch_; | |
6018 | BOOL editing_; | |
6019 | } | |
6020 | ||
6021 | - (void) setSection:(Section *)section editing:(BOOL)editing; | |
6022 | ||
6023 | @end | |
6024 | ||
6025 | @implementation SectionCell | |
6026 | ||
6027 | - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier { | |
6028 | if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) { | |
6029 | icon_ = [UIImage imageNamed:@"folder.png"]; | |
6030 | // XXX: this initial frame is wrong, but is fixed later | |
6031 | switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease]; | |
6032 | [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged]; | |
6033 | ||
6034 | UIView *content([self contentView]); | |
6035 | CGRect bounds([content bounds]); | |
6036 | ||
6037 | content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease]; | |
6038 | [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
6039 | [content addSubview:content_]; | |
6040 | [content_ setBackgroundColor:[UIColor whiteColor]]; | |
6041 | ||
6042 | [content_ setDelegate:self]; | |
6043 | } return self; | |
6044 | } | |
6045 | ||
6046 | - (void) onSwitch:(id)sender { | |
6047 | NSMutableDictionary *metadata([Sections_ objectForKey:basic_]); | |
6048 | if (metadata == nil) { | |
6049 | metadata = [NSMutableDictionary dictionaryWithCapacity:2]; | |
6050 | [Sections_ setObject:metadata forKey:basic_]; | |
6051 | } | |
6052 | ||
6053 | [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"]; | |
6054 | } | |
6055 | ||
6056 | - (void) setSection:(Section *)section editing:(BOOL)editing { | |
6057 | if (editing != editing_) { | |
6058 | if (editing_) | |
6059 | [switch_ removeFromSuperview]; | |
6060 | else | |
6061 | [self addSubview:switch_]; | |
6062 | editing_ = editing; | |
6063 | } | |
6064 | ||
6065 | basic_ = nil; | |
6066 | section_ = nil; | |
6067 | name_ = nil; | |
6068 | count_ = nil; | |
6069 | ||
6070 | if (section == nil) { | |
6071 | name_ = UCLocalize("ALL_PACKAGES"); | |
6072 | count_ = nil; | |
6073 | } else { | |
6074 | basic_ = [section name]; | |
6075 | section_ = [section localized]; | |
6076 | ||
6077 | name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_; | |
6078 | count_ = [NSString stringWithFormat:@"%zd", [section count]]; | |
6079 | ||
6080 | if (editing_) | |
6081 | [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO]; | |
6082 | } | |
6083 | ||
6084 | [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator]; | |
6085 | [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue]; | |
6086 | ||
6087 | [content_ setNeedsDisplay]; | |
6088 | } | |
6089 | ||
6090 | - (void) setFrame:(CGRect)frame { | |
6091 | [super setFrame:frame]; | |
6092 | ||
6093 | CGRect rect([switch_ frame]); | |
6094 | [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)]; | |
6095 | } | |
6096 | ||
6097 | - (NSString *) accessibilityLabel { | |
6098 | return name_; | |
6099 | } | |
6100 | ||
6101 | - (void) drawContentRect:(CGRect)rect { | |
6102 | bool highlighted(highlighted_ && !editing_); | |
6103 | ||
6104 | [icon_ drawInRect:CGRectMake(7, 7, 32, 32)]; | |
6105 | ||
6106 | if (highlighted && kCFCoreFoundationVersionNumber < 800) | |
6107 | UISetColor(White_); | |
6108 | ||
6109 | float width(rect.size.width); | |
6110 | if (editing_) | |
6111 | width -= 9 + [switch_ frame].size.width; | |
6112 | ||
6113 | if (!highlighted) | |
6114 | UISetColor(Black_); | |
6115 | [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
6116 | ||
6117 | CGSize size = [count_ sizeWithFont:Font14_]; | |
6118 | ||
6119 | UISetColor(Folder_); | |
6120 | if (count_ != nil) | |
6121 | [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_]; | |
6122 | } | |
6123 | ||
6124 | @end | |
6125 | /* }}} */ | |
6126 | ||
6127 | /* File Table {{{ */ | |
6128 | @interface FileTable : CyteViewController < | |
6129 | UITableViewDataSource, | |
6130 | UITableViewDelegate | |
6131 | > { | |
6132 | _transient Database *database_; | |
6133 | _H<Package> package_; | |
6134 | _H<NSString> name_; | |
6135 | _H<NSMutableArray> files_; | |
6136 | _H<UITableView, 2> list_; | |
6137 | } | |
6138 | ||
6139 | - (id) initWithDatabase:(Database *)database; | |
6140 | - (void) setPackage:(Package *)package; | |
6141 | ||
6142 | @end | |
6143 | ||
6144 | @implementation FileTable | |
6145 | ||
6146 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
6147 | return files_ == nil ? 0 : [files_ count]; | |
6148 | } | |
6149 | ||
6150 | /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { | |
6151 | return 24.0f; | |
6152 | }*/ | |
6153 | ||
6154 | - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
6155 | static NSString *reuseIdentifier = @"Cell"; | |
6156 | ||
6157 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; | |
6158 | if (cell == nil) { | |
6159 | cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease]; | |
6160 | [cell setFont:[UIFont systemFontOfSize:16]]; | |
6161 | } | |
6162 | [cell setText:[files_ objectAtIndex:indexPath.row]]; | |
6163 | [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; | |
6164 | ||
6165 | return cell; | |
6166 | } | |
6167 | ||
6168 | - (NSURL *) navigationURL { | |
6169 | return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]]; | |
6170 | } | |
6171 | ||
6172 | - (void) loadView { | |
6173 | list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]; | |
6174 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
6175 | [list_ setRowHeight:24.0f]; | |
6176 | [(UITableView *) list_ setDataSource:self]; | |
6177 | [list_ setDelegate:self]; | |
6178 | [self setView:list_]; | |
6179 | } | |
6180 | ||
6181 | - (void) viewDidLoad { | |
6182 | [super viewDidLoad]; | |
6183 | ||
6184 | [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")]; | |
6185 | } | |
6186 | ||
6187 | - (void) releaseSubviews { | |
6188 | list_ = nil; | |
6189 | ||
6190 | package_ = nil; | |
6191 | files_ = nil; | |
6192 | ||
6193 | [super releaseSubviews]; | |
6194 | } | |
6195 | ||
6196 | - (id) initWithDatabase:(Database *)database { | |
6197 | if ((self = [super init]) != nil) { | |
6198 | database_ = database; | |
6199 | } return self; | |
6200 | } | |
6201 | ||
6202 | - (void) setPackage:(Package *)package { | |
6203 | package_ = nil; | |
6204 | name_ = nil; | |
6205 | ||
6206 | files_ = [NSMutableArray arrayWithCapacity:32]; | |
6207 | ||
6208 | if (package != nil) { | |
6209 | package_ = package; | |
6210 | name_ = [package id]; | |
6211 | ||
6212 | if (NSArray *files = [package files]) | |
6213 | [files_ addObjectsFromArray:files]; | |
6214 | ||
6215 | if ([files_ count] != 0) { | |
6216 | if ([[files_ objectAtIndex:0] isEqualToString:@"/."]) | |
6217 | [files_ removeObjectAtIndex:0]; | |
6218 | [files_ sortUsingSelector:@selector(compareByPath:)]; | |
6219 | ||
6220 | NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8]; | |
6221 | [stack addObject:@"/"]; | |
6222 | ||
6223 | for (int i(0), e([files_ count]); i != e; ++i) { | |
6224 | NSString *file = [files_ objectAtIndex:i]; | |
6225 | while (![file hasPrefix:[stack lastObject]]) | |
6226 | [stack removeLastObject]; | |
6227 | NSString *directory = [stack lastObject]; | |
6228 | [stack addObject:[file stringByAppendingString:@"/"]]; | |
6229 | [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@", | |
6230 | ([stack count] - 2) * 3, "", | |
6231 | [file substringFromIndex:[directory length]] | |
6232 | ]]; | |
6233 | } | |
6234 | } | |
6235 | } | |
6236 | ||
6237 | [list_ reloadData]; | |
6238 | } | |
6239 | ||
6240 | - (void) reloadData { | |
6241 | [super reloadData]; | |
6242 | ||
6243 | [self setPackage:[database_ packageWithName:name_]]; | |
6244 | } | |
6245 | ||
6246 | @end | |
6247 | /* }}} */ | |
6248 | /* Package Controller {{{ */ | |
6249 | @interface CYPackageController : CydiaWebViewController < | |
6250 | UIActionSheetDelegate | |
6251 | > { | |
6252 | _transient Database *database_; | |
6253 | _H<Package> package_; | |
6254 | _H<NSString> name_; | |
6255 | bool commercial_; | |
6256 | std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_; | |
6257 | _H<UIBarButtonItem> button_; | |
6258 | } | |
6259 | ||
6260 | - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer; | |
6261 | ||
6262 | @end | |
6263 | ||
6264 | @implementation CYPackageController | |
6265 | ||
6266 | - (NSURL *) navigationURL { | |
6267 | return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]]; | |
6268 | } | |
6269 | ||
6270 | - (void) _clickButtonWithName:(NSString *)name { | |
6271 | if ([name isEqualToString:@"CLEAR"]) | |
6272 | [delegate_ clearPackage:package_]; | |
6273 | else if ([name isEqualToString:@"INSTALL"]) | |
6274 | [delegate_ installPackage:package_]; | |
6275 | else if ([name isEqualToString:@"REINSTALL"]) | |
6276 | [delegate_ installPackage:package_]; | |
6277 | else if ([name isEqualToString:@"REMOVE"]) | |
6278 | [delegate_ removePackage:package_]; | |
6279 | else if ([name isEqualToString:@"UPGRADE"]) | |
6280 | [delegate_ installPackage:package_]; | |
6281 | else _assert(false); | |
6282 | } | |
6283 | ||
6284 | - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button { | |
6285 | NSString *context([sheet context]); | |
6286 | ||
6287 | if ([context isEqualToString:@"modify"]) { | |
6288 | if (button != [sheet cancelButtonIndex]) { | |
6289 | if (IsWildcat_) | |
6290 | [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0]; | |
6291 | else | |
6292 | [self _clickButtonWithName:buttons_[button].first]; | |
6293 | } | |
6294 | ||
6295 | [sheet dismissWithClickedButtonIndex:button animated:YES]; | |
6296 | } | |
6297 | } | |
6298 | ||
6299 | - (bool) _allowJavaScriptPanel { | |
6300 | return commercial_; | |
6301 | } | |
6302 | ||
6303 | #if !AlwaysReload | |
6304 | - (void) _customButtonClicked { | |
6305 | size_t count(buttons_.size()); | |
6306 | if (count == 0) | |
6307 | return; | |
6308 | ||
6309 | if (count == 1) | |
6310 | [self _clickButtonWithName:buttons_[0].first]; | |
6311 | else { | |
6312 | NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count]; | |
6313 | for (const auto &button : buttons_) | |
6314 | [buttons addObject:button.second]; | |
6315 | ||
6316 | UIActionSheet *sheet = [[[UIActionSheet alloc] | |
6317 | initWithTitle:nil | |
6318 | delegate:self | |
6319 | cancelButtonTitle:nil | |
6320 | destructiveButtonTitle:nil | |
6321 | otherButtonTitles:nil | |
6322 | ] autorelease]; | |
6323 | ||
6324 | for (NSString *button in buttons) [sheet addButtonWithTitle:button]; | |
6325 | if (!IsWildcat_) { | |
6326 | [sheet addButtonWithTitle:UCLocalize("CANCEL")]; | |
6327 | [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1]; | |
6328 | } | |
6329 | [sheet setContext:@"modify"]; | |
6330 | ||
6331 | [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]]; | |
6332 | } | |
6333 | } | |
6334 | ||
6335 | - (void) reloadButtonClicked { | |
6336 | if (commercial_ && function_ == nil && [package_ uninstalled]) | |
6337 | return; | |
6338 | [self customButtonClicked]; | |
6339 | } | |
6340 | ||
6341 | - (void) applyLoadingTitle { | |
6342 | // Don't show "Loading" as the title. Ever. | |
6343 | } | |
6344 | ||
6345 | - (UIBarButtonItem *) rightButton { | |
6346 | return button_; | |
6347 | } | |
6348 | #endif | |
6349 | ||
6350 | - (void) setPageColor:(UIColor *)color { | |
6351 | return [super setPageColor:nil]; | |
6352 | } | |
6353 | ||
6354 | - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer { | |
6355 | if ((self = [super init]) != nil) { | |
6356 | database_ = database; | |
6357 | name_ = name == nil ? @"" : [NSString stringWithString:name]; | |
6358 | [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer]; | |
6359 | } return self; | |
6360 | } | |
6361 | ||
6362 | - (void) reloadData { | |
6363 | [super reloadData]; | |
6364 | ||
6365 | package_ = [database_ packageWithName:name_]; | |
6366 | ||
6367 | buttons_.clear(); | |
6368 | ||
6369 | if (package_ != nil) { | |
6370 | [(Package *) package_ parse]; | |
6371 | ||
6372 | commercial_ = [package_ isCommercial]; | |
6373 | ||
6374 | if ([package_ mode] != nil) | |
6375 | buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR"))); | |
6376 | if ([package_ source] == nil); | |
6377 | else if ([package_ upgradableAndEssential:NO]) | |
6378 | buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE"))); | |
6379 | else if ([package_ uninstalled]) | |
6380 | buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL"))); | |
6381 | else | |
6382 | buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL"))); | |
6383 | if (![package_ uninstalled]) | |
6384 | buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE"))); | |
6385 | } | |
6386 | ||
6387 | NSString *title; | |
6388 | switch (buttons_.size()) { | |
6389 | case 0: title = nil; break; | |
6390 | case 1: title = buttons_[0].second; break; | |
6391 | default: title = UCLocalize("MODIFY"); break; | |
6392 | } | |
6393 | ||
6394 | button_ = [[[UIBarButtonItem alloc] | |
6395 | initWithTitle:title | |
6396 | style:UIBarButtonItemStylePlain | |
6397 | target:self | |
6398 | action:@selector(customButtonClicked) | |
6399 | ] autorelease]; | |
6400 | } | |
6401 | ||
6402 | - (bool) isLoading { | |
6403 | return commercial_ ? [super isLoading] : false; | |
6404 | } | |
6405 | ||
6406 | @end | |
6407 | /* }}} */ | |
6408 | ||
6409 | /* Package List Controller {{{ */ | |
6410 | @interface PackageListController : CyteViewController < | |
6411 | UITableViewDataSource, | |
6412 | UITableViewDelegate | |
6413 | > { | |
6414 | _transient Database *database_; | |
6415 | unsigned era_; | |
6416 | _H<NSArray> packages_; | |
6417 | _H<NSArray> sections_; | |
6418 | _H<UITableView, 2> list_; | |
6419 | ||
6420 | _H<NSArray> thumbs_; | |
6421 | std::vector<NSInteger> offset_; | |
6422 | ||
6423 | _H<NSString> title_; | |
6424 | unsigned reloading_; | |
6425 | } | |
6426 | ||
6427 | - (id) initWithDatabase:(Database *)database title:(NSString *)title; | |
6428 | - (void) setDelegate:(id)delegate; | |
6429 | - (void) resetCursor; | |
6430 | - (void) clearData; | |
6431 | ||
6432 | - (NSArray *) sectionsForPackages:(NSMutableArray *)packages; | |
6433 | ||
6434 | @end | |
6435 | ||
6436 | @implementation PackageListController | |
6437 | ||
6438 | - (NSURL *) referrerURL { | |
6439 | return [self navigationURL]; | |
6440 | } | |
6441 | ||
6442 | - (bool) isSummarized { | |
6443 | return false; | |
6444 | } | |
6445 | ||
6446 | - (bool) showsSections { | |
6447 | return true; | |
6448 | } | |
6449 | ||
6450 | - (void) deselectWithAnimation:(BOOL)animated { | |
6451 | [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; | |
6452 | } | |
6453 | ||
6454 | - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve { | |
6455 | CGRect base = [[self view] bounds]; | |
6456 | base.size.height -= bounds.size.height; | |
6457 | base.origin = [list_ frame].origin; | |
6458 | ||
6459 | [UIView beginAnimations:nil context:NULL]; | |
6460 | [UIView setAnimationBeginsFromCurrentState:YES]; | |
6461 | [UIView setAnimationCurve:curve]; | |
6462 | [UIView setAnimationDuration:duration]; | |
6463 | [list_ setFrame:base]; | |
6464 | [UIView commitAnimations]; | |
6465 | } | |
6466 | ||
6467 | - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration { | |
6468 | [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear]; | |
6469 | } | |
6470 | ||
6471 | - (void) resizeForKeyboardBounds:(CGRect)bounds { | |
6472 | [self resizeForKeyboardBounds:bounds duration:0]; | |
6473 | } | |
6474 | ||
6475 | - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification { | |
6476 | if (&UIKeyboardAnimationCurveUserInfoKey == NULL) | |
6477 | *curve = UIViewAnimationCurveEaseInOut; | |
6478 | else | |
6479 | [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve]; | |
6480 | ||
6481 | if (&UIKeyboardAnimationDurationUserInfoKey == NULL) | |
6482 | *duration = 0.3; | |
6483 | else | |
6484 | [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration]; | |
6485 | } | |
6486 | ||
6487 | - (void) keyboardWillShow:(NSNotification *)notification { | |
6488 | CGRect bounds; | |
6489 | CGPoint center; | |
6490 | [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds]; | |
6491 | [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er]; | |
6492 | ||
6493 | NSTimeInterval duration; | |
6494 | UIViewAnimationCurve curve; | |
6495 | [self getKeyboardCurve:&curve duration:&duration forNotification:notification]; | |
6496 | ||
6497 | CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height); | |
6498 | UIViewController *base = self; | |
6499 | while ([base parentOrPresentingViewController] != nil) | |
6500 | base = [base parentOrPresentingViewController]; | |
6501 | CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]]; | |
6502 | CGRect intersection = CGRectIntersection(viewframe, kbframe); | |
6503 | ||
6504 | if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4) | |
6505 | intersection.size.height += CYStatusBarHeight(); | |
6506 | ||
6507 | [self resizeForKeyboardBounds:intersection duration:duration curve:curve]; | |
6508 | } | |
6509 | ||
6510 | - (void) keyboardWillHide:(NSNotification *)notification { | |
6511 | NSTimeInterval duration; | |
6512 | UIViewAnimationCurve curve; | |
6513 | [self getKeyboardCurve:&curve duration:&duration forNotification:notification]; | |
6514 | ||
6515 | [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve]; | |
6516 | } | |
6517 | ||
6518 | - (void) viewWillAppear:(BOOL)animated { | |
6519 | [super viewWillAppear:animated]; | |
6520 | ||
6521 | [self resizeForKeyboardBounds:CGRectZero]; | |
6522 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; | |
6523 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; | |
6524 | } | |
6525 | ||
6526 | - (void) viewWillDisappear:(BOOL)animated { | |
6527 | [super viewWillDisappear:animated]; | |
6528 | ||
6529 | [self resizeForKeyboardBounds:CGRectZero]; | |
6530 | [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; | |
6531 | [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; | |
6532 | } | |
6533 | ||
6534 | - (void) viewDidAppear:(BOOL)animated { | |
6535 | [super viewDidAppear:animated]; | |
6536 | [self deselectWithAnimation:animated]; | |
6537 | } | |
6538 | ||
6539 | - (void) didSelectPackage:(Package *)package { | |
6540 | CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]); | |
6541 | [view setDelegate:delegate_]; | |
6542 | [[self navigationController] pushViewController:view animated:YES]; | |
6543 | } | |
6544 | ||
6545 | - (NSInteger) numberOfSectionsInTableView:(UITableView *)list { | |
6546 | NSInteger count([sections_ count]); | |
6547 | return count == 0 ? 1 : count; | |
6548 | } | |
6549 | ||
6550 | - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section { | |
6551 | if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0) | |
6552 | return nil; | |
6553 | return [[sections_ objectAtIndex:section] name]; | |
6554 | } | |
6555 | ||
6556 | - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section { | |
6557 | if ([sections_ count] == 0) | |
6558 | return 0; | |
6559 | return [[sections_ objectAtIndex:section] count]; | |
6560 | } | |
6561 | ||
6562 | - (Package *) packageAtIndexPath:(NSIndexPath *)path { | |
6563 | @synchronized (database_) { | |
6564 | if ([database_ era] != era_) | |
6565 | return nil; | |
6566 | ||
6567 | Section *section([sections_ objectAtIndex:[path section]]); | |
6568 | NSInteger row([path row]); | |
6569 | Package *package([packages_ objectAtIndex:([section row] + row)]); | |
6570 | return [[package retain] autorelease]; | |
6571 | } } | |
6572 | ||
6573 | - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path { | |
6574 | PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]); | |
6575 | if (cell == nil) | |
6576 | cell = [[[PackageCell alloc] init] autorelease]; | |
6577 | ||
6578 | Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]); | |
6579 | [cell setPackage:package asSummary:[self isSummarized]]; | |
6580 | return cell; | |
6581 | } | |
6582 | ||
6583 | - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path { | |
6584 | Package *package([self packageAtIndexPath:path]); | |
6585 | package = [database_ packageWithName:[package id]]; | |
6586 | [self didSelectPackage:package]; | |
6587 | } | |
6588 | ||
6589 | - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView { | |
6590 | return thumbs_; | |
6591 | } | |
6592 | ||
6593 | - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { | |
6594 | return offset_[index]; | |
6595 | } | |
6596 | ||
6597 | - (void) updateHeight { | |
6598 | [list_ setRowHeight:([self isSummarized] ? 38 : 73)]; | |
6599 | } | |
6600 | ||
6601 | - (id) initWithDatabase:(Database *)database title:(NSString *)title { | |
6602 | if ((self = [super init]) != nil) { | |
6603 | database_ = database; | |
6604 | title_ = [title copy]; | |
6605 | [[self navigationItem] setTitle:title_]; | |
6606 | } return self; | |
6607 | } | |
6608 | ||
6609 | - (void) loadView { | |
6610 | UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]); | |
6611 | [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)]; | |
6612 | [self setView:view]; | |
6613 | ||
6614 | list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease]; | |
6615 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
6616 | [view addSubview:list_]; | |
6617 | ||
6618 | // XXX: is 20 the most optimal number here? | |
6619 | [list_ setSectionIndexMinimumDisplayRowCount:20]; | |
6620 | ||
6621 | [(UITableView *) list_ setDataSource:self]; | |
6622 | [list_ setDelegate:self]; | |
6623 | ||
6624 | [self updateHeight]; | |
6625 | } | |
6626 | ||
6627 | - (void) releaseSubviews { | |
6628 | list_ = nil; | |
6629 | ||
6630 | packages_ = nil; | |
6631 | sections_ = nil; | |
6632 | ||
6633 | thumbs_ = nil; | |
6634 | offset_.clear(); | |
6635 | ||
6636 | [super releaseSubviews]; | |
6637 | } | |
6638 | ||
6639 | - (void) setDelegate:(id)delegate { | |
6640 | delegate_ = delegate; | |
6641 | } | |
6642 | ||
6643 | - (bool) shouldYield { | |
6644 | return false; | |
6645 | } | |
6646 | ||
6647 | - (bool) shouldBlock { | |
6648 | return false; | |
6649 | } | |
6650 | ||
6651 | - (NSMutableArray *) _reloadPackages { | |
6652 | @synchronized (database_) { | |
6653 | era_ = [database_ era]; | |
6654 | NSArray *packages([database_ packages]); | |
6655 | ||
6656 | return [NSMutableArray arrayWithArray:packages]; | |
6657 | } } | |
6658 | ||
6659 | - (void) _reloadData { | |
6660 | if (reloading_ != 0) { | |
6661 | reloading_ = 2; | |
6662 | return; | |
6663 | } | |
6664 | ||
6665 | NSMutableArray *packages; | |
6666 | ||
6667 | reload: | |
6668 | if ([self shouldYield]) { | |
6669 | do { | |
6670 | UIProgressHUD *hud; | |
6671 | ||
6672 | if (![self shouldBlock]) | |
6673 | hud = nil; | |
6674 | else { | |
6675 | hud = [delegate_ addProgressHUD]; | |
6676 | [hud setText:UCLocalize("LOADING")]; | |
6677 | } | |
6678 | ||
6679 | reloading_ = 1; | |
6680 | packages = [self yieldToSelector:@selector(_reloadPackages)]; | |
6681 | ||
6682 | if (hud != nil) | |
6683 | [delegate_ removeProgressHUD:hud]; | |
6684 | } while (reloading_ == 2); | |
6685 | } else { | |
6686 | packages = [self _reloadPackages]; | |
6687 | } | |
6688 | ||
6689 | @synchronized (database_) { | |
6690 | if (era_ != [database_ era]) | |
6691 | goto reload; | |
6692 | reloading_ = 0; | |
6693 | ||
6694 | thumbs_ = nil; | |
6695 | offset_.clear(); | |
6696 | ||
6697 | packages_ = packages; | |
6698 | ||
6699 | if ([self showsSections]) | |
6700 | sections_ = [self sectionsForPackages:packages]; | |
6701 | else { | |
6702 | Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]); | |
6703 | [section setCount:[packages_ count]]; | |
6704 | sections_ = [NSArray arrayWithObject:section]; | |
6705 | } | |
6706 | ||
6707 | [self updateHeight]; | |
6708 | ||
6709 | _profile(PackageTable$reloadData$List) | |
6710 | [(UITableView *) list_ setDataSource:self]; | |
6711 | [list_ reloadData]; | |
6712 | _end | |
6713 | } | |
6714 | ||
6715 | PrintTimes(); | |
6716 | } | |
6717 | ||
6718 | - (NSArray *) sectionsForPackages:(NSMutableArray *)packages { | |
6719 | Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]); | |
6720 | size_t end([packages count]); | |
6721 | ||
6722 | NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]); | |
6723 | Section *section(prefix); | |
6724 | ||
6725 | thumbs_ = CollationThumbs_; | |
6726 | offset_ = CollationOffset_; | |
6727 | ||
6728 | size_t offset(0); | |
6729 | size_t offsets([CollationStarts_ count]); | |
6730 | ||
6731 | NSString *start([CollationStarts_ objectAtIndex:offset]); | |
6732 | size_t length([start length]); | |
6733 | ||
6734 | for (size_t index(0); index != end; ++index) { | |
6735 | if (start != nil) { | |
6736 | Package *package([packages objectAtIndex:index]); | |
6737 | NSString *name(PackageName(package, @selector(cyname))); | |
6738 | ||
6739 | //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) { | |
6740 | while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) { | |
6741 | NSString *title([CollationTitles_ objectAtIndex:offset]); | |
6742 | section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease]; | |
6743 | [sections addObject:section]; | |
6744 | ||
6745 | start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset]; | |
6746 | if (start == nil) | |
6747 | break; | |
6748 | length = [start length]; | |
6749 | } | |
6750 | } | |
6751 | ||
6752 | [section addToCount]; | |
6753 | } | |
6754 | ||
6755 | for (; offset != offsets; ++offset) { | |
6756 | NSString *title([CollationTitles_ objectAtIndex:offset]); | |
6757 | Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]); | |
6758 | [sections addObject:section]; | |
6759 | } | |
6760 | ||
6761 | if ([prefix count] != 0) { | |
6762 | Section *suffix([sections lastObject]); | |
6763 | [prefix setName:[suffix name]]; | |
6764 | [suffix setName:nil]; | |
6765 | [sections insertObject:prefix atIndex:(offsets - 1)]; | |
6766 | } | |
6767 | ||
6768 | return sections; | |
6769 | } | |
6770 | ||
6771 | - (void) reloadData { | |
6772 | [super reloadData]; | |
6773 | ||
6774 | if ([self shouldYield]) | |
6775 | [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0]; | |
6776 | else | |
6777 | [self _reloadData]; | |
6778 | } | |
6779 | ||
6780 | - (void) resetCursor { | |
6781 | [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO]; | |
6782 | } | |
6783 | ||
6784 | - (void) clearData { | |
6785 | [self updateHeight]; | |
6786 | ||
6787 | [list_ setDataSource:nil]; | |
6788 | [list_ reloadData]; | |
6789 | ||
6790 | [self resetCursor]; | |
6791 | } | |
6792 | ||
6793 | @end | |
6794 | /* }}} */ | |
6795 | /* Filtered Package List Controller {{{ */ | |
6796 | typedef Function<bool, Package *> PackageFilter; | |
6797 | typedef Function<void, NSMutableArray *> PackageSorter; | |
6798 | @interface FilteredPackageListController : PackageListController { | |
6799 | PackageFilter filter_; | |
6800 | PackageSorter sorter_; | |
6801 | } | |
6802 | ||
6803 | - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter; | |
6804 | ||
6805 | - (void) setFilter:(PackageFilter)filter; | |
6806 | - (void) setSorter:(PackageSorter)sorter; | |
6807 | ||
6808 | @end | |
6809 | ||
6810 | @implementation FilteredPackageListController | |
6811 | ||
6812 | - (void) setFilter:(PackageFilter)filter { | |
6813 | @synchronized (self) { | |
6814 | filter_ = filter; | |
6815 | } } | |
6816 | ||
6817 | - (void) setSorter:(PackageSorter)sorter { | |
6818 | @synchronized (self) { | |
6819 | sorter_ = sorter; | |
6820 | } } | |
6821 | ||
6822 | - (NSMutableArray *) _reloadPackages { | |
6823 | @synchronized (database_) { | |
6824 | era_ = [database_ era]; | |
6825 | ||
6826 | NSArray *packages([database_ packages]); | |
6827 | NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]); | |
6828 | ||
6829 | PackageFilter filter; | |
6830 | PackageSorter sorter; | |
6831 | ||
6832 | @synchronized (self) { | |
6833 | filter = filter_; | |
6834 | sorter = sorter_; | |
6835 | } | |
6836 | ||
6837 | _profile(PackageTable$reloadData$Filter) | |
6838 | for (Package *package in packages) | |
6839 | if ([package valid] && filter(package)) | |
6840 | [filtered addObject:package]; | |
6841 | _end | |
6842 | ||
6843 | if (sorter) | |
6844 | sorter(filtered); | |
6845 | return filtered; | |
6846 | } } | |
6847 | ||
6848 | - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter { | |
6849 | if ((self = [super initWithDatabase:database title:title]) != nil) { | |
6850 | [self setFilter:filter]; | |
6851 | } return self; | |
6852 | } | |
6853 | ||
6854 | @end | |
6855 | /* }}} */ | |
6856 | ||
6857 | /* Home Controller {{{ */ | |
6858 | @interface HomeController : CydiaWebViewController { | |
6859 | CFRunLoopRef runloop_; | |
6860 | SCNetworkReachabilityRef reachability_; | |
6861 | } | |
6862 | ||
6863 | @end | |
6864 | ||
6865 | @implementation HomeController | |
6866 | ||
6867 | static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) { | |
6868 | [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"]; | |
6869 | } | |
6870 | ||
6871 | - (id) init { | |
6872 | if ((self = [super init]) != nil) { | |
6873 | [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]]; | |
6874 | [self reloadData]; | |
6875 | ||
6876 | reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com"); | |
6877 | if (reachability_ != NULL) { | |
6878 | SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL}; | |
6879 | SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context); | |
6880 | ||
6881 | CFRunLoopRef runloop(CFRunLoopGetCurrent()); | |
6882 | if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode)) | |
6883 | runloop_ = runloop; | |
6884 | } | |
6885 | } return self; | |
6886 | } | |
6887 | ||
6888 | - (void) dealloc { | |
6889 | if (reachability_ != NULL && runloop_ != NULL) | |
6890 | SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode); | |
6891 | [super dealloc]; | |
6892 | } | |
6893 | ||
6894 | - (NSURL *) navigationURL { | |
6895 | return [NSURL URLWithString:@"cydia://home"]; | |
6896 | } | |
6897 | ||
6898 | - (void) aboutButtonClicked { | |
6899 | UIAlertView *alert([[[UIAlertView alloc] init] autorelease]); | |
6900 | ||
6901 | [alert setTitle:UCLocalize("ABOUT_CYDIA")]; | |
6902 | [alert addButtonWithTitle:UCLocalize("CLOSE")]; | |
6903 | [alert setCancelButtonIndex:0]; | |
6904 | ||
6905 | [alert setMessage: | |
6906 | @"Copyright \u00a9 2008-2015\n" | |
6907 | "SaurikIT, LLC\n" | |
6908 | "\n" | |
6909 | "Jay Freeman (saurik)\n" | |
6910 | "saurik@saurik.com\n" | |
6911 | "http://www.saurik.com/" | |
6912 | ]; | |
6913 | ||
6914 | [alert show]; | |
6915 | } | |
6916 | ||
6917 | - (UIBarButtonItem *) leftButton { | |
6918 | return [[[UIBarButtonItem alloc] | |
6919 | initWithTitle:UCLocalize("ABOUT") | |
6920 | style:UIBarButtonItemStylePlain | |
6921 | target:self | |
6922 | action:@selector(aboutButtonClicked) | |
6923 | ] autorelease]; | |
6924 | } | |
6925 | ||
6926 | @end | |
6927 | /* }}} */ | |
6928 | ||
6929 | /* Cydia Navigation Controller Interface {{{ */ | |
6930 | @interface UINavigationController (Cydia) | |
6931 | ||
6932 | - (NSArray *) navigationURLCollection; | |
6933 | - (void) unloadData; | |
6934 | ||
6935 | @end | |
6936 | /* }}} */ | |
6937 | ||
6938 | /* Cydia Tab Bar Controller {{{ */ | |
6939 | @interface CydiaTabBarController : CyteTabBarController < | |
6940 | UITabBarControllerDelegate, | |
6941 | FetchDelegate | |
6942 | > { | |
6943 | _transient Database *database_; | |
6944 | ||
6945 | _H<UIActivityIndicatorView> indicator_; | |
6946 | ||
6947 | bool updating_; | |
6948 | // XXX: ok, "updatedelegate_"?... | |
6949 | _transient NSObject<CydiaDelegate> *updatedelegate_; | |
6950 | } | |
6951 | ||
6952 | - (NSArray *) navigationURLCollection; | |
6953 | - (void) beginUpdate; | |
6954 | - (BOOL) updating; | |
6955 | ||
6956 | @end | |
6957 | ||
6958 | @implementation CydiaTabBarController | |
6959 | ||
6960 | - (NSArray *) navigationURLCollection { | |
6961 | NSMutableArray *items([NSMutableArray array]); | |
6962 | ||
6963 | // XXX: Should this deal with transient view controllers? | |
6964 | for (id navigation in [self viewControllers]) { | |
6965 | NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)]; | |
6966 | if (stack != nil) | |
6967 | [items addObject:stack]; | |
6968 | } | |
6969 | ||
6970 | return items; | |
6971 | } | |
6972 | ||
6973 | - (id) initWithDatabase:(Database *)database { | |
6974 | if ((self = [super init]) != nil) { | |
6975 | database_ = database; | |
6976 | [self setDelegate:self]; | |
6977 | ||
6978 | indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease]; | |
6979 | [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)]; | |
6980 | ||
6981 | [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
6982 | } return self; | |
6983 | } | |
6984 | ||
6985 | - (void) beginUpdate { | |
6986 | if (updating_) | |
6987 | return; | |
6988 | ||
6989 | UIViewController *controller([[self viewControllers] objectAtIndex:1]); | |
6990 | UITabBarItem *item([controller tabBarItem]); | |
6991 | ||
6992 | [item setBadgeValue:@""]; | |
6993 | UIView *badge(MSHookIvar<UIView *>([item view], "_badge")); | |
6994 | ||
6995 | [indicator_ startAnimating]; | |
6996 | [badge addSubview:indicator_]; | |
6997 | ||
6998 | [updatedelegate_ retainNetworkActivityIndicator]; | |
6999 | updating_ = true; | |
7000 | ||
7001 | [NSThread | |
7002 | detachNewThreadSelector:@selector(performUpdate) | |
7003 | toTarget:self | |
7004 | withObject:nil | |
7005 | ]; | |
7006 | } | |
7007 | ||
7008 | - (void) performUpdate { | |
7009 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
7010 | ||
7011 | SourceStatus status(self, database_); | |
7012 | [database_ updateWithStatus:status]; | |
7013 | ||
7014 | [self | |
7015 | performSelectorOnMainThread:@selector(completeUpdate) | |
7016 | withObject:nil | |
7017 | waitUntilDone:NO | |
7018 | ]; | |
7019 | ||
7020 | [pool release]; | |
7021 | } | |
7022 | ||
7023 | - (void) stopUpdateWithSelector:(SEL)selector { | |
7024 | updating_ = false; | |
7025 | [updatedelegate_ releaseNetworkActivityIndicator]; | |
7026 | ||
7027 | UIViewController *controller([[self viewControllers] objectAtIndex:1]); | |
7028 | [[controller tabBarItem] setBadgeValue:nil]; | |
7029 | ||
7030 | [indicator_ removeFromSuperview]; | |
7031 | [indicator_ stopAnimating]; | |
7032 | ||
7033 | [updatedelegate_ performSelector:selector withObject:nil afterDelay:0]; | |
7034 | } | |
7035 | ||
7036 | - (void) completeUpdate { | |
7037 | if (!updating_) | |
7038 | return; | |
7039 | [self stopUpdateWithSelector:@selector(reloadData)]; | |
7040 | } | |
7041 | ||
7042 | - (void) cancelUpdate { | |
7043 | [self stopUpdateWithSelector:@selector(updateDataAndLoad)]; | |
7044 | } | |
7045 | ||
7046 | - (void) cancelPressed { | |
7047 | [self cancelUpdate]; | |
7048 | } | |
7049 | ||
7050 | - (BOOL) updating { | |
7051 | return updating_; | |
7052 | } | |
7053 | ||
7054 | - (bool) isSourceCancelled { | |
7055 | return !updating_; | |
7056 | } | |
7057 | ||
7058 | - (void) startSourceFetch:(NSString *)uri { | |
7059 | } | |
7060 | ||
7061 | - (void) stopSourceFetch:(NSString *)uri { | |
7062 | } | |
7063 | ||
7064 | - (void) setUpdateDelegate:(id)delegate { | |
7065 | updatedelegate_ = delegate; | |
7066 | } | |
7067 | ||
7068 | @end | |
7069 | /* }}} */ | |
7070 | ||
7071 | /* Cydia Navigation Controller Implementation {{{ */ | |
7072 | @implementation UINavigationController (Cydia) | |
7073 | ||
7074 | - (NSArray *) navigationURLCollection { | |
7075 | NSMutableArray *stack([NSMutableArray array]); | |
7076 | ||
7077 | for (CyteViewController *controller in [self viewControllers]) { | |
7078 | NSString *url = [[controller navigationURL] absoluteString]; | |
7079 | if (url != nil) | |
7080 | [stack addObject:url]; | |
7081 | } | |
7082 | ||
7083 | return stack; | |
7084 | } | |
7085 | ||
7086 | - (void) reloadData { | |
7087 | [super reloadData]; | |
7088 | ||
7089 | UIViewController *visible([self visibleViewController]); | |
7090 | if (visible != nil) | |
7091 | [visible reloadData]; | |
7092 | ||
7093 | // on the iPad, this view controller is ALSO visible. :( | |
7094 | if (IsWildcat_) | |
7095 | if (UIViewController *modal = [self modalViewController]) | |
7096 | if ([modal modalPresentationStyle] == UIModalPresentationFormSheet) | |
7097 | if (UIViewController *top = [self topViewController]) | |
7098 | if (top != visible) | |
7099 | [top reloadData]; | |
7100 | } | |
7101 | ||
7102 | - (void) unloadData { | |
7103 | for (CyteViewController *page in [self viewControllers]) | |
7104 | [page unloadData]; | |
7105 | ||
7106 | [super unloadData]; | |
7107 | } | |
7108 | ||
7109 | @end | |
7110 | /* }}} */ | |
7111 | ||
7112 | /* Cydia:// Protocol {{{ */ | |
7113 | @interface CydiaURLProtocol : NSURLProtocol { | |
7114 | } | |
7115 | ||
7116 | @end | |
7117 | ||
7118 | @implementation CydiaURLProtocol | |
7119 | ||
7120 | + (BOOL) canInitWithRequest:(NSURLRequest *)request { | |
7121 | NSURL *url([request URL]); | |
7122 | if (url == nil) | |
7123 | return NO; | |
7124 | ||
7125 | NSString *scheme([[url scheme] lowercaseString]); | |
7126 | if (scheme != nil && [scheme isEqualToString:@"cydia"]) | |
7127 | return YES; | |
7128 | if ([[url absoluteString] hasPrefix:@"about:cydia-"]) | |
7129 | return YES; | |
7130 | ||
7131 | return NO; | |
7132 | } | |
7133 | ||
7134 | + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request { | |
7135 | return request; | |
7136 | } | |
7137 | ||
7138 | - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request { | |
7139 | id<NSURLProtocolClient> client([self client]); | |
7140 | if (icon == nil) | |
7141 | [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]]; | |
7142 | else { | |
7143 | NSData *data(UIImagePNGRepresentation(icon)); | |
7144 | ||
7145 | NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]); | |
7146 | [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; | |
7147 | [client URLProtocol:self didLoadData:data]; | |
7148 | [client URLProtocolDidFinishLoading:self]; | |
7149 | } | |
7150 | } | |
7151 | ||
7152 | - (void) startLoading { | |
7153 | id<NSURLProtocolClient> client([self client]); | |
7154 | NSURLRequest *request([self request]); | |
7155 | ||
7156 | NSURL *url([request URL]); | |
7157 | NSString *href([url absoluteString]); | |
7158 | NSString *scheme([[url scheme] lowercaseString]); | |
7159 | ||
7160 | NSString *path; | |
7161 | ||
7162 | if ([scheme isEqualToString:@"cydia"]) | |
7163 | path = [href substringFromIndex:8]; | |
7164 | else if ([scheme isEqualToString:@"about"]) | |
7165 | path = [href substringFromIndex:12]; | |
7166 | else _assert(false); | |
7167 | ||
7168 | NSRange slash([path rangeOfString:@"/"]); | |
7169 | ||
7170 | NSString *command; | |
7171 | if (slash.location == NSNotFound) { | |
7172 | command = path; | |
7173 | path = nil; | |
7174 | } else { | |
7175 | command = [path substringToIndex:slash.location]; | |
7176 | path = [path substringFromIndex:(slash.location + 1)]; | |
7177 | } | |
7178 | ||
7179 | Database *database([Database sharedInstance]); | |
7180 | ||
7181 | if (false); | |
7182 | else if ([command isEqualToString:@"application-icon"]) { | |
7183 | if (path == nil) | |
7184 | goto fail; | |
7185 | path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
7186 | ||
7187 | UIImage *icon(nil); | |
7188 | ||
7189 | if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) { | |
7190 | NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]); | |
7191 | icon = [UIImage imageWithData:data]; | |
7192 | } | |
7193 | ||
7194 | if (icon == nil) | |
7195 | if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path)) | |
7196 | icon = [UIImage imageAtPath:file]; | |
7197 | ||
7198 | if (icon == nil) | |
7199 | icon = [UIImage imageNamed:@"unknown.png"]; | |
7200 | ||
7201 | [self _returnPNGWithImage:icon forRequest:request]; | |
7202 | } else if ([command isEqualToString:@"package-icon"]) { | |
7203 | if (path == nil) | |
7204 | goto fail; | |
7205 | path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
7206 | Package *package([database packageWithName:path]); | |
7207 | if (package == nil) | |
7208 | goto fail; | |
7209 | [package parse]; | |
7210 | UIImage *icon([package icon]); | |
7211 | [self _returnPNGWithImage:icon forRequest:request]; | |
7212 | } else if ([command isEqualToString:@"uikit-image"]) { | |
7213 | if (path == nil) | |
7214 | goto fail; | |
7215 | path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
7216 | UIImage *icon(_UIImageWithName(path)); | |
7217 | [self _returnPNGWithImage:icon forRequest:request]; | |
7218 | } else if ([command isEqualToString:@"section-icon"]) { | |
7219 | if (path == nil) | |
7220 | goto fail; | |
7221 | path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
7222 | UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]); | |
7223 | if (icon == nil) | |
7224 | icon = [UIImage imageNamed:@"unknown.png"]; | |
7225 | [self _returnPNGWithImage:icon forRequest:request]; | |
7226 | } else fail: { | |
7227 | [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]]; | |
7228 | } | |
7229 | } | |
7230 | ||
7231 | - (void) stopLoading { | |
7232 | } | |
7233 | ||
7234 | @end | |
7235 | /* }}} */ | |
7236 | ||
7237 | /* Section Controller {{{ */ | |
7238 | @interface SectionController : FilteredPackageListController { | |
7239 | _H<NSString> key_; | |
7240 | _H<NSString> section_; | |
7241 | } | |
7242 | ||
7243 | - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section; | |
7244 | ||
7245 | @end | |
7246 | ||
7247 | @implementation SectionController | |
7248 | ||
7249 | - (NSURL *) referrerURL { | |
7250 | NSString *name(section_); | |
7251 | name = name ?: @"*"; | |
7252 | NSString *key(key_); | |
7253 | key = key ?: @"*"; | |
7254 | return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]]; | |
7255 | } | |
7256 | ||
7257 | - (NSURL *) navigationURL { | |
7258 | NSString *name(section_); | |
7259 | name = name ?: @"*"; | |
7260 | NSString *key(key_); | |
7261 | key = key ?: @"*"; | |
7262 | return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]]; | |
7263 | } | |
7264 | ||
7265 | - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section { | |
7266 | NSString *title; | |
7267 | if (section == nil) | |
7268 | title = UCLocalize("ALL_PACKAGES"); | |
7269 | else if (![section isEqual:@""]) | |
7270 | title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"]; | |
7271 | else | |
7272 | title = UCLocalize("NO_SECTION"); | |
7273 | ||
7274 | if ((self = [super initWithDatabase:database title:title]) != nil) { | |
7275 | key_ = [source key]; | |
7276 | section_ = section; | |
7277 | } return self; | |
7278 | } | |
7279 | ||
7280 | - (void) reloadData { | |
7281 | Source *source([database_ sourceWithKey:key_]); | |
7282 | _H<NSString> name(section_); | |
7283 | ||
7284 | [self setFilter:[=](Package *package) { | |
7285 | NSString *section([package section]); | |
7286 | ||
7287 | return ( | |
7288 | name == nil || | |
7289 | section == nil && [name length] == 0 || | |
7290 | [name isEqualToString:section] | |
7291 | ) && ( | |
7292 | source == nil || | |
7293 | [package source] == source | |
7294 | ) && [package visible]; | |
7295 | }]; | |
7296 | ||
7297 | [super reloadData]; | |
7298 | } | |
7299 | ||
7300 | @end | |
7301 | /* }}} */ | |
7302 | /* Sections Controller {{{ */ | |
7303 | @interface SectionsController : CyteViewController < | |
7304 | UITableViewDataSource, | |
7305 | UITableViewDelegate | |
7306 | > { | |
7307 | _transient Database *database_; | |
7308 | _H<NSString> key_; | |
7309 | _H<NSMutableArray> sections_; | |
7310 | _H<NSMutableArray> filtered_; | |
7311 | _H<UITableView, 2> list_; | |
7312 | } | |
7313 | ||
7314 | - (id) initWithDatabase:(Database *)database source:(Source *)source; | |
7315 | - (void) editButtonClicked; | |
7316 | ||
7317 | @end | |
7318 | ||
7319 | @implementation SectionsController | |
7320 | ||
7321 | - (NSURL *) navigationURL { | |
7322 | return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]]; | |
7323 | } | |
7324 | ||
7325 | - (Source *) source { | |
7326 | if (key_ == nil) | |
7327 | return nil; | |
7328 | return [database_ sourceWithKey:key_]; | |
7329 | } | |
7330 | ||
7331 | - (void) updateNavigationItem { | |
7332 | [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")]; | |
7333 | if ([sections_ count] == 0) { | |
7334 | [[self navigationItem] setRightBarButtonItem:nil]; | |
7335 | } else { | |
7336 | [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc] | |
7337 | initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit) | |
7338 | target:self | |
7339 | action:@selector(editButtonClicked) | |
7340 | ] animated:([[self navigationItem] rightBarButtonItem] != nil)]; | |
7341 | } | |
7342 | } | |
7343 | ||
7344 | - (void) setEditing:(BOOL)editing animated:(BOOL)animated { | |
7345 | [super setEditing:editing animated:animated]; | |
7346 | ||
7347 | if (editing) | |
7348 | [list_ reloadData]; | |
7349 | else | |
7350 | [delegate_ updateData]; | |
7351 | ||
7352 | [self updateNavigationItem]; | |
7353 | } | |
7354 | ||
7355 | - (void) viewDidAppear:(BOOL)animated { | |
7356 | [super viewDidAppear:animated]; | |
7357 | [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; | |
7358 | } | |
7359 | ||
7360 | - (void) viewWillDisappear:(BOOL)animated { | |
7361 | [super viewWillDisappear:animated]; | |
7362 | [self setEditing:NO]; | |
7363 | } | |
7364 | ||
7365 | - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath { | |
7366 | Section *section = nil; | |
7367 | int index = [indexPath row]; | |
7368 | if (![self isEditing]) { | |
7369 | index -= 1; | |
7370 | if (index >= 0) | |
7371 | section = [filtered_ objectAtIndex:index]; | |
7372 | } else { | |
7373 | section = [sections_ objectAtIndex:index]; | |
7374 | } | |
7375 | return section; | |
7376 | } | |
7377 | ||
7378 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
7379 | if ([self isEditing]) | |
7380 | return [sections_ count]; | |
7381 | else | |
7382 | return [filtered_ count] + 1; | |
7383 | } | |
7384 | ||
7385 | /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { | |
7386 | return 45.0f; | |
7387 | }*/ | |
7388 | ||
7389 | - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
7390 | static NSString *reuseIdentifier = @"SectionCell"; | |
7391 | ||
7392 | SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; | |
7393 | if (cell == nil) | |
7394 | cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease]; | |
7395 | ||
7396 | [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]]; | |
7397 | ||
7398 | return cell; | |
7399 | } | |
7400 | ||
7401 | - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { | |
7402 | if ([self isEditing]) | |
7403 | return; | |
7404 | ||
7405 | Section *section = [self sectionAtIndexPath:indexPath]; | |
7406 | ||
7407 | SectionController *controller = [[[SectionController alloc] | |
7408 | initWithDatabase:database_ | |
7409 | source:[self source] | |
7410 | section:[section name] | |
7411 | ] autorelease]; | |
7412 | [controller setDelegate:delegate_]; | |
7413 | ||
7414 | [[self navigationController] pushViewController:controller animated:YES]; | |
7415 | } | |
7416 | ||
7417 | - (void) loadView { | |
7418 | list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]; | |
7419 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
7420 | [list_ setRowHeight:46]; | |
7421 | [(UITableView *) list_ setDataSource:self]; | |
7422 | [list_ setDelegate:self]; | |
7423 | [self setView:list_]; | |
7424 | } | |
7425 | ||
7426 | - (void) viewDidLoad { | |
7427 | [super viewDidLoad]; | |
7428 | ||
7429 | [[self navigationItem] setTitle:UCLocalize("SECTIONS")]; | |
7430 | } | |
7431 | ||
7432 | - (void) releaseSubviews { | |
7433 | list_ = nil; | |
7434 | ||
7435 | sections_ = nil; | |
7436 | filtered_ = nil; | |
7437 | ||
7438 | [super releaseSubviews]; | |
7439 | } | |
7440 | ||
7441 | - (id) initWithDatabase:(Database *)database source:(Source *)source { | |
7442 | if ((self = [super init]) != nil) { | |
7443 | database_ = database; | |
7444 | key_ = [source key]; | |
7445 | } return self; | |
7446 | } | |
7447 | ||
7448 | - (void) reloadData { | |
7449 | [super reloadData]; | |
7450 | ||
7451 | NSArray *packages = [database_ packages]; | |
7452 | ||
7453 | sections_ = [NSMutableArray arrayWithCapacity:16]; | |
7454 | filtered_ = [NSMutableArray arrayWithCapacity:16]; | |
7455 | ||
7456 | NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]); | |
7457 | ||
7458 | Source *source([self source]); | |
7459 | ||
7460 | _trace(); | |
7461 | for (Package *package in packages) { | |
7462 | if (source != nil && [package source] != source) | |
7463 | continue; | |
7464 | ||
7465 | NSString *name([package section]); | |
7466 | NSString *key(name == nil ? @"" : name); | |
7467 | ||
7468 | Section *section; | |
7469 | ||
7470 | _profile(SectionsView$reloadData$Section) | |
7471 | section = [sections objectForKey:key]; | |
7472 | if (section == nil) { | |
7473 | _profile(SectionsView$reloadData$Section$Allocate) | |
7474 | section = [[[Section alloc] initWithName:key localize:YES] autorelease]; | |
7475 | [sections setObject:section forKey:key]; | |
7476 | _end | |
7477 | } | |
7478 | _end | |
7479 | ||
7480 | [section addToCount]; | |
7481 | ||
7482 | _profile(SectionsView$reloadData$Filter) | |
7483 | if (![package valid] || ![package visible]) | |
7484 | continue; | |
7485 | _end | |
7486 | ||
7487 | [section addToRow]; | |
7488 | } | |
7489 | _trace(); | |
7490 | ||
7491 | [sections_ addObjectsFromArray:[sections allValues]]; | |
7492 | ||
7493 | [sections_ sortUsingSelector:@selector(compareByLocalized:)]; | |
7494 | ||
7495 | for (Section *section in (id) sections_) { | |
7496 | size_t count([section row]); | |
7497 | if (count == 0) | |
7498 | continue; | |
7499 | ||
7500 | section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease]; | |
7501 | [section setCount:count]; | |
7502 | [filtered_ addObject:section]; | |
7503 | } | |
7504 | ||
7505 | [self updateNavigationItem]; | |
7506 | [list_ reloadData]; | |
7507 | _trace(); | |
7508 | } | |
7509 | ||
7510 | - (void) editButtonClicked { | |
7511 | [self setEditing:![self isEditing] animated:YES]; | |
7512 | } | |
7513 | ||
7514 | @end | |
7515 | /* }}} */ | |
7516 | ||
7517 | /* Changes Controller {{{ */ | |
7518 | @interface ChangesController : FilteredPackageListController { | |
7519 | unsigned upgrades_; | |
7520 | } | |
7521 | ||
7522 | - (id) initWithDatabase:(Database *)database; | |
7523 | ||
7524 | @end | |
7525 | ||
7526 | @implementation ChangesController | |
7527 | ||
7528 | - (NSURL *) referrerURL { | |
7529 | return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]]; | |
7530 | } | |
7531 | ||
7532 | - (NSURL *) navigationURL { | |
7533 | return [NSURL URLWithString:@"cydia://changes"]; | |
7534 | } | |
7535 | ||
7536 | - (Package *) packageAtIndexPath:(NSIndexPath *)path { | |
7537 | @synchronized (database_) { | |
7538 | if ([database_ era] != era_) | |
7539 | return nil; | |
7540 | ||
7541 | NSUInteger sectionIndex([path section]); | |
7542 | if (sectionIndex >= [sections_ count]) | |
7543 | return nil; | |
7544 | Section *section([sections_ objectAtIndex:sectionIndex]); | |
7545 | NSInteger row([path row]); | |
7546 | return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease]; | |
7547 | } } | |
7548 | ||
7549 | - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { | |
7550 | NSString *context([alert context]); | |
7551 | ||
7552 | if ([context isEqualToString:@"norefresh"]) | |
7553 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
7554 | } | |
7555 | ||
7556 | - (void) setLeftBarButtonItem { | |
7557 | if ([delegate_ updating]) | |
7558 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
7559 | initWithTitle:UCLocalize("CANCEL") | |
7560 | style:UIBarButtonItemStyleDone | |
7561 | target:self | |
7562 | action:@selector(cancelButtonClicked) | |
7563 | ] autorelease] animated:YES]; | |
7564 | else | |
7565 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
7566 | initWithTitle:UCLocalize("REFRESH") | |
7567 | style:UIBarButtonItemStylePlain | |
7568 | target:self | |
7569 | action:@selector(refreshButtonClicked) | |
7570 | ] autorelease] animated:YES]; | |
7571 | } | |
7572 | ||
7573 | - (void) refreshButtonClicked { | |
7574 | if ([delegate_ requestUpdate]) | |
7575 | [self setLeftBarButtonItem]; | |
7576 | } | |
7577 | ||
7578 | - (void) cancelButtonClicked { | |
7579 | [delegate_ cancelUpdate]; | |
7580 | } | |
7581 | ||
7582 | - (void) upgradeButtonClicked { | |
7583 | [delegate_ distUpgrade]; | |
7584 | [[self navigationItem] setRightBarButtonItem:nil animated:YES]; | |
7585 | } | |
7586 | ||
7587 | - (bool) shouldYield { | |
7588 | return true; | |
7589 | } | |
7590 | ||
7591 | - (bool) shouldBlock { | |
7592 | return true; | |
7593 | } | |
7594 | ||
7595 | - (void) useFilter { | |
7596 | @synchronized (self) { | |
7597 | [self setFilter:[](Package *package) { | |
7598 | return [package upgradableAndEssential:YES] || [package visible]; | |
7599 | }]; | |
7600 | ||
7601 | [self setSorter:[](NSMutableArray *packages) { | |
7602 | [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL]; | |
7603 | }]; | |
7604 | } } | |
7605 | ||
7606 | - (id) initWithDatabase:(Database *)database { | |
7607 | if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) { | |
7608 | [self useFilter]; | |
7609 | } return self; | |
7610 | } | |
7611 | ||
7612 | - (void) viewDidLoad { | |
7613 | [super viewDidLoad]; | |
7614 | [self setLeftBarButtonItem]; | |
7615 | } | |
7616 | ||
7617 | - (void) viewWillAppear:(BOOL)animated { | |
7618 | [super viewWillAppear:animated]; | |
7619 | [self setLeftBarButtonItem]; | |
7620 | } | |
7621 | ||
7622 | - (void) reloadData { | |
7623 | [self setLeftBarButtonItem]; | |
7624 | [super reloadData]; | |
7625 | } | |
7626 | ||
7627 | - (NSArray *) sectionsForPackages:(NSMutableArray *)packages { | |
7628 | NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]); | |
7629 | ||
7630 | Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease]; | |
7631 | Section *ignored = nil; | |
7632 | Section *section = nil; | |
7633 | time_t last = 0; | |
7634 | ||
7635 | upgrades_ = 0; | |
7636 | bool unseens = false; | |
7637 | ||
7638 | CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle)); | |
7639 | ||
7640 | for (size_t offset = 0, count = [packages count]; offset != count; ++offset) { | |
7641 | Package *package = [packages objectAtIndex:offset]; | |
7642 | ||
7643 | BOOL uae = [package upgradableAndEssential:YES]; | |
7644 | ||
7645 | if (!uae) { | |
7646 | unseens = true; | |
7647 | time_t seen([package seen]); | |
7648 | ||
7649 | if (section == nil || last != seen) { | |
7650 | last = seen; | |
7651 | ||
7652 | NSString *name; | |
7653 | name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]); | |
7654 | [name autorelease]; | |
7655 | ||
7656 | _profile(ChangesController$reloadData$Allocate) | |
7657 | name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name]; | |
7658 | section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease]; | |
7659 | [sections addObject:section]; | |
7660 | _end | |
7661 | } | |
7662 | ||
7663 | [section addToCount]; | |
7664 | } else if ([package ignored]) { | |
7665 | if (ignored == nil) { | |
7666 | ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease]; | |
7667 | } | |
7668 | [ignored addToCount]; | |
7669 | } else { | |
7670 | ++upgrades_; | |
7671 | [upgradable addToCount]; | |
7672 | } | |
7673 | } | |
7674 | _trace(); | |
7675 | ||
7676 | CFRelease(formatter); | |
7677 | ||
7678 | if (unseens) { | |
7679 | Section *last = [sections lastObject]; | |
7680 | size_t count = [last count]; | |
7681 | [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)]; | |
7682 | [sections removeLastObject]; | |
7683 | } | |
7684 | ||
7685 | if ([ignored count] != 0) | |
7686 | [sections insertObject:ignored atIndex:0]; | |
7687 | if (upgrades_ != 0) | |
7688 | [sections insertObject:upgradable atIndex:0]; | |
7689 | ||
7690 | [list_ reloadData]; | |
7691 | ||
7692 | [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc] | |
7693 | initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]] | |
7694 | style:UIBarButtonItemStylePlain | |
7695 | target:self | |
7696 | action:@selector(upgradeButtonClicked) | |
7697 | ] autorelease]) animated:YES]; | |
7698 | ||
7699 | return sections; | |
7700 | } | |
7701 | ||
7702 | @end | |
7703 | /* }}} */ | |
7704 | /* Search Controller {{{ */ | |
7705 | @interface SearchController : FilteredPackageListController < | |
7706 | UISearchBarDelegate | |
7707 | > { | |
7708 | _H<UISearchBar, 1> search_; | |
7709 | BOOL searchloaded_; | |
7710 | bool summary_; | |
7711 | } | |
7712 | ||
7713 | - (id) initWithDatabase:(Database *)database query:(NSString *)query; | |
7714 | - (void) reloadData; | |
7715 | ||
7716 | @end | |
7717 | ||
7718 | @implementation SearchController | |
7719 | ||
7720 | - (NSURL *) referrerURL { | |
7721 | return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]]; | |
7722 | } | |
7723 | ||
7724 | - (NSURL *) navigationURL { | |
7725 | if ([search_ text] == nil || [[search_ text] isEqualToString:@""]) | |
7726 | return [NSURL URLWithString:@"cydia://search"]; | |
7727 | else | |
7728 | return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]]; | |
7729 | } | |
7730 | ||
7731 | - (NSArray *) termsForQuery:(NSString *)query { | |
7732 | NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]); | |
7733 | for (NSString *component in [query componentsSeparatedByString:@" "]) | |
7734 | if ([component length] != 0) | |
7735 | [terms addObject:component]; | |
7736 | ||
7737 | return terms; | |
7738 | } | |
7739 | ||
7740 | - (void) useSearch { | |
7741 | _H<NSArray> query([self termsForQuery:[search_ text]]); | |
7742 | summary_ = false; | |
7743 | ||
7744 | @synchronized (self) { | |
7745 | [self setFilter:[=](Package *package) { | |
7746 | if (![package unfiltered]) | |
7747 | return false; | |
7748 | if (![package matches:query]) | |
7749 | return false; | |
7750 | return true; | |
7751 | }]; | |
7752 | ||
7753 | [self setSorter:[](NSMutableArray *packages) { | |
7754 | [packages radixSortUsingSelector:@selector(rank)]; | |
7755 | }]; | |
7756 | } | |
7757 | ||
7758 | [self clearData]; | |
7759 | [self reloadData]; | |
7760 | } | |
7761 | ||
7762 | - (void) usePrefix:(NSString *)prefix { | |
7763 | _H<NSString> query(prefix); | |
7764 | summary_ = true; | |
7765 | ||
7766 | @synchronized (self) { | |
7767 | [self setFilter:[=](Package *package) { | |
7768 | if ([query length] == 0) | |
7769 | return false; | |
7770 | if (![package unfiltered]) | |
7771 | return false; | |
7772 | if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame) | |
7773 | return false; | |
7774 | return true; | |
7775 | }]; | |
7776 | ||
7777 | [self setSorter:nullptr]; | |
7778 | } | |
7779 | ||
7780 | [self reloadData]; | |
7781 | } | |
7782 | ||
7783 | - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar { | |
7784 | [self clearData]; | |
7785 | [self usePrefix:[search_ text]]; | |
7786 | } | |
7787 | ||
7788 | - (void) searchBarButtonClicked:(UISearchBar *)searchBar { | |
7789 | [search_ resignFirstResponder]; | |
7790 | [self useSearch]; | |
7791 | } | |
7792 | ||
7793 | - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar { | |
7794 | [search_ setText:@""]; | |
7795 | [self searchBarButtonClicked:searchBar]; | |
7796 | } | |
7797 | ||
7798 | - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar { | |
7799 | [self searchBarButtonClicked:searchBar]; | |
7800 | } | |
7801 | ||
7802 | - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text { | |
7803 | [self usePrefix:text]; | |
7804 | } | |
7805 | ||
7806 | - (bool) shouldYield { | |
7807 | return YES; | |
7808 | } | |
7809 | ||
7810 | - (bool) shouldBlock { | |
7811 | return !summary_; | |
7812 | } | |
7813 | ||
7814 | - (bool) isSummarized { | |
7815 | return summary_; | |
7816 | } | |
7817 | ||
7818 | - (bool) showsSections { | |
7819 | return false; | |
7820 | } | |
7821 | ||
7822 | - (id) initWithDatabase:(Database *)database query:(NSString *)query { | |
7823 | if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) { | |
7824 | search_ = [[[UISearchBar alloc] init] autorelease]; | |
7825 | [search_ setPlaceholder:UCLocalize("SEARCH_EX")]; | |
7826 | [search_ setDelegate:self]; | |
7827 | ||
7828 | UITextField *textField; | |
7829 | if ([search_ respondsToSelector:@selector(searchField)]) | |
7830 | textField = [search_ searchField]; | |
7831 | else | |
7832 | textField = MSHookIvar<UITextField *>(search_, "_searchField"); | |
7833 | ||
7834 | [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; | |
7835 | [textField setEnablesReturnKeyAutomatically:NO]; | |
7836 | [[self navigationItem] setTitleView:textField]; | |
7837 | ||
7838 | if (query != nil) | |
7839 | [search_ setText:query]; | |
7840 | [self useSearch]; | |
7841 | } return self; | |
7842 | } | |
7843 | ||
7844 | - (void) viewDidAppear:(BOOL)animated { | |
7845 | [super viewDidAppear:animated]; | |
7846 | ||
7847 | if (!searchloaded_) { | |
7848 | searchloaded_ = YES; | |
7849 | [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)]; | |
7850 | [search_ layoutSubviews]; | |
7851 | } | |
7852 | ||
7853 | if ([self isSummarized]) | |
7854 | [search_ becomeFirstResponder]; | |
7855 | } | |
7856 | ||
7857 | - (void) reloadData { | |
7858 | [self resetCursor]; | |
7859 | [super reloadData]; | |
7860 | } | |
7861 | ||
7862 | - (void) didSelectPackage:(Package *)package { | |
7863 | [search_ resignFirstResponder]; | |
7864 | [super didSelectPackage:package]; | |
7865 | } | |
7866 | ||
7867 | @end | |
7868 | /* }}} */ | |
7869 | /* Package Settings Controller {{{ */ | |
7870 | @interface PackageSettingsController : CyteViewController < | |
7871 | UITableViewDataSource, | |
7872 | UITableViewDelegate | |
7873 | > { | |
7874 | _transient Database *database_; | |
7875 | _H<NSString> name_; | |
7876 | _H<Package> package_; | |
7877 | _H<UITableView, 2> table_; | |
7878 | _H<UISwitch> subscribedSwitch_; | |
7879 | _H<UISwitch> ignoredSwitch_; | |
7880 | _H<UITableViewCell> subscribedCell_; | |
7881 | _H<UITableViewCell> ignoredCell_; | |
7882 | } | |
7883 | ||
7884 | - (id) initWithDatabase:(Database *)database package:(NSString *)package; | |
7885 | ||
7886 | @end | |
7887 | ||
7888 | @implementation PackageSettingsController | |
7889 | ||
7890 | - (NSURL *) navigationURL { | |
7891 | return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]]; | |
7892 | } | |
7893 | ||
7894 | - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { | |
7895 | if (package_ == nil) | |
7896 | return 0; | |
7897 | ||
7898 | if ([package_ installed] == nil) | |
7899 | return 1; | |
7900 | else | |
7901 | return 2; | |
7902 | } | |
7903 | ||
7904 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
7905 | if (package_ == nil) | |
7906 | return 0; | |
7907 | ||
7908 | // both sections contain just one item right now. | |
7909 | return 1; | |
7910 | } | |
7911 | ||
7912 | - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { | |
7913 | return nil; | |
7914 | } | |
7915 | ||
7916 | - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { | |
7917 | if (section == 0) | |
7918 | return UCLocalize("SHOW_ALL_CHANGES_EX"); | |
7919 | else | |
7920 | return UCLocalize("IGNORE_UPGRADES_EX"); | |
7921 | } | |
7922 | ||
7923 | - (void) onSubscribed:(id)control { | |
7924 | bool value([control isOn]); | |
7925 | if (package_ == nil) | |
7926 | return; | |
7927 | if ([package_ setSubscribed:value]) | |
7928 | [delegate_ updateData]; | |
7929 | } | |
7930 | ||
7931 | - (void) _updateIgnored { | |
7932 | const char *package([name_ UTF8String]); | |
7933 | bool on([ignoredSwitch_ isOn]); | |
7934 | ||
7935 | FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w")); | |
7936 | fwrite(package, strlen(package), 1, dpkg); | |
7937 | ||
7938 | if (on) | |
7939 | fwrite(" hold\n", 6, 1, dpkg); | |
7940 | else | |
7941 | fwrite(" install\n", 9, 1, dpkg); | |
7942 | ||
7943 | pclose(dpkg); | |
7944 | } | |
7945 | ||
7946 | - (void) onIgnored:(id)control { | |
7947 | NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]); | |
7948 | [invocation setTarget:self]; | |
7949 | [invocation setSelector:@selector(_updateIgnored)]; | |
7950 | ||
7951 | [delegate_ reloadDataWithInvocation:invocation]; | |
7952 | } | |
7953 | ||
7954 | - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
7955 | if (package_ == nil) | |
7956 | return nil; | |
7957 | ||
7958 | switch ([indexPath section]) { | |
7959 | case 0: return subscribedCell_; | |
7960 | case 1: return ignoredCell_; | |
7961 | ||
7962 | _nodefault | |
7963 | } | |
7964 | ||
7965 | return nil; | |
7966 | } | |
7967 | ||
7968 | - (void) loadView { | |
7969 | UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]); | |
7970 | [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)]; | |
7971 | [self setView:view]; | |
7972 | ||
7973 | table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]; | |
7974 | [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
7975 | [(UITableView *) table_ setDataSource:self]; | |
7976 | [table_ setDelegate:self]; | |
7977 | [view addSubview:table_]; | |
7978 | ||
7979 | subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease]; | |
7980 | [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; | |
7981 | [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged]; | |
7982 | ||
7983 | ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease]; | |
7984 | [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; | |
7985 | [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged]; | |
7986 | ||
7987 | subscribedCell_ = [[[UITableViewCell alloc] init] autorelease]; | |
7988 | [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")]; | |
7989 | [subscribedCell_ setAccessoryView:subscribedSwitch_]; | |
7990 | [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone]; | |
7991 | ||
7992 | ignoredCell_ = [[[UITableViewCell alloc] init] autorelease]; | |
7993 | [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")]; | |
7994 | [ignoredCell_ setAccessoryView:ignoredSwitch_]; | |
7995 | [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone]; | |
7996 | } | |
7997 | ||
7998 | - (void) viewDidLoad { | |
7999 | [super viewDidLoad]; | |
8000 | ||
8001 | [[self navigationItem] setTitle:UCLocalize("SETTINGS")]; | |
8002 | } | |
8003 | ||
8004 | - (void) releaseSubviews { | |
8005 | ignoredCell_ = nil; | |
8006 | subscribedCell_ = nil; | |
8007 | table_ = nil; | |
8008 | ignoredSwitch_ = nil; | |
8009 | subscribedSwitch_ = nil; | |
8010 | ||
8011 | [super releaseSubviews]; | |
8012 | } | |
8013 | ||
8014 | - (id) initWithDatabase:(Database *)database package:(NSString *)package { | |
8015 | if ((self = [super init]) != nil) { | |
8016 | database_ = database; | |
8017 | name_ = package; | |
8018 | } return self; | |
8019 | } | |
8020 | ||
8021 | - (void) reloadData { | |
8022 | [super reloadData]; | |
8023 | ||
8024 | package_ = [database_ packageWithName:name_]; | |
8025 | ||
8026 | if (package_ != nil) { | |
8027 | [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO]; | |
8028 | [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO]; | |
8029 | } // XXX: what now, G? | |
8030 | ||
8031 | [table_ reloadData]; | |
8032 | } | |
8033 | ||
8034 | @end | |
8035 | /* }}} */ | |
8036 | ||
8037 | /* Installed Controller {{{ */ | |
8038 | @interface InstalledController : FilteredPackageListController { | |
8039 | bool sectioned_; | |
8040 | } | |
8041 | ||
8042 | - (id) initWithDatabase:(Database *)database; | |
8043 | - (void) queueStatusDidChange; | |
8044 | ||
8045 | @end | |
8046 | ||
8047 | @implementation InstalledController | |
8048 | ||
8049 | - (NSURL *) referrerURL { | |
8050 | return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]]; | |
8051 | } | |
8052 | ||
8053 | - (NSURL *) navigationURL { | |
8054 | return [NSURL URLWithString:@"cydia://installed"]; | |
8055 | } | |
8056 | ||
8057 | - (void) useRecent { | |
8058 | sectioned_ = false; | |
8059 | ||
8060 | @synchronized (self) { | |
8061 | [self setFilter:[](Package *package) { | |
8062 | return ![package uninstalled] && package->role_ < 7; | |
8063 | }]; | |
8064 | ||
8065 | [self setSorter:[](NSMutableArray *packages) { | |
8066 | [packages radixSortUsingSelector:@selector(recent)]; | |
8067 | }]; | |
8068 | } } | |
8069 | ||
8070 | - (void) useFilter:(UISegmentedControl *)segmented { | |
8071 | NSInteger selected([segmented selectedSegmentIndex]); | |
8072 | if (selected == 2) | |
8073 | return [self useRecent]; | |
8074 | bool simple(selected == 0); | |
8075 | sectioned_ = true; | |
8076 | ||
8077 | @synchronized (self) { | |
8078 | [self setFilter:[=](Package *package) { | |
8079 | return ![package uninstalled] && package->role_ <= (simple ? 1 : 3); | |
8080 | }]; | |
8081 | ||
8082 | [self setSorter:nullptr]; | |
8083 | } } | |
8084 | ||
8085 | - (NSArray *) sectionsForPackages:(NSMutableArray *)packages { | |
8086 | if (sectioned_) | |
8087 | return [super sectionsForPackages:packages]; | |
8088 | ||
8089 | CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle)); | |
8090 | ||
8091 | NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]); | |
8092 | Section *section(nil); | |
8093 | time_t last(0); | |
8094 | ||
8095 | for (size_t offset(0), count([packages count]); offset != count; ++offset) { | |
8096 | Package *package([packages objectAtIndex:offset]); | |
8097 | ||
8098 | time_t upgraded([package upgraded]); | |
8099 | if (upgraded < 1168364520) | |
8100 | upgraded = 0; | |
8101 | else | |
8102 | upgraded -= upgraded % (60 * 60 * 24); | |
8103 | ||
8104 | if (section == nil || upgraded != last) { | |
8105 | last = upgraded; | |
8106 | ||
8107 | NSString *name; | |
8108 | if (upgraded == 0) | |
8109 | continue; // XXX: name = UCLocalize("..."); | |
8110 | else { | |
8111 | name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]); | |
8112 | [name autorelease]; | |
8113 | } | |
8114 | ||
8115 | section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease]; | |
8116 | [sections addObject:section]; | |
8117 | } | |
8118 | ||
8119 | [section addToCount]; | |
8120 | } | |
8121 | ||
8122 | CFRelease(formatter); | |
8123 | return sections; | |
8124 | } | |
8125 | ||
8126 | - (id) initWithDatabase:(Database *)database { | |
8127 | if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) { | |
8128 | UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]); | |
8129 | [segmented setSelectedSegmentIndex:0]; | |
8130 | [segmented setSegmentedControlStyle:UISegmentedControlStyleBar]; | |
8131 | [[self navigationItem] setTitleView:segmented]; | |
8132 | ||
8133 | [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged]; | |
8134 | [self useFilter:segmented]; | |
8135 | ||
8136 | [self queueStatusDidChange]; | |
8137 | } return self; | |
8138 | } | |
8139 | ||
8140 | #if !AlwaysReload | |
8141 | - (void) queueButtonClicked { | |
8142 | [delegate_ queue]; | |
8143 | } | |
8144 | #endif | |
8145 | ||
8146 | - (void) queueStatusDidChange { | |
8147 | #if !AlwaysReload | |
8148 | if (Queuing_) { | |
8149 | [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] | |
8150 | initWithTitle:UCLocalize("QUEUE") | |
8151 | style:UIBarButtonItemStyleDone | |
8152 | target:self | |
8153 | action:@selector(queueButtonClicked) | |
8154 | ] autorelease]]; | |
8155 | } else { | |
8156 | [[self navigationItem] setRightBarButtonItem:nil]; | |
8157 | } | |
8158 | #endif | |
8159 | } | |
8160 | ||
8161 | - (void) modeChanged:(UISegmentedControl *)segmented { | |
8162 | [self useFilter:segmented]; | |
8163 | [self reloadData]; | |
8164 | } | |
8165 | ||
8166 | @end | |
8167 | /* }}} */ | |
8168 | ||
8169 | /* Source Cell {{{ */ | |
8170 | @interface SourceCell : CyteTableViewCell < | |
8171 | CyteTableViewCellDelegate, | |
8172 | SourceDelegate | |
8173 | > { | |
8174 | _H<Source, 1> source_; | |
8175 | _H<NSURL> url_; | |
8176 | _H<UIImage> icon_; | |
8177 | _H<NSString> origin_; | |
8178 | _H<NSString> label_; | |
8179 | _H<UIActivityIndicatorView> indicator_; | |
8180 | } | |
8181 | ||
8182 | - (void) setSource:(Source *)source; | |
8183 | - (void) setFetch:(NSNumber *)fetch; | |
8184 | ||
8185 | @end | |
8186 | ||
8187 | @implementation SourceCell | |
8188 | ||
8189 | - (void) _setImage:(NSArray *)data { | |
8190 | if ([url_ isEqual:[data objectAtIndex:0]]) { | |
8191 | icon_ = [data objectAtIndex:1]; | |
8192 | [content_ setNeedsDisplay]; | |
8193 | } | |
8194 | } | |
8195 | ||
8196 | - (void) _setSource:(NSURL *) url { | |
8197 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
8198 | ||
8199 | if (NSData *data = [NSURLConnection | |
8200 | sendSynchronousRequest:[NSURLRequest | |
8201 | requestWithURL:url | |
8202 | cachePolicy:NSURLRequestUseProtocolCachePolicy | |
8203 | timeoutInterval:10 | |
8204 | ] | |
8205 | ||
8206 | returningResponse:NULL | |
8207 | error:NULL | |
8208 | ]) | |
8209 | if (UIImage *image = [UIImage imageWithData:data]) | |
8210 | [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO]; | |
8211 | ||
8212 | [pool release]; | |
8213 | } | |
8214 | ||
8215 | - (void) setSource:(Source *)source { | |
8216 | source_ = source; | |
8217 | [source_ setDelegate:self]; | |
8218 | ||
8219 | [self setFetch:[NSNumber numberWithBool:[source_ fetch]]]; | |
8220 | ||
8221 | icon_ = [UIImage imageNamed:@"unknown.png"]; | |
8222 | ||
8223 | origin_ = [source name]; | |
8224 | label_ = [source rooturi]; | |
8225 | ||
8226 | [content_ setNeedsDisplay]; | |
8227 | ||
8228 | url_ = [source iconURL]; | |
8229 | [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_]; | |
8230 | } | |
8231 | ||
8232 | - (void) setAllSource { | |
8233 | source_ = nil; | |
8234 | [indicator_ stopAnimating]; | |
8235 | ||
8236 | icon_ = [UIImage imageNamed:@"folder.png"]; | |
8237 | origin_ = UCLocalize("ALL_SOURCES"); | |
8238 | label_ = UCLocalize("ALL_SOURCES_EX"); | |
8239 | [content_ setNeedsDisplay]; | |
8240 | } | |
8241 | ||
8242 | - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier { | |
8243 | if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) { | |
8244 | UIView *content([self contentView]); | |
8245 | CGRect bounds([content bounds]); | |
8246 | ||
8247 | content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease]; | |
8248 | [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
8249 | [content_ setBackgroundColor:[UIColor whiteColor]]; | |
8250 | [content addSubview:content_]; | |
8251 | ||
8252 | [content_ setDelegate:self]; | |
8253 | [content_ setOpaque:YES]; | |
8254 | ||
8255 | indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease]; | |
8256 | [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin]; | |
8257 | [content addSubview:indicator_]; | |
8258 | ||
8259 | [[content_ layer] setContentsGravity:kCAGravityTopLeft]; | |
8260 | } return self; | |
8261 | } | |
8262 | ||
8263 | - (void) layoutSubviews { | |
8264 | [super layoutSubviews]; | |
8265 | ||
8266 | UIView *content([self contentView]); | |
8267 | CGRect bounds([content bounds]); | |
8268 | ||
8269 | CGRect frame([indicator_ frame]); | |
8270 | frame.origin.x = bounds.size.width - frame.size.width; | |
8271 | frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2); | |
8272 | ||
8273 | if (kCFCoreFoundationVersionNumber < 800) | |
8274 | frame.origin.x -= 8; | |
8275 | [indicator_ setFrame:frame]; | |
8276 | } | |
8277 | ||
8278 | - (NSString *) accessibilityLabel { | |
8279 | return origin_; | |
8280 | } | |
8281 | ||
8282 | - (void) drawContentRect:(CGRect)rect { | |
8283 | bool highlighted(highlighted_); | |
8284 | float width(rect.size.width); | |
8285 | ||
8286 | if (icon_ != nil) { | |
8287 | CGRect rect; | |
8288 | rect.size = [(UIImage *) icon_ size]; | |
8289 | ||
8290 | while (rect.size.width > 32 || rect.size.height > 32) { | |
8291 | rect.size.width /= 2; | |
8292 | rect.size.height /= 2; | |
8293 | } | |
8294 | ||
8295 | rect.origin.x = 26 - rect.size.width / 2; | |
8296 | rect.origin.y = 26 - rect.size.height / 2; | |
8297 | ||
8298 | [icon_ drawInRect:Retina(rect)]; | |
8299 | } | |
8300 | ||
8301 | if (highlighted && kCFCoreFoundationVersionNumber < 800) | |
8302 | UISetColor(White_); | |
8303 | ||
8304 | if (!highlighted) | |
8305 | UISetColor(Black_); | |
8306 | [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
8307 | ||
8308 | if (!highlighted) | |
8309 | UISetColor(Gray_); | |
8310 | [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
8311 | } | |
8312 | ||
8313 | - (void) setFetch:(NSNumber *)fetch { | |
8314 | if ([fetch boolValue]) | |
8315 | [indicator_ startAnimating]; | |
8316 | else | |
8317 | [indicator_ stopAnimating]; | |
8318 | } | |
8319 | ||
8320 | @end | |
8321 | /* }}} */ | |
8322 | /* Sources Controller {{{ */ | |
8323 | @interface SourcesController : CyteViewController < | |
8324 | UITableViewDataSource, | |
8325 | UITableViewDelegate | |
8326 | > { | |
8327 | _transient Database *database_; | |
8328 | unsigned era_; | |
8329 | ||
8330 | _H<UITableView, 2> list_; | |
8331 | _H<NSMutableArray> sources_; | |
8332 | int offset_; | |
8333 | ||
8334 | _H<NSString> href_; | |
8335 | _H<UIProgressHUD> hud_; | |
8336 | _H<NSError> error_; | |
8337 | ||
8338 | NSURLConnection *trivial_bz2_; | |
8339 | NSURLConnection *trivial_gz_; | |
8340 | ||
8341 | BOOL cydia_; | |
8342 | } | |
8343 | ||
8344 | - (id) initWithDatabase:(Database *)database; | |
8345 | - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated; | |
8346 | ||
8347 | @end | |
8348 | ||
8349 | @implementation SourcesController | |
8350 | ||
8351 | - (void) _releaseConnection:(NSURLConnection *)connection { | |
8352 | if (connection != nil) { | |
8353 | [connection cancel]; | |
8354 | //[connection setDelegate:nil]; | |
8355 | [connection release]; | |
8356 | } | |
8357 | } | |
8358 | ||
8359 | - (void) dealloc { | |
8360 | [self _releaseConnection:trivial_gz_]; | |
8361 | [self _releaseConnection:trivial_bz2_]; | |
8362 | ||
8363 | [super dealloc]; | |
8364 | } | |
8365 | ||
8366 | - (NSURL *) navigationURL { | |
8367 | return [NSURL URLWithString:@"cydia://sources"]; | |
8368 | } | |
8369 | ||
8370 | - (void) viewDidAppear:(BOOL)animated { | |
8371 | [super viewDidAppear:animated]; | |
8372 | [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; | |
8373 | } | |
8374 | ||
8375 | - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { | |
8376 | return 2; | |
8377 | } | |
8378 | ||
8379 | - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { | |
8380 | if (section == 1) | |
8381 | return UCLocalize("INDIVIDUAL_SOURCES"); | |
8382 | return nil; | |
8383 | } | |
8384 | ||
8385 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
8386 | switch (section) { | |
8387 | case 0: return 1; | |
8388 | case 1: return [sources_ count]; | |
8389 | default: return 0; | |
8390 | } | |
8391 | } | |
8392 | ||
8393 | - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath { | |
8394 | @synchronized (database_) { | |
8395 | if ([database_ era] != era_) | |
8396 | return nil; | |
8397 | if ([indexPath section] != 1) | |
8398 | return nil; | |
8399 | NSUInteger index([indexPath row]); | |
8400 | if (index >= [sources_ count]) | |
8401 | return nil; | |
8402 | return [sources_ objectAtIndex:index]; | |
8403 | } } | |
8404 | ||
8405 | - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
8406 | static NSString *cellIdentifier = @"SourceCell"; | |
8407 | ||
8408 | SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; | |
8409 | if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease]; | |
8410 | [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; | |
8411 | ||
8412 | Source *source([self sourceAtIndexPath:indexPath]); | |
8413 | if (source == nil) | |
8414 | [cell setAllSource]; | |
8415 | else | |
8416 | [cell setSource:source]; | |
8417 | ||
8418 | return cell; | |
8419 | } | |
8420 | ||
8421 | - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { | |
8422 | SectionsController *controller([[[SectionsController alloc] | |
8423 | initWithDatabase:database_ | |
8424 | source:[self sourceAtIndexPath:indexPath] | |
8425 | ] autorelease]); | |
8426 | ||
8427 | [controller setDelegate:delegate_]; | |
8428 | [[self navigationController] pushViewController:controller animated:YES]; | |
8429 | } | |
8430 | ||
8431 | - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { | |
8432 | if ([indexPath section] != 1) | |
8433 | return false; | |
8434 | Source *source = [self sourceAtIndexPath:indexPath]; | |
8435 | return [source record] != nil; | |
8436 | } | |
8437 | ||
8438 | - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { | |
8439 | _assert([indexPath section] == 1); | |
8440 | if (editingStyle == UITableViewCellEditingStyleDelete) { | |
8441 | Source *source = [self sourceAtIndexPath:indexPath]; | |
8442 | if (source == nil) return; | |
8443 | ||
8444 | [Sources_ removeObjectForKey:[source key]]; | |
8445 | ||
8446 | [delegate_ _saveConfig]; | |
8447 | [delegate_ reloadDataWithInvocation:nil]; | |
8448 | } | |
8449 | } | |
8450 | ||
8451 | - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath { | |
8452 | [self updateButtonsForEditingStatusAnimated:YES]; | |
8453 | } | |
8454 | ||
8455 | - (void) complete { | |
8456 | [delegate_ addTrivialSource:href_]; | |
8457 | href_ = nil; | |
8458 | ||
8459 | [delegate_ syncData]; | |
8460 | } | |
8461 | ||
8462 | - (NSString *) getWarning { | |
8463 | NSString *href(href_); | |
8464 | NSRange colon([href rangeOfString:@"://"]); | |
8465 | if (colon.location != NSNotFound) | |
8466 | href = [href substringFromIndex:(colon.location + 3)]; | |
8467 | href = [href stringByAddingPercentEscapes]; | |
8468 | href = [CydiaURL(@"api/repotag/") stringByAppendingString:href]; | |
8469 | ||
8470 | NSURL *url([NSURL URLWithString:href]); | |
8471 | ||
8472 | NSStringEncoding encoding; | |
8473 | NSError *error(nil); | |
8474 | ||
8475 | if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error]) | |
8476 | return [warning length] == 0 ? nil : warning; | |
8477 | return nil; | |
8478 | } | |
8479 | ||
8480 | - (void) _endConnection:(NSURLConnection *)connection { | |
8481 | // XXX: the memory management in this method is horribly awkward | |
8482 | ||
8483 | NSURLConnection **field = NULL; | |
8484 | if (connection == trivial_bz2_) | |
8485 | field = &trivial_bz2_; | |
8486 | else if (connection == trivial_gz_) | |
8487 | field = &trivial_gz_; | |
8488 | _assert(field != NULL); | |
8489 | [connection release]; | |
8490 | *field = nil; | |
8491 | ||
8492 | if ( | |
8493 | trivial_bz2_ == nil && | |
8494 | trivial_gz_ == nil | |
8495 | ) { | |
8496 | NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil); | |
8497 | ||
8498 | [delegate_ releaseNetworkActivityIndicator]; | |
8499 | ||
8500 | [delegate_ removeProgressHUD:hud_]; | |
8501 | hud_ = nil; | |
8502 | ||
8503 | if (cydia_) { | |
8504 | if (warning != nil) { | |
8505 | UIAlertView *alert = [[[UIAlertView alloc] | |
8506 | initWithTitle:UCLocalize("SOURCE_WARNING") | |
8507 | message:warning | |
8508 | delegate:self | |
8509 | cancelButtonTitle:UCLocalize("CANCEL") | |
8510 | otherButtonTitles: | |
8511 | UCLocalize("ADD_ANYWAY"), | |
8512 | nil | |
8513 | ] autorelease]; | |
8514 | ||
8515 | [alert setContext:@"warning"]; | |
8516 | [alert setNumberOfRows:1]; | |
8517 | [alert show]; | |
8518 | ||
8519 | // XXX: there used to be this great mechanism called yieldToPopup... who deleted it? | |
8520 | error_ = nil; | |
8521 | return; | |
8522 | } | |
8523 | ||
8524 | [self complete]; | |
8525 | } else if (error_ != nil) { | |
8526 | UIAlertView *alert = [[[UIAlertView alloc] | |
8527 | initWithTitle:UCLocalize("VERIFICATION_ERROR") | |
8528 | message:[error_ localizedDescription] | |
8529 | delegate:self | |
8530 | cancelButtonTitle:UCLocalize("OK") | |
8531 | otherButtonTitles:nil | |
8532 | ] autorelease]; | |
8533 | ||
8534 | [alert setContext:@"urlerror"]; | |
8535 | [alert show]; | |
8536 | ||
8537 | href_ = nil; | |
8538 | } else { | |
8539 | UIAlertView *alert = [[[UIAlertView alloc] | |
8540 | initWithTitle:UCLocalize("NOT_REPOSITORY") | |
8541 | message:UCLocalize("NOT_REPOSITORY_EX") | |
8542 | delegate:self | |
8543 | cancelButtonTitle:UCLocalize("OK") | |
8544 | otherButtonTitles:nil | |
8545 | ] autorelease]; | |
8546 | ||
8547 | [alert setContext:@"trivial"]; | |
8548 | [alert show]; | |
8549 | ||
8550 | href_ = nil; | |
8551 | } | |
8552 | ||
8553 | error_ = nil; | |
8554 | } | |
8555 | } | |
8556 | ||
8557 | - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { | |
8558 | switch ([response statusCode]) { | |
8559 | case 200: | |
8560 | cydia_ = YES; | |
8561 | } | |
8562 | } | |
8563 | ||
8564 | - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { | |
8565 | lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]); | |
8566 | error_ = error; | |
8567 | [self _endConnection:connection]; | |
8568 | } | |
8569 | ||
8570 | - (void) connectionDidFinishLoading:(NSURLConnection *)connection { | |
8571 | [self _endConnection:connection]; | |
8572 | } | |
8573 | ||
8574 | - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method { | |
8575 | NSURL *url([NSURL URLWithString:href]); | |
8576 | ||
8577 | NSMutableURLRequest *request = [NSMutableURLRequest | |
8578 | requestWithURL:url | |
8579 | cachePolicy:NSURLRequestUseProtocolCachePolicy | |
8580 | timeoutInterval:10 | |
8581 | ]; | |
8582 | ||
8583 | [request setHTTPMethod:method]; | |
8584 | ||
8585 | if (Machine_ != NULL) | |
8586 | [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"]; | |
8587 | ||
8588 | if (UniqueID_ != nil) | |
8589 | [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"]; | |
8590 | ||
8591 | if ([url isCydiaSecure]) { | |
8592 | if (UniqueID_ != nil) | |
8593 | [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"]; | |
8594 | } | |
8595 | ||
8596 | return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; | |
8597 | } | |
8598 | ||
8599 | - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { | |
8600 | NSString *context([alert context]); | |
8601 | ||
8602 | if ([context isEqualToString:@"source"]) { | |
8603 | switch (button) { | |
8604 | case 1: { | |
8605 | NSString *href = [[alert textField] text]; | |
8606 | href = VerifySource(href); | |
8607 | if (href == nil) | |
8608 | break; | |
8609 | href_ = href; | |
8610 | ||
8611 | trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain]; | |
8612 | trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain]; | |
8613 | ||
8614 | cydia_ = false; | |
8615 | ||
8616 | // XXX: this is stupid | |
8617 | hud_ = [delegate_ addProgressHUD]; | |
8618 | [hud_ setText:UCLocalize("VERIFYING_URL")]; | |
8619 | [delegate_ retainNetworkActivityIndicator]; | |
8620 | } break; | |
8621 | ||
8622 | case 0: | |
8623 | break; | |
8624 | ||
8625 | _nodefault | |
8626 | } | |
8627 | ||
8628 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
8629 | } else if ([context isEqualToString:@"trivial"]) | |
8630 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
8631 | else if ([context isEqualToString:@"urlerror"]) | |
8632 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
8633 | else if ([context isEqualToString:@"warning"]) { | |
8634 | switch (button) { | |
8635 | case 1: | |
8636 | [self performSelector:@selector(complete) withObject:nil afterDelay:0]; | |
8637 | break; | |
8638 | ||
8639 | case 0: | |
8640 | break; | |
8641 | ||
8642 | _nodefault | |
8643 | } | |
8644 | ||
8645 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
8646 | } | |
8647 | } | |
8648 | ||
8649 | - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated { | |
8650 | BOOL editing([list_ isEditing]); | |
8651 | ||
8652 | if (editing) | |
8653 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
8654 | initWithTitle:UCLocalize("ADD") | |
8655 | style:UIBarButtonItemStylePlain | |
8656 | target:self | |
8657 | action:@selector(addButtonClicked) | |
8658 | ] autorelease] animated:animated]; | |
8659 | else if ([delegate_ updating]) | |
8660 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
8661 | initWithTitle:UCLocalize("CANCEL") | |
8662 | style:UIBarButtonItemStyleDone | |
8663 | target:self | |
8664 | action:@selector(cancelButtonClicked) | |
8665 | ] autorelease] animated:animated]; | |
8666 | else | |
8667 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
8668 | initWithTitle:UCLocalize("REFRESH") | |
8669 | style:UIBarButtonItemStylePlain | |
8670 | target:self | |
8671 | action:@selector(refreshButtonClicked) | |
8672 | ] autorelease] animated:animated]; | |
8673 | ||
8674 | [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] | |
8675 | initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT")) | |
8676 | style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain) | |
8677 | target:self | |
8678 | action:@selector(editButtonClicked) | |
8679 | ] autorelease] animated:animated]; | |
8680 | } | |
8681 | ||
8682 | - (void) loadView { | |
8683 | list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease]; | |
8684 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
8685 | [list_ setRowHeight:53]; | |
8686 | [(UITableView *) list_ setDataSource:self]; | |
8687 | [list_ setDelegate:self]; | |
8688 | [self setView:list_]; | |
8689 | } | |
8690 | ||
8691 | - (void) viewDidLoad { | |
8692 | [super viewDidLoad]; | |
8693 | ||
8694 | [[self navigationItem] setTitle:UCLocalize("SOURCES")]; | |
8695 | [self updateButtonsForEditingStatusAnimated:NO]; | |
8696 | } | |
8697 | ||
8698 | - (void) viewWillAppear:(BOOL)animated { | |
8699 | [super viewWillAppear:animated]; | |
8700 | ||
8701 | [list_ setEditing:NO]; | |
8702 | [self updateButtonsForEditingStatusAnimated:NO]; | |
8703 | } | |
8704 | ||
8705 | - (void) releaseSubviews { | |
8706 | list_ = nil; | |
8707 | ||
8708 | sources_ = nil; | |
8709 | ||
8710 | [super releaseSubviews]; | |
8711 | } | |
8712 | ||
8713 | - (id) initWithDatabase:(Database *)database { | |
8714 | if ((self = [super init]) != nil) { | |
8715 | database_ = database; | |
8716 | } return self; | |
8717 | } | |
8718 | ||
8719 | - (void) reloadData { | |
8720 | [super reloadData]; | |
8721 | [self updateButtonsForEditingStatusAnimated:YES]; | |
8722 | ||
8723 | @synchronized (database_) { | |
8724 | era_ = [database_ era]; | |
8725 | ||
8726 | sources_ = [NSMutableArray arrayWithCapacity:16]; | |
8727 | [sources_ addObjectsFromArray:[database_ sources]]; | |
8728 | _trace(); | |
8729 | [sources_ sortUsingSelector:@selector(compareByName:)]; | |
8730 | _trace(); | |
8731 | ||
8732 | int count([sources_ count]); | |
8733 | offset_ = 0; | |
8734 | for (int i = 0; i != count; i++) { | |
8735 | if ([[sources_ objectAtIndex:i] record] == nil) | |
8736 | break; | |
8737 | offset_++; | |
8738 | } | |
8739 | ||
8740 | [list_ reloadData]; | |
8741 | } } | |
8742 | ||
8743 | - (void) showAddSourcePrompt { | |
8744 | UIAlertView *alert = [[[UIAlertView alloc] | |
8745 | initWithTitle:UCLocalize("ENTER_APT_URL") | |
8746 | message:nil | |
8747 | delegate:self | |
8748 | cancelButtonTitle:UCLocalize("CANCEL") | |
8749 | otherButtonTitles: | |
8750 | UCLocalize("ADD_SOURCE"), | |
8751 | nil | |
8752 | ] autorelease]; | |
8753 | ||
8754 | [alert setContext:@"source"]; | |
8755 | ||
8756 | [alert setNumberOfRows:1]; | |
8757 | [alert addTextFieldWithValue:@"http://" label:@""]; | |
8758 | ||
8759 | UITextInputTraits *traits = [[alert textField] textInputTraits]; | |
8760 | [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone]; | |
8761 | [traits setAutocorrectionType:UITextAutocorrectionTypeNo]; | |
8762 | [traits setKeyboardType:UIKeyboardTypeURL]; | |
8763 | // XXX: UIReturnKeyDone | |
8764 | [traits setReturnKeyType:UIReturnKeyNext]; | |
8765 | ||
8766 | [alert show]; | |
8767 | } | |
8768 | ||
8769 | - (void) addButtonClicked { | |
8770 | [self showAddSourcePrompt]; | |
8771 | } | |
8772 | ||
8773 | - (void) refreshButtonClicked { | |
8774 | if ([delegate_ requestUpdate]) | |
8775 | [self updateButtonsForEditingStatusAnimated:YES]; | |
8776 | } | |
8777 | ||
8778 | - (void) cancelButtonClicked { | |
8779 | [delegate_ cancelUpdate]; | |
8780 | } | |
8781 | ||
8782 | - (void) editButtonClicked { | |
8783 | [list_ setEditing:![list_ isEditing] animated:YES]; | |
8784 | [self updateButtonsForEditingStatusAnimated:YES]; | |
8785 | } | |
8786 | ||
8787 | @end | |
8788 | /* }}} */ | |
8789 | ||
8790 | /* Stash Controller {{{ */ | |
8791 | @interface StashController : CyteViewController { | |
8792 | _H<UIActivityIndicatorView> spinner_; | |
8793 | _H<UILabel> status_; | |
8794 | _H<UILabel> caption_; | |
8795 | } | |
8796 | ||
8797 | @end | |
8798 | ||
8799 | @implementation StashController | |
8800 | ||
8801 | - (void) loadView { | |
8802 | UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]); | |
8803 | [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)]; | |
8804 | [self setView:view]; | |
8805 | ||
8806 | [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]]; | |
8807 | ||
8808 | spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease]; | |
8809 | CGRect spinrect = [spinner_ frame]; | |
8810 | spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2); | |
8811 | spinrect.origin.y = [[self view] frame].size.height - 80.0f; | |
8812 | [spinner_ setFrame:spinrect]; | |
8813 | [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin]; | |
8814 | [view addSubview:spinner_]; | |
8815 | [spinner_ startAnimating]; | |
8816 | ||
8817 | CGRect captrect; | |
8818 | captrect.size.width = [[self view] frame].size.width; | |
8819 | captrect.size.height = 40.0f; | |
8820 | captrect.origin.x = 0; | |
8821 | captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2); | |
8822 | caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease]; | |
8823 | [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")]; | |
8824 | [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; | |
8825 | [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]]; | |
8826 | [caption_ setTextColor:[UIColor whiteColor]]; | |
8827 | [caption_ setBackgroundColor:[UIColor clearColor]]; | |
8828 | [caption_ setShadowColor:[UIColor blackColor]]; | |
8829 | [caption_ setTextAlignment:NSTextAlignmentCenter]; | |
8830 | [view addSubview:caption_]; | |
8831 | ||
8832 | CGRect statusrect; | |
8833 | statusrect.size.width = [[self view] frame].size.width; | |
8834 | statusrect.size.height = 30.0f; | |
8835 | statusrect.origin.x = 0; | |
8836 | statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height); | |
8837 | status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease]; | |
8838 | [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; | |
8839 | [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")]; | |
8840 | [status_ setFont:[UIFont systemFontOfSize:16.0f]]; | |
8841 | [status_ setTextColor:[UIColor whiteColor]]; | |
8842 | [status_ setBackgroundColor:[UIColor clearColor]]; | |
8843 | [status_ setShadowColor:[UIColor blackColor]]; | |
8844 | [status_ setTextAlignment:NSTextAlignmentCenter]; | |
8845 | [view addSubview:status_]; | |
8846 | } | |
8847 | ||
8848 | - (void) releaseSubviews { | |
8849 | spinner_ = nil; | |
8850 | status_ = nil; | |
8851 | caption_ = nil; | |
8852 | ||
8853 | [super releaseSubviews]; | |
8854 | } | |
8855 | ||
8856 | @end | |
8857 | /* }}} */ | |
8858 | ||
8859 | @interface CYURLCache : SDURLCache { | |
8860 | } | |
8861 | ||
8862 | @end | |
8863 | ||
8864 | @implementation CYURLCache | |
8865 | ||
8866 | - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request { | |
8867 | #if !ForRelease | |
8868 | if (false); | |
8869 | else if ([event isEqualToString:@"no-cache"]) | |
8870 | event = @"!!!"; | |
8871 | else if ([event isEqualToString:@"store"]) | |
8872 | event = @">>>"; | |
8873 | else if ([event isEqualToString:@"invalid"]) | |
8874 | event = @"???"; | |
8875 | else if ([event isEqualToString:@"memory"]) | |
8876 | event = @"mem"; | |
8877 | else if ([event isEqualToString:@"disk"]) | |
8878 | event = @"ssd"; | |
8879 | else if ([event isEqualToString:@"miss"]) | |
8880 | event = @"---"; | |
8881 | ||
8882 | NSLog(@"%@: %@", event, [[request URL] absoluteString]); | |
8883 | #endif | |
8884 | } | |
8885 | ||
8886 | - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request { | |
8887 | if (NSURLResponse *response = [cached response]) | |
8888 | if (NSString *mime = [response MIMEType]) | |
8889 | if ([mime isEqualToString:@"text/cache-manifest"]) { | |
8890 | NSURL *url([response URL]); | |
8891 | ||
8892 | #if !ForRelease | |
8893 | NSLog(@"###: %@", [url absoluteString]); | |
8894 | #endif | |
8895 | ||
8896 | @synchronized (HostConfig_) { | |
8897 | [CachedURLs_ addObject:url]; | |
8898 | } | |
8899 | } | |
8900 | ||
8901 | [super storeCachedResponse:cached forRequest:request]; | |
8902 | } | |
8903 | ||
8904 | - (void) createDiskCachePath { | |
8905 | [super createDiskCachePath]; | |
8906 | } | |
8907 | ||
8908 | @end | |
8909 | ||
8910 | @interface Cydia : UIApplication < | |
8911 | ConfirmationControllerDelegate, | |
8912 | DatabaseDelegate, | |
8913 | CydiaDelegate | |
8914 | > { | |
8915 | _H<UIWindow> window_; | |
8916 | _H<CydiaTabBarController> tabbar_; | |
8917 | _H<CyteTabBarController> emulated_; | |
8918 | _H<AppCacheController> appcache_; | |
8919 | ||
8920 | _H<NSMutableArray> essential_; | |
8921 | _H<NSMutableArray> broken_; | |
8922 | ||
8923 | Database *database_; | |
8924 | ||
8925 | _H<NSURL> starturl_; | |
8926 | ||
8927 | unsigned locked_; | |
8928 | unsigned activity_; | |
8929 | ||
8930 | _H<StashController> stash_; | |
8931 | ||
8932 | bool loaded_; | |
8933 | } | |
8934 | ||
8935 | - (void) loadData; | |
8936 | ||
8937 | @end | |
8938 | ||
8939 | @implementation Cydia | |
8940 | ||
8941 | - (void) lockSuspend { | |
8942 | if (locked_++ == 0) { | |
8943 | if ($SBSSetInterceptsMenuButtonForever != NULL) | |
8944 | (*$SBSSetInterceptsMenuButtonForever)(true); | |
8945 | ||
8946 | [self setIdleTimerDisabled:YES]; | |
8947 | } | |
8948 | } | |
8949 | ||
8950 | - (void) unlockSuspend { | |
8951 | if (--locked_ == 0) { | |
8952 | [self setIdleTimerDisabled:NO]; | |
8953 | ||
8954 | if ($SBSSetInterceptsMenuButtonForever != NULL) | |
8955 | (*$SBSSetInterceptsMenuButtonForever)(false); | |
8956 | } | |
8957 | } | |
8958 | ||
8959 | - (void) beginUpdate { | |
8960 | [tabbar_ beginUpdate]; | |
8961 | } | |
8962 | ||
8963 | - (void) cancelUpdate { | |
8964 | [tabbar_ cancelUpdate]; | |
8965 | } | |
8966 | ||
8967 | - (bool) requestUpdate { | |
8968 | if (IsReachable("cydia.saurik.com")) { | |
8969 | [self beginUpdate]; | |
8970 | return true; | |
8971 | } else { | |
8972 | UIAlertView *alert = [[[UIAlertView alloc] | |
8973 | initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")] | |
8974 | message:@"Host Unreachable" // XXX: Localize | |
8975 | delegate:self | |
8976 | cancelButtonTitle:UCLocalize("OK") | |
8977 | otherButtonTitles:nil | |
8978 | ] autorelease]; | |
8979 | ||
8980 | [alert setContext:@"norefresh"]; | |
8981 | [alert show]; | |
8982 | ||
8983 | return false; | |
8984 | } | |
8985 | } | |
8986 | ||
8987 | - (BOOL) updating { | |
8988 | return [tabbar_ updating]; | |
8989 | } | |
8990 | ||
8991 | - (void) _loaded { | |
8992 | if ([broken_ count] != 0) { | |
8993 | int count = [broken_ count]; | |
8994 | ||
8995 | UIAlertView *alert = [[[UIAlertView alloc] | |
8996 | initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count]) | |
8997 | message:UCLocalize("HALFINSTALLED_PACKAGE_EX") | |
8998 | delegate:self | |
8999 | cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")] | |
9000 | otherButtonTitles: | |
9001 | UCLocalize("TEMPORARY_IGNORE"), | |
9002 | nil | |
9003 | ] autorelease]; | |
9004 | ||
9005 | [alert setContext:@"fixhalf"]; | |
9006 | [alert setNumberOfRows:2]; | |
9007 | [alert show]; | |
9008 | } else if (!Ignored_ && [essential_ count] != 0) { | |
9009 | int count = [essential_ count]; | |
9010 | ||
9011 | UIAlertView *alert = [[[UIAlertView alloc] | |
9012 | initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count]) | |
9013 | message:UCLocalize("ESSENTIAL_UPGRADE_EX") | |
9014 | delegate:self | |
9015 | cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE") | |
9016 | otherButtonTitles: | |
9017 | UCLocalize("UPGRADE_ESSENTIAL"), | |
9018 | UCLocalize("COMPLETE_UPGRADE"), | |
9019 | nil | |
9020 | ] autorelease]; | |
9021 | ||
9022 | [alert setContext:@"upgrade"]; | |
9023 | [alert show]; | |
9024 | } | |
9025 | } | |
9026 | ||
9027 | - (void) returnToCydia { | |
9028 | [self _loaded]; | |
9029 | } | |
9030 | ||
9031 | - (void) reloadSpringBoard { | |
9032 | if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x | |
9033 | system("/bin/launchctl stop com.apple.backboardd"); | |
9034 | else | |
9035 | system("/bin/launchctl stop com.apple.SpringBoard"); | |
9036 | sleep(15); | |
9037 | system("/usr/bin/killall backboardd SpringBoard"); | |
9038 | } | |
9039 | ||
9040 | - (void) _saveConfig { | |
9041 | SaveConfig(database_); | |
9042 | } | |
9043 | ||
9044 | // Navigation controller for the queuing badge. | |
9045 | - (UINavigationController *) queueNavigationController { | |
9046 | NSArray *controllers = [tabbar_ viewControllers]; | |
9047 | return [controllers objectAtIndex:3]; | |
9048 | } | |
9049 | ||
9050 | - (void) unloadData { | |
9051 | [tabbar_ unloadData]; | |
9052 | } | |
9053 | ||
9054 | - (void) _updateData { | |
9055 | [self _saveConfig]; | |
9056 | [self unloadData]; | |
9057 | ||
9058 | UINavigationController *navigation = [self queueNavigationController]; | |
9059 | ||
9060 | id queuedelegate = nil; | |
9061 | if ([[navigation viewControllers] count] > 0) | |
9062 | queuedelegate = [[navigation viewControllers] objectAtIndex:0]; | |
9063 | ||
9064 | [queuedelegate queueStatusDidChange]; | |
9065 | [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)]; | |
9066 | } | |
9067 | ||
9068 | - (void) _refreshIfPossible { | |
9069 | NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; | |
9070 | ||
9071 | NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]); | |
9072 | ||
9073 | bool recently = false; | |
9074 | if (update != nil) { | |
9075 | NSTimeInterval interval([update timeIntervalSinceNow]); | |
9076 | if (interval > -(15*60)) | |
9077 | recently = true; | |
9078 | } | |
9079 | ||
9080 | // Don't automatic refresh if: | |
9081 | // - We already refreshed recently. | |
9082 | // - We already auto-refreshed this launch. | |
9083 | // - Auto-refresh is disabled. | |
9084 | // - Cydia's server is not reachable | |
9085 | if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) { | |
9086 | // If we are cancelling, we need to make sure it knows it's already loaded. | |
9087 | loaded_ = true; | |
9088 | ||
9089 | [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO]; | |
9090 | } else { | |
9091 | // We are going to load, so remember that. | |
9092 | loaded_ = true; | |
9093 | ||
9094 | [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO]; | |
9095 | } | |
9096 | ||
9097 | [pool release]; | |
9098 | } | |
9099 | ||
9100 | - (void) refreshIfPossible { | |
9101 | [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil]; | |
9102 | } | |
9103 | ||
9104 | - (void) reloadDataWithInvocation:(NSInvocation *)invocation { | |
9105 | _profile(reloadDataWithInvocation) | |
9106 | @synchronized (self) { | |
9107 | UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil); | |
9108 | if (hud != nil) | |
9109 | [hud setText:UCLocalize("RELOADING_DATA")]; | |
9110 | ||
9111 | [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation]; | |
9112 | ||
9113 | size_t changes(0); | |
9114 | ||
9115 | [essential_ removeAllObjects]; | |
9116 | [broken_ removeAllObjects]; | |
9117 | ||
9118 | _profile(reloadDataWithInvocation$Essential) | |
9119 | NSArray *packages([database_ packages]); | |
9120 | for (Package *package in packages) { | |
9121 | if ([package half]) | |
9122 | [broken_ addObject:package]; | |
9123 | if ([package upgradableAndEssential:YES] && ![package ignored]) { | |
9124 | if ([package essential] && [package installed] != nil) | |
9125 | [essential_ addObject:package]; | |
9126 | ++changes; | |
9127 | } | |
9128 | } | |
9129 | _end | |
9130 | ||
9131 | UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem]; | |
9132 | if (changes != 0) { | |
9133 | _trace(); | |
9134 | NSString *badge([[NSNumber numberWithInt:changes] stringValue]); | |
9135 | [changesItem setBadgeValue:badge]; | |
9136 | [changesItem setAnimatedBadge:([essential_ count] > 0)]; | |
9137 | [self setApplicationIconBadgeNumber:changes]; | |
9138 | } else { | |
9139 | _trace(); | |
9140 | [changesItem setBadgeValue:nil]; | |
9141 | [changesItem setAnimatedBadge:NO]; | |
9142 | [self setApplicationIconBadgeNumber:0]; | |
9143 | } | |
9144 | ||
9145 | Queuing_ = false; | |
9146 | [self _updateData]; | |
9147 | ||
9148 | if (hud != nil) | |
9149 | [self removeProgressHUD:hud]; | |
9150 | } | |
9151 | _end | |
9152 | ||
9153 | PrintTimes(); | |
9154 | } | |
9155 | ||
9156 | - (void) updateData { | |
9157 | [self _updateData]; | |
9158 | } | |
9159 | ||
9160 | - (void) updateDataAndLoad { | |
9161 | [self _updateData]; | |
9162 | if ([database_ progressDelegate] == nil) | |
9163 | [self _loaded]; | |
9164 | } | |
9165 | ||
9166 | - (void) update_ { | |
9167 | [database_ update]; | |
9168 | [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES]; | |
9169 | } | |
9170 | ||
9171 | - (void) disemulate { | |
9172 | if (emulated_ == nil) | |
9173 | return; | |
9174 | ||
9175 | if ([window_ respondsToSelector:@selector(setRootViewController:)]) | |
9176 | [window_ setRootViewController:tabbar_]; | |
9177 | else { | |
9178 | [window_ addSubview:[tabbar_ view]]; | |
9179 | [[emulated_ view] removeFromSuperview]; | |
9180 | } | |
9181 | ||
9182 | emulated_ = nil; | |
9183 | [window_ setUserInteractionEnabled:YES]; | |
9184 | } | |
9185 | ||
9186 | - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force { | |
9187 | UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]); | |
9188 | ||
9189 | UIViewController *parent; | |
9190 | if (emulated_ == nil) | |
9191 | parent = tabbar_; | |
9192 | else if (!force) | |
9193 | parent = emulated_; | |
9194 | else { | |
9195 | [self disemulate]; | |
9196 | parent = tabbar_; | |
9197 | } | |
9198 | ||
9199 | if (IsWildcat_) | |
9200 | [navigation setModalPresentationStyle:UIModalPresentationFormSheet]; | |
9201 | [parent presentModalViewController:navigation animated:YES]; | |
9202 | } | |
9203 | ||
9204 | - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title { | |
9205 | ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]); | |
9206 | ||
9207 | if (navigation != nil) | |
9208 | [navigation pushViewController:progress animated:YES]; | |
9209 | else | |
9210 | [self presentModalViewController:progress force:YES]; | |
9211 | ||
9212 | [progress invoke:invocation withTitle:title]; | |
9213 | return progress; | |
9214 | } | |
9215 | ||
9216 | - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title { | |
9217 | [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title]; | |
9218 | } | |
9219 | ||
9220 | - (void) repairWithInvocation:(NSInvocation *)invocation { | |
9221 | _trace(); | |
9222 | [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"]; | |
9223 | _trace(); | |
9224 | } | |
9225 | ||
9226 | - (void) repairWithSelector:(SEL)selector { | |
9227 | [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES]; | |
9228 | } | |
9229 | ||
9230 | - (void) reloadData { | |
9231 | [self reloadDataWithInvocation:nil]; | |
9232 | if ([database_ progressDelegate] == nil) | |
9233 | [self _loaded]; | |
9234 | } | |
9235 | ||
9236 | - (void) syncData { | |
9237 | [self _saveConfig]; | |
9238 | [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"]; | |
9239 | } | |
9240 | ||
9241 | - (void) addSource:(NSDictionary *) source { | |
9242 | CydiaAddSource(source); | |
9243 | } | |
9244 | ||
9245 | - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections { | |
9246 | CydiaAddSource(href, distribution, sections); | |
9247 | } | |
9248 | ||
9249 | // XXX: this method should not return anything | |
9250 | - (BOOL) addTrivialSource:(NSString *)href { | |
9251 | CydiaAddSource(href, @"./"); | |
9252 | return YES; | |
9253 | } | |
9254 | ||
9255 | - (void) resolve { | |
9256 | pkgProblemResolver *resolver = [database_ resolver]; | |
9257 | ||
9258 | resolver->InstallProtect(); | |
9259 | if (!resolver->Resolve(true)) | |
9260 | _error->Discard(); | |
9261 | } | |
9262 | ||
9263 | - (bool) perform { | |
9264 | // XXX: this is a really crappy way of doing this. | |
9265 | // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that. | |
9266 | // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid | |
9267 | // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing. | |
9268 | if ([tabbar_ updating]) | |
9269 | [tabbar_ cancelUpdate]; | |
9270 | ||
9271 | if (![database_ prepare]) | |
9272 | return false; | |
9273 | ||
9274 | ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]); | |
9275 | [page setDelegate:self]; | |
9276 | UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]); | |
9277 | ||
9278 | if (IsWildcat_) | |
9279 | [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet]; | |
9280 | [tabbar_ presentModalViewController:confirm_ animated:YES]; | |
9281 | ||
9282 | return true; | |
9283 | } | |
9284 | ||
9285 | - (void) queue { | |
9286 | @synchronized (self) { | |
9287 | [self perform]; | |
9288 | } | |
9289 | } | |
9290 | ||
9291 | - (void) clearPackage:(Package *)package { | |
9292 | @synchronized (self) { | |
9293 | [package clear]; | |
9294 | [self resolve]; | |
9295 | [self perform]; | |
9296 | } | |
9297 | } | |
9298 | ||
9299 | - (void) installPackages:(NSArray *)packages { | |
9300 | @synchronized (self) { | |
9301 | for (Package *package in packages) | |
9302 | [package install]; | |
9303 | [self resolve]; | |
9304 | [self perform]; | |
9305 | } | |
9306 | } | |
9307 | ||
9308 | - (void) installPackage:(Package *)package { | |
9309 | @synchronized (self) { | |
9310 | [package install]; | |
9311 | [self resolve]; | |
9312 | [self perform]; | |
9313 | } | |
9314 | } | |
9315 | ||
9316 | - (void) removePackage:(Package *)package { | |
9317 | @synchronized (self) { | |
9318 | [package remove]; | |
9319 | [self resolve]; | |
9320 | [self perform]; | |
9321 | } | |
9322 | } | |
9323 | ||
9324 | - (void) distUpgrade { | |
9325 | @synchronized (self) { | |
9326 | if (![database_ upgrade]) | |
9327 | return; | |
9328 | [self perform]; | |
9329 | } | |
9330 | } | |
9331 | ||
9332 | - (void) _uicache { | |
9333 | _trace(); | |
9334 | system("/usr/bin/uicache"); | |
9335 | _trace(); | |
9336 | } | |
9337 | ||
9338 | - (void) uicache { | |
9339 | UIProgressHUD *hud([self addProgressHUD]); | |
9340 | [hud setText:UCLocalize("LOADING")]; | |
9341 | [self yieldToSelector:@selector(_uicache)]; | |
9342 | [self removeProgressHUD:hud]; | |
9343 | } | |
9344 | ||
9345 | - (void) perform_ { | |
9346 | [database_ perform]; | |
9347 | [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES]; | |
9348 | [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES]; | |
9349 | } | |
9350 | ||
9351 | - (void) confirmWithNavigationController:(UINavigationController *)navigation { | |
9352 | Queuing_ = false; | |
9353 | [self lockSuspend]; | |
9354 | [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"]; | |
9355 | [self unlockSuspend]; | |
9356 | } | |
9357 | ||
9358 | - (void) retainNetworkActivityIndicator { | |
9359 | if (activity_++ == 0) | |
9360 | [self setNetworkActivityIndicatorVisible:YES]; | |
9361 | ||
9362 | #if TraceLogging | |
9363 | NSLog(@"retainNetworkActivityIndicator->%d", activity_); | |
9364 | #endif | |
9365 | } | |
9366 | ||
9367 | - (void) releaseNetworkActivityIndicator { | |
9368 | if (--activity_ == 0) | |
9369 | [self setNetworkActivityIndicatorVisible:NO]; | |
9370 | ||
9371 | #if TraceLogging | |
9372 | NSLog(@"releaseNetworkActivityIndicator->%d", activity_); | |
9373 | #endif | |
9374 | ||
9375 | } | |
9376 | ||
9377 | - (void) cancelAndClear:(bool)clear { | |
9378 | @synchronized (self) { | |
9379 | if (clear) { | |
9380 | [database_ clear]; | |
9381 | Queuing_ = false; | |
9382 | } else { | |
9383 | Queuing_ = true; | |
9384 | } | |
9385 | ||
9386 | [self _updateData]; | |
9387 | } | |
9388 | } | |
9389 | ||
9390 | - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { | |
9391 | NSString *context([alert context]); | |
9392 | ||
9393 | if ([context isEqualToString:@"conffile"]) { | |
9394 | FILE *input = [database_ input]; | |
9395 | if (button == [alert cancelButtonIndex]) | |
9396 | fprintf(input, "N\n"); | |
9397 | else if (button == [alert firstOtherButtonIndex]) | |
9398 | fprintf(input, "Y\n"); | |
9399 | fflush(input); | |
9400 | ||
9401 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
9402 | } else if ([context isEqualToString:@"fixhalf"]) { | |
9403 | if (button == [alert cancelButtonIndex]) { | |
9404 | @synchronized (self) { | |
9405 | for (Package *broken in (id) broken_) { | |
9406 | [broken remove]; | |
9407 | NSString *id(ShellEscape([broken id])); | |
9408 | system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f" | |
9409 | " /var/lib/dpkg/info/%@.prerm" | |
9410 | " /var/lib/dpkg/info/%@.postrm" | |
9411 | " /var/lib/dpkg/info/%@.preinst" | |
9412 | " /var/lib/dpkg/info/%@.postinst" | |
9413 | " /var/lib/dpkg/info/%@.extrainst_" | |
9414 | "", id, id, id, id, id] UTF8String]); | |
9415 | } | |
9416 | ||
9417 | [self resolve]; | |
9418 | [self perform]; | |
9419 | } | |
9420 | } else if (button == [alert firstOtherButtonIndex]) { | |
9421 | [broken_ removeAllObjects]; | |
9422 | [self _loaded]; | |
9423 | } | |
9424 | ||
9425 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
9426 | } else if ([context isEqualToString:@"upgrade"]) { | |
9427 | if (button == [alert firstOtherButtonIndex]) { | |
9428 | @synchronized (self) { | |
9429 | for (Package *essential in (id) essential_) | |
9430 | [essential install]; | |
9431 | ||
9432 | [self resolve]; | |
9433 | [self perform]; | |
9434 | } | |
9435 | } else if (button == [alert firstOtherButtonIndex] + 1) { | |
9436 | [self distUpgrade]; | |
9437 | } else if (button == [alert cancelButtonIndex]) { | |
9438 | Ignored_ = YES; | |
9439 | } | |
9440 | ||
9441 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
9442 | } | |
9443 | } | |
9444 | ||
9445 | - (void) system:(NSString *)command { | |
9446 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
9447 | ||
9448 | _trace(); | |
9449 | system([command UTF8String]); | |
9450 | _trace(); | |
9451 | ||
9452 | [pool release]; | |
9453 | } | |
9454 | ||
9455 | - (void) applicationWillSuspend { | |
9456 | [database_ clean]; | |
9457 | [super applicationWillSuspend]; | |
9458 | } | |
9459 | ||
9460 | - (BOOL) isSafeToSuspend { | |
9461 | if (locked_ != 0) { | |
9462 | #if !ForRelease | |
9463 | NSLog(@"isSafeToSuspend: locked_ != 0"); | |
9464 | #endif | |
9465 | return false; | |
9466 | } | |
9467 | ||
9468 | if ([tabbar_ modalViewController] != nil) | |
9469 | return false; | |
9470 | ||
9471 | // Use external process status API internally. | |
9472 | // This is probably a really bad idea. | |
9473 | // XXX: what is the point of this? does this solve anything at all? | |
9474 | uint64_t status = 0; | |
9475 | int notify_token; | |
9476 | if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) { | |
9477 | notify_get_state(notify_token, &status); | |
9478 | notify_cancel(notify_token); | |
9479 | } | |
9480 | ||
9481 | if (status != 0) { | |
9482 | #if !ForRelease | |
9483 | NSLog(@"isSafeToSuspend: status != 0"); | |
9484 | #endif | |
9485 | return false; | |
9486 | } | |
9487 | ||
9488 | #if !ForRelease | |
9489 | NSLog(@"isSafeToSuspend: -> true"); | |
9490 | #endif | |
9491 | return true; | |
9492 | } | |
9493 | ||
9494 | - (void) suspendReturningToLastApp:(BOOL)returning { | |
9495 | if ([self isSafeToSuspend]) | |
9496 | [super suspendReturningToLastApp:returning]; | |
9497 | } | |
9498 | ||
9499 | - (void) suspend { | |
9500 | if ([self isSafeToSuspend]) | |
9501 | [super suspend]; | |
9502 | } | |
9503 | ||
9504 | - (void) applicationSuspend { | |
9505 | if ([self isSafeToSuspend]) | |
9506 | [super applicationSuspend]; | |
9507 | } | |
9508 | ||
9509 | - (void) applicationSuspend:(__GSEvent *)event { | |
9510 | if ([self isSafeToSuspend]) | |
9511 | [super applicationSuspend:event]; | |
9512 | } | |
9513 | ||
9514 | - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 { | |
9515 | if ([self isSafeToSuspend]) | |
9516 | [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3]; | |
9517 | } | |
9518 | ||
9519 | - (void) _setSuspended:(BOOL)value { | |
9520 | if ([self isSafeToSuspend]) | |
9521 | [super _setSuspended:value]; | |
9522 | } | |
9523 | ||
9524 | - (UIProgressHUD *) addProgressHUD { | |
9525 | UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]); | |
9526 | [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
9527 | ||
9528 | [window_ setUserInteractionEnabled:NO]; | |
9529 | ||
9530 | UIViewController *target(tabbar_); | |
9531 | if (UIViewController *modal = [target modalViewController]) | |
9532 | target = modal; | |
9533 | ||
9534 | [hud showInView:[target view]]; | |
9535 | ||
9536 | [self lockSuspend]; | |
9537 | return hud; | |
9538 | } | |
9539 | ||
9540 | - (void) removeProgressHUD:(UIProgressHUD *)hud { | |
9541 | [self unlockSuspend]; | |
9542 | [hud hide]; | |
9543 | [hud removeFromSuperview]; | |
9544 | [window_ setUserInteractionEnabled:YES]; | |
9545 | } | |
9546 | ||
9547 | - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer { | |
9548 | return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease]; | |
9549 | } | |
9550 | ||
9551 | - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer { | |
9552 | NSString *scheme([[url scheme] lowercaseString]); | |
9553 | if ([[url absoluteString] length] <= [scheme length] + 3) | |
9554 | return nil; | |
9555 | NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]); | |
9556 | NSArray *components([path componentsSeparatedByString:@"/"]); | |
9557 | ||
9558 | if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) { | |
9559 | CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]); | |
9560 | if (controller != nil) | |
9561 | [controller setDelegate:self]; | |
9562 | return controller; | |
9563 | } | |
9564 | ||
9565 | if ([components count] < 1 || ![scheme isEqualToString:@"cydia"]) | |
9566 | return nil; | |
9567 | ||
9568 | NSString *base([components objectAtIndex:0]); | |
9569 | ||
9570 | CyteViewController *controller = nil; | |
9571 | ||
9572 | if ([base isEqualToString:@"url"]) { | |
9573 | // This kind of URL can contain slashes in the argument, so we can't parse them below. | |
9574 | NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])]; | |
9575 | controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease]; | |
9576 | } else if (!external && [components count] == 1) { | |
9577 | if ([base isEqualToString:@"sources"]) { | |
9578 | controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease]; | |
9579 | } | |
9580 | ||
9581 | if ([base isEqualToString:@"home"]) { | |
9582 | controller = [[[HomeController alloc] init] autorelease]; | |
9583 | } | |
9584 | ||
9585 | if ([base isEqualToString:@"sections"]) { | |
9586 | controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease]; | |
9587 | } | |
9588 | ||
9589 | if ([base isEqualToString:@"search"]) { | |
9590 | controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease]; | |
9591 | } | |
9592 | ||
9593 | if ([base isEqualToString:@"changes"]) { | |
9594 | controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease]; | |
9595 | } | |
9596 | ||
9597 | if ([base isEqualToString:@"installed"]) { | |
9598 | controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease]; | |
9599 | } | |
9600 | } else if ([components count] == 2) { | |
9601 | NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
9602 | ||
9603 | if ([base isEqualToString:@"package"]) { | |
9604 | controller = [self pageForPackage:argument withReferrer:referrer]; | |
9605 | } | |
9606 | ||
9607 | if (!external && [base isEqualToString:@"search"]) { | |
9608 | controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease]; | |
9609 | } | |
9610 | ||
9611 | if (!external && [base isEqualToString:@"sections"]) { | |
9612 | if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"]) | |
9613 | argument = nil; | |
9614 | controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease]; | |
9615 | } | |
9616 | ||
9617 | if ([base isEqualToString:@"sources"]) { | |
9618 | if ([argument isEqualToString:@"add"]) { | |
9619 | controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease]; | |
9620 | [(SourcesController *)controller showAddSourcePrompt]; | |
9621 | } else { | |
9622 | Source *source([database_ sourceWithKey:argument]); | |
9623 | controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease]; | |
9624 | } | |
9625 | } | |
9626 | ||
9627 | if (!external && [base isEqualToString:@"launch"]) { | |
9628 | [self launchApplicationWithIdentifier:argument suspended:NO]; | |
9629 | return nil; | |
9630 | } | |
9631 | } else if (!external && [components count] == 3) { | |
9632 | NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
9633 | NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
9634 | ||
9635 | if ([base isEqualToString:@"package"]) { | |
9636 | if ([arg2 isEqualToString:@"settings"]) { | |
9637 | controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease]; | |
9638 | } else if ([arg2 isEqualToString:@"files"]) { | |
9639 | if (Package *package = [database_ packageWithName:arg1]) { | |
9640 | controller = [[[FileTable alloc] initWithDatabase:database_] autorelease]; | |
9641 | [(FileTable *)controller setPackage:package]; | |
9642 | } | |
9643 | } | |
9644 | } | |
9645 | ||
9646 | if ([base isEqualToString:@"sections"]) { | |
9647 | Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]); | |
9648 | NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2); | |
9649 | controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease]; | |
9650 | } | |
9651 | } | |
9652 | ||
9653 | [controller setDelegate:self]; | |
9654 | return controller; | |
9655 | } | |
9656 | ||
9657 | - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external { | |
9658 | CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]); | |
9659 | ||
9660 | if (page != nil) | |
9661 | [tabbar_ setUnselectedViewController:page]; | |
9662 | ||
9663 | return page != nil; | |
9664 | } | |
9665 | ||
9666 | - (void) applicationOpenURL:(NSURL *)url { | |
9667 | [super applicationOpenURL:url]; | |
9668 | ||
9669 | if (!loaded_) | |
9670 | starturl_ = url; | |
9671 | else | |
9672 | [self openCydiaURL:url forExternal:YES]; | |
9673 | } | |
9674 | ||
9675 | - (void) applicationWillResignActive:(UIApplication *)application { | |
9676 | // Stop refreshing if you get a phone call or lock the device. | |
9677 | if ([tabbar_ updating]) | |
9678 | [tabbar_ cancelUpdate]; | |
9679 | ||
9680 | if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)]) | |
9681 | [super applicationWillResignActive:application]; | |
9682 | } | |
9683 | ||
9684 | - (void) saveState { | |
9685 | [[NSDictionary dictionaryWithObjectsAndKeys: | |
9686 | @"InterfaceState", [tabbar_ navigationURLCollection], | |
9687 | @"LastClosed", [NSDate date], | |
9688 | @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]], | |
9689 | nil] writeToFile:@ SavedState_ atomically:YES]; | |
9690 | ||
9691 | [self _saveConfig]; | |
9692 | } | |
9693 | ||
9694 | - (void) applicationWillTerminate:(UIApplication *)application { | |
9695 | [self saveState]; | |
9696 | } | |
9697 | ||
9698 | - (void) applicationDidEnterBackground:(UIApplication *)application { | |
9699 | if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend]) | |
9700 | return [self terminateWithSuccess]; | |
9701 | Backgrounded_ = [NSDate date]; | |
9702 | [self saveState]; | |
9703 | } | |
9704 | ||
9705 | - (void) applicationWillEnterForeground:(UIApplication *)application { | |
9706 | if (Backgrounded_ == nil) | |
9707 | return; | |
9708 | ||
9709 | NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]); | |
9710 | ||
9711 | if (interval <= -(30*60)) { | |
9712 | [tabbar_ setSelectedIndex:0]; | |
9713 | [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO]; | |
9714 | } | |
9715 | ||
9716 | if (interval <= -(15*60)) { | |
9717 | if (IsReachable("cydia.saurik.com")) { | |
9718 | [tabbar_ beginUpdate]; | |
9719 | [appcache_ reloadURLWithCache:YES]; | |
9720 | } | |
9721 | } | |
9722 | ||
9723 | if ([database_ delocked]) | |
9724 | [self reloadData]; | |
9725 | } | |
9726 | ||
9727 | - (void) setConfigurationData:(NSString *)data { | |
9728 | static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])"); | |
9729 | ||
9730 | if (!conffile_r(data)) { | |
9731 | lprintf("E:invalid conffile\n"); | |
9732 | return; | |
9733 | } | |
9734 | ||
9735 | NSString *ofile = conffile_r[1]; | |
9736 | //NSString *nfile = conffile_r[2]; | |
9737 | ||
9738 | UIAlertView *alert = [[[UIAlertView alloc] | |
9739 | initWithTitle:UCLocalize("CONFIGURATION_UPGRADE") | |
9740 | message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile] | |
9741 | delegate:self | |
9742 | cancelButtonTitle:UCLocalize("KEEP_OLD_COPY") | |
9743 | otherButtonTitles: | |
9744 | UCLocalize("ACCEPT_NEW_COPY"), | |
9745 | // XXX: UCLocalize("SEE_WHAT_CHANGED"), | |
9746 | nil | |
9747 | ] autorelease]; | |
9748 | ||
9749 | [alert setContext:@"conffile"]; | |
9750 | [alert setNumberOfRows:2]; | |
9751 | [alert show]; | |
9752 | } | |
9753 | ||
9754 | - (void) addStashController { | |
9755 | [self lockSuspend]; | |
9756 | stash_ = [[[StashController alloc] init] autorelease]; | |
9757 | [window_ addSubview:[stash_ view]]; | |
9758 | } | |
9759 | ||
9760 | - (void) removeStashController { | |
9761 | [[stash_ view] removeFromSuperview]; | |
9762 | stash_ = nil; | |
9763 | [self unlockSuspend]; | |
9764 | } | |
9765 | ||
9766 | - (void) stash { | |
9767 | [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque]; | |
9768 | UpdateExternalStatus(1); | |
9769 | [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"]; | |
9770 | UpdateExternalStatus(0); | |
9771 | ||
9772 | [self removeStashController]; | |
9773 | [self reloadSpringBoard]; | |
9774 | } | |
9775 | ||
9776 | - (void) setupViewControllers { | |
9777 | tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease]; | |
9778 | ||
9779 | NSMutableArray *items; | |
9780 | if (kCFCoreFoundationVersionNumber < 800) { | |
9781 | items = [NSMutableArray arrayWithObjects: | |
9782 | [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease], | |
9783 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease], | |
9784 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease], | |
9785 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease], | |
9786 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease], | |
9787 | nil]; | |
9788 | } else { | |
9789 | items = [NSMutableArray arrayWithObjects: | |
9790 | [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease], | |
9791 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease], | |
9792 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease], | |
9793 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease], | |
9794 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease], | |
9795 | nil]; | |
9796 | } | |
9797 | ||
9798 | NSMutableArray *controllers([NSMutableArray array]); | |
9799 | for (UITabBarItem *item in items) { | |
9800 | UINavigationController *controller([[[UINavigationController alloc] init] autorelease]); | |
9801 | [controller setTabBarItem:item]; | |
9802 | [controllers addObject:controller]; | |
9803 | } | |
9804 | [tabbar_ setViewControllers:controllers]; | |
9805 | ||
9806 | [tabbar_ setUpdateDelegate:self]; | |
9807 | } | |
9808 | ||
9809 | - (void) _sendMemoryWarningNotification { | |
9810 | if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0? | |
9811 | [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]]; | |
9812 | else | |
9813 | [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]]; | |
9814 | } | |
9815 | ||
9816 | - (void) _sendMemoryWarningNotifications { | |
9817 | while (true) { | |
9818 | [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO]; | |
9819 | sleep(2); | |
9820 | //usleep(2000000); | |
9821 | } | |
9822 | } | |
9823 | ||
9824 | - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application { | |
9825 | NSLog(@"--"); | |
9826 | [[NSURLCache sharedURLCache] removeAllCachedResponses]; | |
9827 | } | |
9828 | ||
9829 | - (void) applicationDidFinishLaunching:(id)unused { | |
9830 | //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil]; | |
9831 | ||
9832 | _trace(); | |
9833 | if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)]) | |
9834 | [self setApplicationSupportsShakeToEdit:NO]; | |
9835 | ||
9836 | @synchronized (HostConfig_) { | |
9837 | [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]]; | |
9838 | } | |
9839 | ||
9840 | [NSURLCache setSharedURLCache:[[[CYURLCache alloc] | |
9841 | initWithMemoryCapacity:524288 | |
9842 | diskCapacity:10485760 | |
9843 | diskPath:Cache("SDURLCache") | |
9844 | ] autorelease]]; | |
9845 | ||
9846 | [CydiaWebViewController _initialize]; | |
9847 | ||
9848 | [NSURLProtocol registerClass:[CydiaURLProtocol class]]; | |
9849 | ||
9850 | // this would disallow http{,s} URLs from accessing this data | |
9851 | //[WebView registerURLSchemeAsLocal:@"cydia"]; | |
9852 | ||
9853 | Font12_ = [UIFont systemFontOfSize:12]; | |
9854 | Font12Bold_ = [UIFont boldSystemFontOfSize:12]; | |
9855 | Font14_ = [UIFont systemFontOfSize:14]; | |
9856 | Font18_ = [UIFont systemFontOfSize:18]; | |
9857 | Font18Bold_ = [UIFont boldSystemFontOfSize:18]; | |
9858 | Font22Bold_ = [UIFont boldSystemFontOfSize:22]; | |
9859 | ||
9860 | essential_ = [NSMutableArray arrayWithCapacity:4]; | |
9861 | broken_ = [NSMutableArray arrayWithCapacity:4]; | |
9862 | ||
9863 | // XXX: I really need this thing... like, seriously... I'm sorry | |
9864 | appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease]; | |
9865 | [appcache_ reloadData]; | |
9866 | ||
9867 | window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; | |
9868 | [window_ orderFront:self]; | |
9869 | [window_ makeKey:self]; | |
9870 | [window_ setHidden:NO]; | |
9871 | ||
9872 | if (false) stash: { | |
9873 | [self addStashController]; | |
9874 | // XXX: this would be much cleaner as a yieldToSelector: | |
9875 | // that way the removeStashController could happen right here inline | |
9876 | // we also could no longer require the useless stash_ field anymore | |
9877 | [self performSelector:@selector(stash) withObject:nil afterDelay:0]; | |
9878 | return; | |
9879 | } | |
9880 | ||
9881 | struct stat root; | |
9882 | int error(stat("/", &root)); | |
9883 | _assert(error != -1); | |
9884 | ||
9885 | #define Stash_(path) do { \ | |
9886 | struct stat folder; \ | |
9887 | int error(lstat((path), &folder)); \ | |
9888 | if (error != -1 && ( \ | |
9889 | folder.st_dev == root.st_dev && \ | |
9890 | S_ISDIR(folder.st_mode) \ | |
9891 | ) || error == -1 && ( \ | |
9892 | errno == ENOENT || \ | |
9893 | errno == ENOTDIR \ | |
9894 | )) goto stash; \ | |
9895 | } while (false) | |
9896 | ||
9897 | Stash_("/Applications"); | |
9898 | Stash_("/Library/Ringtones"); | |
9899 | Stash_("/Library/Wallpaper"); | |
9900 | //Stash_("/usr/bin"); | |
9901 | Stash_("/usr/include"); | |
9902 | Stash_("/usr/share"); | |
9903 | //Stash_("/var/lib"); | |
9904 | ||
9905 | database_ = [Database sharedInstance]; | |
9906 | [database_ setDelegate:self]; | |
9907 | ||
9908 | [window_ setUserInteractionEnabled:NO]; | |
9909 | [self setupViewControllers]; | |
9910 | ||
9911 | CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]); | |
9912 | UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]); | |
9913 | [navigation setViewControllers:[NSArray arrayWithObject:loading]]; | |
9914 | ||
9915 | emulated_ = [[[CyteTabBarController alloc] init] autorelease]; | |
9916 | [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]]; | |
9917 | [emulated_ setSelectedIndex:0]; | |
9918 | ||
9919 | if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)]) | |
9920 | [emulated_ concealTabBarSelection]; | |
9921 | ||
9922 | if ([window_ respondsToSelector:@selector(setRootViewController:)]) | |
9923 | [window_ setRootViewController:emulated_]; | |
9924 | else | |
9925 | [window_ addSubview:[emulated_ view]]; | |
9926 | ||
9927 | [self performSelector:@selector(loadData) withObject:nil afterDelay:0]; | |
9928 | _trace(); | |
9929 | } | |
9930 | ||
9931 | - (NSArray *) defaultStartPages { | |
9932 | NSMutableArray *standard = [NSMutableArray array]; | |
9933 | [standard addObject:[NSArray arrayWithObject:@"cydia://home"]]; | |
9934 | [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]]; | |
9935 | [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]]; | |
9936 | [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]]; | |
9937 | [standard addObject:[NSArray arrayWithObject:@"cydia://search"]]; | |
9938 | return standard; | |
9939 | } | |
9940 | ||
9941 | - (void) loadData { | |
9942 | _trace(); | |
9943 | if ([emulated_ modalViewController] != nil) | |
9944 | [emulated_ dismissModalViewControllerAnimated:YES]; | |
9945 | [window_ setUserInteractionEnabled:NO]; | |
9946 | ||
9947 | [self reloadDataWithInvocation:nil]; | |
9948 | [self refreshIfPossible]; | |
9949 | [self disemulate]; | |
9950 | ||
9951 | NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]); | |
9952 | ||
9953 | int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue]; | |
9954 | NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease]; | |
9955 | int standardIndex = 0; | |
9956 | NSArray *standard = [self defaultStartPages]; | |
9957 | ||
9958 | BOOL valid = YES; | |
9959 | ||
9960 | if (saved == nil) | |
9961 | valid = NO; | |
9962 | ||
9963 | NSDate *closed = [state objectForKey:@"LastClosed"]; | |
9964 | if (valid && closed != nil) { | |
9965 | NSTimeInterval interval([closed timeIntervalSinceNow]); | |
9966 | if (interval <= -(30*60)) | |
9967 | valid = NO; | |
9968 | } | |
9969 | ||
9970 | if (valid && [saved count] != [standard count]) | |
9971 | valid = NO; | |
9972 | ||
9973 | if (valid) { | |
9974 | for (unsigned int i = 0; i < [standard count]; i++) { | |
9975 | NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i]; | |
9976 | // XXX: The "hasPrefix" sanity check here could be, in theory, fooled, | |
9977 | // but it's good enough for now. | |
9978 | if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) { | |
9979 | valid = NO; | |
9980 | break; | |
9981 | } | |
9982 | } | |
9983 | } | |
9984 | ||
9985 | NSArray *items = nil; | |
9986 | if (valid) { | |
9987 | [tabbar_ setSelectedIndex:savedIndex]; | |
9988 | items = saved; | |
9989 | } else { | |
9990 | [tabbar_ setSelectedIndex:standardIndex]; | |
9991 | items = standard; | |
9992 | } | |
9993 | ||
9994 | for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) { | |
9995 | NSArray *stack = [items objectAtIndex:tab]; | |
9996 | UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab]; | |
9997 | NSMutableArray *current = [NSMutableArray array]; | |
9998 | ||
9999 | for (unsigned int nav = 0; nav < [stack count]; nav++) { | |
10000 | NSString *addr = [stack objectAtIndex:nav]; | |
10001 | NSURL *url = [NSURL URLWithString:addr]; | |
10002 | CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil]; | |
10003 | if (page != nil) | |
10004 | [current addObject:page]; | |
10005 | } | |
10006 | ||
10007 | [navigation setViewControllers:current]; | |
10008 | } | |
10009 | ||
10010 | // (Try to) show the startup URL. | |
10011 | if (starturl_ != nil) { | |
10012 | [self openCydiaURL:starturl_ forExternal:YES]; | |
10013 | starturl_ = nil; | |
10014 | } | |
10015 | } | |
10016 | ||
10017 | - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item { | |
10018 | if (item != nil && IsWildcat_) { | |
10019 | [sheet showFromBarButtonItem:item animated:YES]; | |
10020 | } else { | |
10021 | [sheet showInView:window_]; | |
10022 | } | |
10023 | } | |
10024 | ||
10025 | - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task { | |
10026 | id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]); | |
10027 | [progress setTitle:task]; | |
10028 | [progress addProgressEvent:event]; | |
10029 | } | |
10030 | ||
10031 | - (void) addProgressEventForTask:(NSArray *)data { | |
10032 | CydiaProgressEvent *event([data objectAtIndex:0]); | |
10033 | NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]); | |
10034 | [self addProgressEvent:event forTask:task]; | |
10035 | } | |
10036 | ||
10037 | - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task { | |
10038 | [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES]; | |
10039 | } | |
10040 | ||
10041 | @end | |
10042 | ||
10043 | /*IMP alloc_; | |
10044 | id Alloc_(id self, SEL selector) { | |
10045 | id object = alloc_(self, selector); | |
10046 | lprintf("[%s]A-%p\n", self->isa->name, object); | |
10047 | return object; | |
10048 | }*/ | |
10049 | ||
10050 | /*IMP dealloc_; | |
10051 | id Dealloc_(id self, SEL selector) { | |
10052 | id object = dealloc_(self, selector); | |
10053 | lprintf("[%s]D-%p\n", self->isa->name, object); | |
10054 | return object; | |
10055 | }*/ | |
10056 | ||
10057 | Class $NSURLConnection; | |
10058 | ||
10059 | MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) { | |
10060 | NSMutableURLRequest *copy([[request mutableCopy] autorelease]); | |
10061 | ||
10062 | NSURL *url([copy URL]); | |
10063 | ||
10064 | NSString *host([url host]); | |
10065 | NSString *scheme([[url scheme] lowercaseString]); | |
10066 | ||
10067 | NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]); | |
10068 | ||
10069 | @synchronized (HostConfig_) { | |
10070 | if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)]) | |
10071 | if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound]) | |
10072 | [copy setHTTPShouldUsePipelining:YES]; | |
10073 | ||
10074 | if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"]) | |
10075 | if ([control isEqualToString:@"max-age=0"]) | |
10076 | if ([CachedURLs_ containsObject:url]) { | |
10077 | #if !ForRelease | |
10078 | NSLog(@"~~~: %@", url); | |
10079 | #endif | |
10080 | ||
10081 | [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; | |
10082 | ||
10083 | [copy setValue:nil forHTTPHeaderField:@"Cache-Control"]; | |
10084 | [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"]; | |
10085 | [copy setValue:nil forHTTPHeaderField:@"If-None-Match"]; | |
10086 | } | |
10087 | } | |
10088 | ||
10089 | if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) { | |
10090 | } return self; | |
10091 | } | |
10092 | ||
10093 | Class $WAKWindow; | |
10094 | ||
10095 | static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) { | |
10096 | CGSize size([[UIScreen mainScreen] bounds].size); | |
10097 | /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)]) | |
10098 | if ([$WAKWindow hasLandscapeOrientation]) | |
10099 | std::swap(size.width, size.height);*/ | |
10100 | return size; | |
10101 | } | |
10102 | ||
10103 | Class $NSUserDefaults; | |
10104 | ||
10105 | MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) { | |
10106 | if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"]) | |
10107 | return Cache("LocalStorage"); | |
10108 | return _NSUserDefaults$objectForKey$(self, _cmd, key); | |
10109 | } | |
10110 | ||
10111 | static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) { | |
10112 | if (type == NULL) | |
10113 | return nil; | |
10114 | if (CFGetTypeID(type) != CFDictionaryGetTypeID()) | |
10115 | return nil; | |
10116 | CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers)); | |
10117 | CFRelease(type); | |
10118 | return [(NSMutableDictionary *) copy autorelease]; | |
10119 | } | |
10120 | ||
10121 | int main(int argc, char *argv[]) { | |
10122 | int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644)); | |
10123 | dup2(fd, 2); | |
10124 | close(fd); | |
10125 | ||
10126 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
10127 | ||
10128 | _trace(); | |
10129 | ||
10130 | UpdateExternalStatus(0); | |
10131 | ||
10132 | UIScreen *screen([UIScreen mainScreen]); | |
10133 | if ([screen respondsToSelector:@selector(scale)]) | |
10134 | ScreenScale_ = [screen scale]; | |
10135 | else | |
10136 | ScreenScale_ = 1; | |
10137 | ||
10138 | UIDevice *device([UIDevice currentDevice]); | |
10139 | if ([device respondsToSelector:@selector(userInterfaceIdiom)]) { | |
10140 | UIUserInterfaceIdiom idiom([device userInterfaceIdiom]); | |
10141 | if (idiom == UIUserInterfaceIdiomPad) | |
10142 | IsWildcat_ = true; | |
10143 | } | |
10144 | ||
10145 | Idiom_ = IsWildcat_ ? @"ipad" : @"iphone"; | |
10146 | ||
10147 | RegEx pattern("([0-9]+\\.[0-9]+).*"); | |
10148 | ||
10149 | if (pattern([device systemVersion])) | |
10150 | Firmware_ = pattern[1]; | |
10151 | if (pattern(Cydia_)) | |
10152 | Major_ = pattern[1]; | |
10153 | ||
10154 | SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4]; | |
10155 | ||
10156 | HostConfig_ = [[[NSObject alloc] init] autorelease]; | |
10157 | @synchronized (HostConfig_) { | |
10158 | BridgedHosts_ = [NSMutableSet setWithCapacity:4]; | |
10159 | InsecureHosts_ = [NSMutableSet setWithCapacity:4]; | |
10160 | PipelinedHosts_ = [NSMutableSet setWithCapacity:4]; | |
10161 | CachedURLs_ = [NSMutableSet setWithCapacity:32]; | |
10162 | } | |
10163 | ||
10164 | NSString *ui(@"ui/ios"); | |
10165 | if (Idiom_ != nil) | |
10166 | ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]]; | |
10167 | ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]]; | |
10168 | UI_ = CydiaURL(ui); | |
10169 | ||
10170 | PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname)))); | |
10171 | ||
10172 | /* Library Hacks {{{ */ | |
10173 | class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16"); | |
10174 | ||
10175 | $WAKWindow = objc_getClass("WAKWindow"); | |
10176 | if ($WAKWindow != NULL) | |
10177 | if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize))) | |
10178 | method_setImplementation(method, (IMP) &$WAKWindow$screenSize); | |
10179 | ||
10180 | $NSURLConnection = objc_getClass("NSURLConnection"); | |
10181 | Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:))); | |
10182 | if (NSURLConnection$init$ != NULL) { | |
10183 | _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$)); | |
10184 | method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$)); | |
10185 | } | |
10186 | ||
10187 | $NSUserDefaults = objc_getClass("NSUserDefaults"); | |
10188 | Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:))); | |
10189 | if (NSUserDefaults$objectForKey$ != NULL) { | |
10190 | _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$)); | |
10191 | method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$)); | |
10192 | } | |
10193 | /* }}} */ | |
10194 | /* Set Locale {{{ */ | |
10195 | Locale_ = CFLocaleCopyCurrent(); | |
10196 | Languages_ = [NSLocale preferredLanguages]; | |
10197 | ||
10198 | //CFStringRef locale(CFLocaleGetIdentifier(Locale_)); | |
10199 | //NSLog(@"%@", [Languages_ description]); | |
10200 | ||
10201 | const char *lang; | |
10202 | if (Locale_ != NULL) | |
10203 | lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]; | |
10204 | else if (Languages_ != nil && [Languages_ count] != 0) | |
10205 | lang = [[Languages_ objectAtIndex:0] UTF8String]; | |
10206 | else | |
10207 | // XXX: consider just setting to C and then falling through? | |
10208 | lang = NULL; | |
10209 | ||
10210 | if (lang != NULL) { | |
10211 | RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?"); | |
10212 | lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String]; | |
10213 | } | |
10214 | ||
10215 | NSLog(@"Setting Language: %s", lang); | |
10216 | ||
10217 | if (lang != NULL) { | |
10218 | setenv("LANG", lang, true); | |
10219 | std::setlocale(LC_ALL, lang); | |
10220 | } | |
10221 | /* }}} */ | |
10222 | /* Index Collation {{{ */ | |
10223 | if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try { | |
10224 | NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]); | |
10225 | NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]); | |
10226 | //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist"; | |
10227 | NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]); | |
10228 | _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]); | |
10229 | ||
10230 | CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale"); | |
10231 | ||
10232 | if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) { | |
10233 | CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil]; | |
10234 | for (NSInteger offset : (NSInteger[]) {0,1,3,4,6,7,9,10,12,13,15,16,18,25,26,29,30,33,34,37,38,42,43,46,47,50,51}) | |
10235 | CollationOffset_.push_back(offset); | |
10236 | CollationTitles_ = [NSArray arrayWithObjects:@"1 畫",@"2 畫",@"3 畫",@"4 畫",@"5 畫",@"6 畫",@"7 畫",@"8 畫",@"9 畫",@"10 畫",@"11 畫",@"12 畫",@"13 畫",@"14 畫",@"15 畫",@"16 畫",@"17 畫",@"18 畫",@"19 畫",@"20 畫",@"21 畫",@"22 畫",@"23 畫",@"24 畫",@"25 畫以上",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil]; | |
10237 | CollationStarts_ = [NSArray arrayWithObjects:@"一",@"丁",@"丈",@"不",@"且",@"丞",@"串",@"並",@"亭",@"乘",@"乾",@"傀",@"亂",@"僎",@"僵",@"儐",@"償",@"叢",@"儳",@"嚴",@"儷",@"儻",@"囌",@"囑",@"廳",@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"ʒ",nil]; | |
10238 | } else { | |
10239 | ||
10240 | CollationThumbs_ = [collation sectionIndexTitles]; | |
10241 | for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index) | |
10242 | CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]); | |
10243 | ||
10244 | CollationTitles_ = [collation sectionTitles]; | |
10245 | CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings"); | |
10246 | ||
10247 | NSString *&transform(MSHookIvar<NSString *>(collation, "_transform")); | |
10248 | if (&transform != NULL && transform != nil) { | |
10249 | /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)]) | |
10250 | CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/ | |
10251 | const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding])); | |
10252 | UErrorCode code(U_ZERO_ERROR); | |
10253 | CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code); | |
10254 | if (!U_SUCCESS(code)) | |
10255 | NSLog(@"%s", u_errorName(code)); | |
10256 | } | |
10257 | ||
10258 | } | |
10259 | } @catch (NSException *e) { | |
10260 | NSLog(@"%@", e); | |
10261 | goto hard; | |
10262 | } } else hard: { | |
10263 | CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease]; | |
10264 | ||
10265 | CollationThumbs_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil]; | |
10266 | for (NSInteger offset(0); offset != 28; ++offset) | |
10267 | CollationOffset_.push_back(offset); | |
10268 | ||
10269 | CollationTitles_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil]; | |
10270 | CollationStarts_ = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"ʒ",nil]; | |
10271 | } | |
10272 | /* }}} */ | |
10273 | /* Parse Arguments {{{ */ | |
10274 | bool substrate(false); | |
10275 | ||
10276 | if (argc != 0) { | |
10277 | char **args(argv); | |
10278 | int arge(1); | |
10279 | ||
10280 | for (int argi(1); argi != argc; ++argi) | |
10281 | if (strcmp(argv[argi], "--") == 0) { | |
10282 | arge = argi; | |
10283 | argv[argi] = argv[0]; | |
10284 | argv += argi; | |
10285 | argc -= argi; | |
10286 | break; | |
10287 | } | |
10288 | ||
10289 | for (int argi(1); argi != arge; ++argi) | |
10290 | if (strcmp(args[argi], "--substrate") == 0) | |
10291 | substrate = true; | |
10292 | else | |
10293 | fprintf(stderr, "unknown argument: %s\n", args[argi]); | |
10294 | } | |
10295 | /* }}} */ | |
10296 | ||
10297 | App_ = [[NSBundle mainBundle] bundlePath]; | |
10298 | Advanced_ = YES; | |
10299 | ||
10300 | Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain]; | |
10301 | ||
10302 | /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc)); | |
10303 | alloc_ = alloc->method_imp; | |
10304 | alloc->method_imp = (IMP) &Alloc_;*/ | |
10305 | ||
10306 | /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc)); | |
10307 | dealloc_ = dealloc->method_imp; | |
10308 | dealloc->method_imp = (IMP) &Dealloc_;*/ | |
10309 | ||
10310 | void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY)); | |
10311 | $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer")); | |
10312 | ||
10313 | /* System Information {{{ */ | |
10314 | size_t size; | |
10315 | ||
10316 | int maxproc; | |
10317 | size = sizeof(maxproc); | |
10318 | if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1) | |
10319 | perror("sysctlbyname(\"kern.maxproc\", ?)"); | |
10320 | else if (maxproc < 64) { | |
10321 | maxproc = 64; | |
10322 | if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1) | |
10323 | perror("sysctlbyname(\"kern.maxproc\", #)"); | |
10324 | } | |
10325 | ||
10326 | sysctlbyname("kern.osversion", NULL, &size, NULL, 0); | |
10327 | char *osversion = new char[size]; | |
10328 | if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1) | |
10329 | perror("sysctlbyname(\"kern.osversion\", ?)"); | |
10330 | else | |
10331 | System_ = [NSString stringWithUTF8String:osversion]; | |
10332 | ||
10333 | sysctlbyname("hw.machine", NULL, &size, NULL, 0); | |
10334 | char *machine = new char[size]; | |
10335 | if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1) | |
10336 | perror("sysctlbyname(\"hw.machine\", ?)"); | |
10337 | else | |
10338 | Machine_ = machine; | |
10339 | ||
10340 | int64_t usermem(0); | |
10341 | size = sizeof(usermem); | |
10342 | if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1) | |
10343 | usermem = 0; | |
10344 | ||
10345 | SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber"); | |
10346 | ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString]; | |
10347 | BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false); | |
10348 | ||
10349 | UniqueID_ = UniqueIdentifier(device); | |
10350 | ||
10351 | if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) { | |
10352 | Product_ = [info objectForKey:@"SafariProductVersion"]; | |
10353 | Safari_ = [info objectForKey:@"CFBundleVersion"]; | |
10354 | } | |
10355 | ||
10356 | NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]); | |
10357 | ||
10358 | if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_)) | |
10359 | agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent]; | |
10360 | if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_)) | |
10361 | agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent]; | |
10362 | if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_)) | |
10363 | agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent]; | |
10364 | ||
10365 | UserAgent_ = agent; | |
10366 | /* }}} */ | |
10367 | /* Load Database {{{ */ | |
10368 | SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease]; | |
10369 | ||
10370 | _trace(); | |
10371 | mkdir("/var/mobile/Library/Cydia", 0755); | |
10372 | MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0"); | |
10373 | _trace(); | |
10374 | ||
10375 | Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia"))); | |
10376 | Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia"))); | |
10377 | Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia"))); | |
10378 | Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease]; | |
10379 | ||
10380 | _trace(); | |
10381 | NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]); | |
10382 | ||
10383 | if (Values_ == nil) | |
10384 | Values_ = [metadata objectForKey:@"Values"]; | |
10385 | if (Values_ == nil) | |
10386 | Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease]; | |
10387 | ||
10388 | if (Sections_ == nil) | |
10389 | Sections_ = [metadata objectForKey:@"Sections"]; | |
10390 | if (Sections_ == nil) | |
10391 | Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease]; | |
10392 | ||
10393 | if (Sources_ == nil) | |
10394 | Sources_ = [metadata objectForKey:@"Sources"]; | |
10395 | if (Sources_ == nil) | |
10396 | Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease]; | |
10397 | ||
10398 | // XXX: this wrong, but in a way that doesn't matter :/ | |
10399 | if (Version_ == nil) | |
10400 | Version_ = [metadata objectForKey:@"Version"]; | |
10401 | if (Version_ == nil) | |
10402 | Version_ = [NSNumber numberWithUnsignedInt:0]; | |
10403 | ||
10404 | if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) { | |
10405 | bool fail(false); | |
10406 | CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail); | |
10407 | _trace(); | |
10408 | if (fail) | |
10409 | NSLog(@"unable to import package preferences... from 2010? oh well :/"); | |
10410 | } | |
10411 | ||
10412 | if ([Version_ unsignedIntValue] == 0) { | |
10413 | CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]); | |
10414 | CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]); | |
10415 | CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]); | |
10416 | CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./"); | |
10417 | ||
10418 | Version_ = [NSNumber numberWithUnsignedInt:1]; | |
10419 | ||
10420 | if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) { | |
10421 | [cache removeObjectForKey:@"LastUpdate"]; | |
10422 | [cache writeToFile:@ CacheState_ atomically:YES]; | |
10423 | } | |
10424 | } | |
10425 | ||
10426 | _H<NSMutableArray> broken([NSMutableArray array]); | |
10427 | for (NSString *key in (id) Sources_) | |
10428 | if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"]) | |
10429 | [broken addObject:key]; | |
10430 | if ([broken count] != 0) | |
10431 | for (NSString *key in (id) broken) | |
10432 | [Sources_ removeObjectForKey:key]; | |
10433 | broken = nil; | |
10434 | ||
10435 | SaveConfig(nil); | |
10436 | system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist"); | |
10437 | /* }}} */ | |
10438 | ||
10439 | Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil]; | |
10440 | ||
10441 | if (kCFCoreFoundationVersionNumber > 1000) | |
10442 | system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib"); | |
10443 | ||
10444 | int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]); | |
10445 | ||
10446 | if (access("/User", F_OK) != 0 || version != 6) { | |
10447 | _trace(); | |
10448 | system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh"); | |
10449 | _trace(); | |
10450 | } | |
10451 | ||
10452 | if (access("/tmp/cydia.chk", F_OK) == 0) { | |
10453 | if (unlink([Cache("pkgcache.bin") UTF8String]) == -1) | |
10454 | _assert(errno == ENOENT); | |
10455 | if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1) | |
10456 | _assert(errno == ENOENT); | |
10457 | } | |
10458 | ||
10459 | system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list"); | |
10460 | ||
10461 | /* APT Initialization {{{ */ | |
10462 | _assert(pkgInitConfig(*_config)); | |
10463 | _assert(pkgInitSystem(*_config, _system)); | |
10464 | ||
10465 | if (lang != NULL) | |
10466 | _config->Set("APT::Acquire::Translation", lang); | |
10467 | ||
10468 | // XXX: this timeout might be important :( | |
10469 | //_config->Set("Acquire::http::Timeout", 15); | |
10470 | ||
10471 | _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3); | |
10472 | ||
10473 | mkdir([Cache_ UTF8String], 0755); | |
10474 | mkdir([Cache("archives") UTF8String], 0755); | |
10475 | mkdir([Cache("archives/partial") UTF8String], 0755); | |
10476 | _config->Set("Dir::Cache", [Cache_ UTF8String]); | |
10477 | ||
10478 | symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]); | |
10479 | _config->Set("Dir::State", [Cache_ UTF8String]); | |
10480 | ||
10481 | mkdir([Cache("lists") UTF8String], 0755); | |
10482 | mkdir([Cache("lists/partial") UTF8String], 0755); | |
10483 | mkdir([Cache("periodic") UTF8String], 0755); | |
10484 | _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]); | |
10485 | ||
10486 | std::string logs("/var/mobile/Library/Logs/Cydia"); | |
10487 | mkdir(logs.c_str(), 0755); | |
10488 | _config->Set("Dir::Log::Terminal", logs + "/apt.log"); | |
10489 | ||
10490 | _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo"); | |
10491 | /* }}} */ | |
10492 | /* Color Choices {{{ */ | |
10493 | space_ = CGColorSpaceCreateDeviceRGB(); | |
10494 | ||
10495 | Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0); | |
10496 | Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0); | |
10497 | Black_.Set(space_, 0.0, 0.0, 0.0, 1.0); | |
10498 | Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0); | |
10499 | Off_.Set(space_, 0.9, 0.9, 0.9, 1.0); | |
10500 | White_.Set(space_, 1.0, 1.0, 1.0, 1.0); | |
10501 | Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0); | |
10502 | Green_.Set(space_, 0.0, 0.5, 0.0, 1.0); | |
10503 | Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0); | |
10504 | Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0); | |
10505 | ||
10506 | InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f]; | |
10507 | RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f]; | |
10508 | /* }}}*/ | |
10509 | /* UIKit Configuration {{{ */ | |
10510 | // XXX: I have a feeling this was important | |
10511 | //UIKeyboardDisableAutomaticAppearance(); | |
10512 | /* }}} */ | |
10513 | ||
10514 | $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever")); | |
10515 | $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier")); | |
10516 | ||
10517 | const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability"); | |
10518 | BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol)); | |
10519 | bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7")); | |
10520 | ||
10521 | PulseInterval_ = fast ? 50000 : 500000; | |
10522 | ||
10523 | Colon_ = UCLocalize("COLON_DELIMITED"); | |
10524 | Elision_ = UCLocalize("ELISION"); | |
10525 | Error_ = UCLocalize("ERROR"); | |
10526 | Warning_ = UCLocalize("WARNING"); | |
10527 | ||
10528 | _trace(); | |
10529 | int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia")); | |
10530 | ||
10531 | CGColorSpaceRelease(space_); | |
10532 | CFRelease(Locale_); | |
10533 | ||
10534 | [pool release]; | |
10535 | return value; | |
10536 | } |