Skip to content

Commit

Permalink
Refactor file handling (#361)
Browse files Browse the repository at this point in the history
  • Loading branch information
fauxpark authored May 5, 2022
1 parent 1e04e73 commit 2a16cc8
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 73 deletions.
58 changes: 26 additions & 32 deletions macos/QMK Toolbox/AppDelegate.m
Original file line number Diff line number Diff line change
Expand Up @@ -363,42 +363,36 @@ - (IBAction)updateFilePath:(id)sender {
}

- (void)setFilePath:(NSURL *)path {
NSString *filename = @"";
if ([path.scheme isEqualToString:@"file"]) {
filename = [[path.absoluteString stringByRemovingPercentEncoding] stringByReplacingOccurrencesOfString:@"file://" withString:@""];
}
if ([path.scheme isEqualToString:@"qmk"]) {
NSURL *url;
if ([path.absoluteString containsString:@"qmk://"]) {
url = [NSURL URLWithString:[path.absoluteString stringByReplacingOccurrencesOfString:@"qmk://" withString:@""]];
} else {
url = [NSURL URLWithString:[path.absoluteString stringByReplacingOccurrencesOfString:@"qmk:" withString:@""]];
}
NSURL *unwrappedUrl = [NSURL URLWithString:[path.absoluteString substringFromIndex:[path.absoluteString hasPrefix:@"qmk://"] ? 6 : 4]];
[self downloadFile:unwrappedUrl];
} else {
[self loadLocalFile:path.path];
}
}

[self.logTextView logInfo:[NSString stringWithFormat:@"Downloading the file: %@", url.absoluteString]];
NSData *data = [NSData dataWithContentsOfURL:url];
if (!data) {
// Try .bin extension if .hex 404'd
url = [[url URLByDeletingPathExtension] URLByAppendingPathExtension:@"bin"];
[self.logTextView logInfo:[NSString stringWithFormat:@"No .hex file found, trying %@", url.absoluteString]];
data = [NSData dataWithContentsOfURL:url];
}
if (data) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES);
NSString *downloadsDirectory = [paths objectAtIndex:0];
NSString *name = [url.lastPathComponent stringByReplacingOccurrencesOfString:@"." withString:[NSString stringWithFormat:@"_%@.", [[[NSProcessInfo processInfo] globallyUniqueString] substringToIndex:8]]];
filename = [NSString stringWithFormat:@"%@/%@", downloadsDirectory, name];
[data writeToFile:filename atomically:YES];
[self.logTextView logInfo:[NSString stringWithFormat:@"File saved to: %@", filename]];
}
-(void)loadLocalFile:(NSString *)path {
if ([self.filepathBox indexOfItemWithObjectValue:path] == NSNotFound) {
[self.filepathBox addItemWithObjectValue:path];
}
if (![filename isEqualToString:@""]) {
if ([self.filepathBox indexOfItemWithObjectValue:filename] == NSNotFound) {
[self.filepathBox addItemWithObjectValue:filename];
}
[self.filepathBox selectItemWithObjectValue:filename];
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[[NSURL alloc] initFileURLWithPath:filename]];
[self.filepathBox selectItemWithObjectValue:path];
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[[NSURL alloc] initFileURLWithPath:path]];
}

-(void)downloadFile:(NSURL *)url {
NSURL *downloadsUrl = [[NSFileManager defaultManager] URLForDirectory:NSDownloadsDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSURL *destFileUrl = [downloadsUrl URLByAppendingPathComponent:url.lastPathComponent];
[self.logTextView logInfo:[NSString stringWithFormat:@"Downloading the file: %@", url.absoluteString]];

NSError *error;
NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
if (error) {
[self.logTextView logError:[NSString stringWithFormat:@"Could not download file: %@", [error localizedDescription]]];
}

[data writeToURL:destFileUrl atomically:YES];
[self.logTextView logInfo:[NSString stringWithFormat:@"File saved to: %@", destFileUrl.path]];
[self loadLocalFile:destFileUrl.path];
}

- (void)enableUI {
Expand Down
3 changes: 1 addition & 2 deletions macos/QMK Toolbox/QMKWindow.m
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {

- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
NSPasteboard *pboard = [sender draggingPasteboard];
NSString *file = [[NSURL URLFromPasteboard:pboard] path];
[(AppDelegate *)[[NSApplication sharedApplication] delegate] setFilePath:[NSURL fileURLWithPath:file]];
[(AppDelegate *)[[NSApplication sharedApplication] delegate] setFilePath:[NSURL URLFromPasteboard:pboard]];
return YES;
}

Expand Down
69 changes: 31 additions & 38 deletions windows/QMK Toolbox/MainWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -447,53 +447,46 @@ private void SetFilePath(string filepath)
{
if (!string.IsNullOrEmpty(filepath))
{
if (!filepath.StartsWith("\\\\wsl$"))
if (filepath.StartsWith("qmk:"))
{
var uri = new Uri(filepath);
if (uri.Scheme == "qmk")
{
string url = filepath.Replace(filepath.Contains("qmk://") ? "qmk://" : "qmk:", "");
filepath = Path.Combine(KnownFolders.Downloads.Path, filepath.Substring(filepath.LastIndexOf("/") + 1).Replace(".", "_" + Guid.NewGuid().ToString().Substring(0, 8) + "."));

try
{
logTextBox.LogInfo($"Downloading the file: {url}");
DownloadFirmwareFile(url, filepath);
}
catch (Exception)
{
try
{
// Try .bin extension if hex 404'd
url = Path.ChangeExtension(url, "bin");
filepath = Path.ChangeExtension(filepath, "bin");
logTextBox.LogInfo($"No .hex file found, trying {url}");
DownloadFirmwareFile(url, filepath);
}
catch (Exception)
{
logTextBox.LogError("Something went wrong when trying to get the default keymap file.");
return;
}
}
logTextBox.LogInfo($"File saved to: {filepath}");
}
string unwrappedUrl = filepath.Substring(filepath.StartsWith("qmk://") ? 6 : 4);
DownloadFile(unwrappedUrl);
}

filepathBox.Text = filepath;
if (!filepathBox.Items.Contains(filepath))
else
{
filepathBox.Items.Add(filepath);
LoadLocalFile(filepath);
}
}
}

private void DownloadFirmwareFile(string url, string filepath)
private void LoadLocalFile(string path)
{
using (var wb = new WebClient())
if (!filepathBox.Items.Contains(path))
{
filepathBox.Items.Add(path);
}
filepathBox.SelectedItem = path;
}

private void DownloadFile(string url)
{
logTextBox.LogInfo($"Downloading the file: {url}");

try
{
string destFile = Path.Combine(KnownFolders.Downloads.Path, url.Substring(url.LastIndexOf("/") + 1));
using (var wb = new WebClient())
{
wb.Headers.Add("User-Agent", "QMK Toolbox");
wb.DownloadFile(url, destFile);
}
logTextBox.LogInfo($"File saved to: {destFile}");

LoadLocalFile(destFile);
}
catch (Exception e)
{
wb.Headers.Add("User-Agent", "QMK Toolbox");
wb.DownloadFile(url, filepath);
logTextBox.LogError($"Could not download file: {e.Message}");
}
}

Expand Down
2 changes: 1 addition & 1 deletion windows/QMK Toolbox/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ private static void Main(string[] args)
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(args.Length == 0 ? new MainWindow(string.Empty) : new MainWindow(args[0]));
Application.Run(new MainWindow(args.Length == 0 ? string.Empty : args[0]));
}
finally
{
Expand Down

0 comments on commit 2a16cc8

Please sign in to comment.