|
1 |
| -use std::{path::PathBuf, ptr::null_mut}; |
| 1 | +use std::{env::current_dir, ptr::null_mut}; |
2 | 2 |
|
3 | 3 | use objc2::{rc::Retained, runtime::ProtocolObject, DeclaredClass};
|
4 | 4 | use objc2_foundation::{NSData, NSError, NSString, NSURLResponse, NSURL};
|
@@ -47,20 +47,36 @@ pub(crate) fn download_policy(
|
47 | 47 | this: &WryDownloadDelegate,
|
48 | 48 | download: &WKDownload,
|
49 | 49 | _response: &NSURLResponse,
|
50 |
| - suggested_path: &NSString, |
| 50 | + suggested_filename: &NSString, |
51 | 51 | completion_handler: &block2::Block<dyn Fn(*const NSURL)>,
|
52 | 52 | ) {
|
53 | 53 | unsafe {
|
54 | 54 | let request = download.originalRequest().unwrap();
|
55 | 55 | let url = request.URL().unwrap().absoluteString().unwrap();
|
56 |
| - let mut path = PathBuf::from(suggested_path.to_string()); |
| 56 | + let suggested_filename = suggested_filename.to_string(); |
| 57 | + let mut download_destination = |
| 58 | + dirs::download_dir().unwrap_or_else(|| current_dir().unwrap_or_default()); |
| 59 | + |
| 60 | + download_destination.push(&suggested_filename); |
| 61 | + |
| 62 | + let (suggested_filename, ext) = suggested_filename |
| 63 | + .split_once('.') |
| 64 | + .map(|(base, ext)| (base, format!(".{ext}"))) |
| 65 | + .unwrap_or((&suggested_filename, "".to_string())); |
| 66 | + |
| 67 | + // WebView2 does not overwrite files but appends numbers |
| 68 | + let mut counter = 1; |
| 69 | + while download_destination.exists() { |
| 70 | + download_destination.set_file_name(format!("{suggested_filename} ({counter}){ext}")); |
| 71 | + counter += 1; |
| 72 | + } |
57 | 73 |
|
58 | 74 | let started_fn = &this.ivars().started;
|
59 | 75 | if let Some(started_fn) = started_fn {
|
60 | 76 | let mut started_fn = started_fn.borrow_mut();
|
61 |
| - match started_fn(url.to_string().to_string(), &mut path) { |
| 77 | + match started_fn(url.to_string().to_string(), &mut download_destination) { |
62 | 78 | true => {
|
63 |
| - let path = NSString::from_str(&path.display().to_string()); |
| 79 | + let path = NSString::from_str(&download_destination.display().to_string()); |
64 | 80 | let ns_url = NSURL::fileURLWithPath_isDirectory(&path, false);
|
65 | 81 | (*completion_handler).call((Retained::as_ptr(&ns_url),))
|
66 | 82 | }
|
|
0 commit comments