Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- index.html:
- ```
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>Sound Font Naming Converter</title>
- <link rel="icon" type="image/png" href="/favicon.png">
- </head>
- <style>
- body, html {
- background-color: #202020;
- color: #FFFFFF;
- font-family: Arial, sans-serif;
- }
- input, select, button {
- background-color: #555;
- color: #fff;
- border: 1px solid #777;
- border-radius: 2px;
- }
- progress {
- background: linear-gradient(to bottom, #FFFFFF, #00FF00);
- border: 1px solid #00AA00;
- }
- progress::-webkit-progress-bar {
- background: #222;
- }
- progress::-webkit-progress-value {
- background: linear-gradient(to bottom, #FFFFFF, #00FF00);
- }
- progress::-moz-progress-bar {
- background: linear-gradient(to bottom, #FFFFFF, #00FF00);
- }
- .uploadProgressBar {
- width: 50%;
- }
- button:active,
- input[type="button"]:active,
- input[type="submit"]:active,
- input[type="file"]:active + label {
- background-color: dodgerblue;
- }
- button:hover,
- input[type="button"]:hover,
- input[type="submit"]:hover,
- input[type="file"]:hover + label {
- box-shadow: 0 0 2px 1px dodgerblue;
- }
- h1 {
- text-align: center;
- }
- .downloadButton {
- display: none;
- }
- /* Footer */
- .footer-title {
- min-width: 180px;
- font-size: 16px;
- padding-left: 10px;
- }
- .footer-container {
- position: absolute;
- bottom: 0;
- left: 0;
- width: 100%;
- display: flex;
- justify-content: space-between;
- align-items: center;
- background-color: #333;
- padding: 6px 0px;
- }
- .other-sites {
- float: right;
- padding-right: 10px;
- margin-left: 35px;
- }
- .footer-links {
- display: flex;
- align-items: center;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- min-width: 100px;
- }
- .footer-links a img {
- height: 16px;
- width: 16px;
- /* margin-right: 5px;*/
- padding-right: 10px;
- }
- .footer-links a:hover {
- color: #000;
- }
- .donate-button {
- width: 170px;
- height: auto;
- }
- </style>
- <body>
- <h1>Welcome to the Sound Font Naming Converter 3.0</h1>
- <p>1. Choose a source and target format from the drop down menus below.</p>
- <!-- Message display for feedback -->
- <div th:if="${message}" th:text="${message}"></div>
- <!-- Form to get user input -->
- <form id="uploadForm" action="/convert" method="post" enctype="multipart/form-data">
- <!-- Dropdown for source board selection -->
- <select id="sourceBoard" name="sourceBoard" title="Source board">
- <option value="CFX">CFX</option>
- <option value="GH3">GH3</option>
- <option value="PROFFIE">PROFFIE</option>
- <option value="VERSO">VERSO</option>
- <option value="XENO3">XENO3</option>
- </select>
- <!-- Dropdown for target board selection -->
- <select id="targetBoard" name="targetBoard" title="Target board">
- <option value="CFX">CFX</option>
- <option value="GH3">GH3</option>
- <option value="PROFFIE">PROFFIE</option>
- <option value="VERSO">VERSO</option>
- <option value="XENO3">XENO3</option>
- </select>
- <input type="checkbox" id="optimizeForProffie" name="optimizeForProffie" value="true" checked>
- <label for="optimizeForProffie">Optimize for FAT32 performance? You should ;)</label>
- <br>
- <br>
- <br>
- <div>
- <button id="proffieOptimizerButton" type="button" class="proffieOptimizerButton"
- title="Reorganizes an existing Proffie font for best performance. Just choose a source folder and the process is automated. Save downloaded file."> Proffie Easy Optimizer </button>
- </div>
- <br>
- <p>2. Add the font folder you wish to convert.</p>
- <!-- Directory input -->
- <div>
- <input type="file" id="files" name="files" webkitdirectory directory multiple>
- </div>
- <br>
- <p>3. Click "Convert" and then Download the resulting zip file to your computer.</p>
- <!-- Convert button -->
- <input type="submit" value="Convert" id="convertInput" title="Convert selected font folder." >
- <!-- Progress bar and its status message -->
- <div>
- <br>
- <p>Progress....</p>
- <progress id="uploadProgressBar" class="uploadProgressBar" max="100" value="0" ></progress>
- <p id="progressStatus">Waiting for files to be uploaded. Choose Files and click 'Convert'.</p>
- </div>
- <!-- Download button (Hidden initially) -->
- <button id="downloadButton" type="button" class="downloadButton" title="Download converted font." >Download Converted Files</button>
- <div class="footer-container">
- <span class="footer-title">NoSloppy - 2023</span>
- <a href="https://www.buymeacoffee.com/BrianConner" title="Brian Conner supports the saber community. Support him back.">
- <img class="donate-button" src="/donateButton.jpg"></a>
- <span class="footer-links">
- <span class="other-sites">Other sites: </span>
- <a href="https://crucible.hubbe.net/" target="_blank" title="The Crucible"><img src="https://crucible.hubbe.net/uploads/default/optimized/1X/2237f551ca8f4f69ac478df5c64aee1c951c33f5_2_180x180.png" alt="Crucible logo"></a>
- <a href="https://pod.hubbe.net/" target="_blank" title="ProffieOS Documentation site" ><img src="https://pod.hubbe.net/images/favicon.png" alt="Pod logo"></a>
- <a href="https://fredrik.hubbe.net/lightsaber/" target="_blank" title="Profezzorn's Proffieboard site"><img src="https://fredrik.hubbe.net/favicon.ico" alt="Lightsaber logo"></a>
- <a href="https://www.fett263.com/" target="_blank" title="Fett263's Style Library"><img src="https://www.fett263.com//favicon.ico" alt="Fett263 logo"></a>
- <a href="https://www.facebook.com/groups/opensourcesabers/" target="_blank" title="Open Source Group"><img src="https://www.facebook.com/favicon.ico" alt="Facebook logo"></a>
- </span>
- </div>
- </form>
- <script>
- let isEasyOptimizeActive = false;
- const sourceBoard = document.getElementById('sourceBoard');
- const targetBoard = document.getElementById('targetBoard');
- const proffieOptimizerButton = document.getElementById('proffieOptimizerButton');
- const optimizeCheckbox = document.getElementById('optimizeForProffie');
- const fileInput = document.getElementById('files');
- const downloadButton = document.getElementById('downloadButton');
- const progressBar = document.getElementById('uploadProgressBar');
- const progressStatus = document.getElementById('progressStatus');
- const form = document.getElementById('uploadForm');
- document.addEventListener('DOMContentLoaded', function() {
- console.log('DOM fully loaded and parsed');
- toggleOptimizeCheckbox();
- });
- targetBoard.addEventListener('change', function() {
- toggleOptimizeCheckbox();
- resetMessage();
- });
- sourceBoard.addEventListener('change', function() {
- fileInput.value = '';
- resetMessage();
- });
- proffieOptimizerButton.addEventListener('click', function() {
- proffieOptimizerButton.style.backgroundColor = 'dodgerblue';
- hideDownloadButton();
- isEasyOptimizeActive = true;
- fileInput.click();
- });
- fileInput.addEventListener('mousedown', function(event) {
- const selectedFiles = fileInput.files;
- const convertButton = document.getElementById('convertInput');
- checkIfBoardsAreSame(event);
- });
- fileInput.addEventListener('change', function() {
- if (this.files.length === 0) {
- isEasyOptimizeActive = false; // Reset the flag
- alert("No files selected. Please choose files before starting the conversion.");
- } else if (isEasyOptimizeActive && this.files.length > 0) {
- proffieOptimizerButton.style.backgroundColor = '#555';
- sourceBoard.value = "PROFFIE";
- targetBoard.value = "PROFFIE";
- optimizeCheckbox.checked = true;
- setTimeout(() => {
- const event = new Event('submit', {
- 'bubbles': true,
- 'cancelable': true
- });
- form.dispatchEvent(event);
- }, 100);
- }
- });
- // Assuming conversionData is the data received from the backend
- function processFiles(conversionData, files) {
- const zip = new JSZip();
- files.forEach(file => {
- const newFilePath = getNewFilePath(file.name, conversionData); // Assume this function determines the new path
- const folderPath = newFilePath.substring(0, newFilePath.lastIndexOf('/'));
- const fileName = newFilePath.substring(newFilePath.lastIndexOf('/') + 1);
- if (folderPath) {
- zip.folder(folderPath);
- }
- zip.file(newFilePath, file);
- });
- zip.generateAsync({type:"blob"})
- .then(function(blob) {
- saveZip(blob); // Assume this function triggers the download of the blob
- });
- }
- function getNewFilePath(oldFilePath, conversionData) {
- // ... logic to determine the new file path based on conversionData
- }
- function saveZip(blob) {
- // ... logic to trigger download
- }
- async function processAndDownload(targetBoard) {
- const wasEasyOptimizeActive = isEasyOptimizeActive; // Capture value here
- const response = await fetch(`/getConversionData?targetBoard=${targetBoard}`);
- const conversionData = await response.json();
- const files = Array.from(document.getElementById('files').files);
- processFiles(conversionData, files);
- // Delay the reset of the UI elements by 2 seconds
- setTimeout(() => {
- progressStatus.innerText = "Conversion complete.";
- if (isEasyOptimizeActive) {
- proffieOptimizerButton.style.backgroundColor = '#555';
- } else {
- downloadButton.style.backgroundColor = '#555';
- }
- }, 2000); // 2000 milliseconds = 2 seconds
- }
- function getNewFilePath(oldFilePath, conversionData) {
- // Example logic, replace with actual logic based on conversionData
- return conversionData[oldFilePath] || oldFilePath;
- }
- function saveZip(blob) {
- const a = document.createElement('a');
- const url = window.URL.createObjectURL(blob);
- a.href = url;
- a.download = 'ConvertedFiles.zip'; // replace with desired file name
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- window.URL.revokeObjectURL(url);
- }
- form.addEventListener('submit', function(event) {
- console.log("Form is being submitted. isEasyOptimizeActive:", isEasyOptimizeActive);
- const selectedFiles = fileInput.files;
- if (selectedFiles.length === 0) {
- isEasyOptimizeActive = false; // Reset the flag
- alert("No files selected. Please choose files before starting the conversion.");
- event.preventDefault();
- return;
- }
- event.preventDefault();
- const fileNames = Array.from(selectedFiles).map(file => file.name);
- const fileNamesJson = JSON.stringify({fileNames: fileNames});
- const xhr = new XMLHttpRequest();
- xhr.open('POST', '/convert', true);
- xhr.setRequestHeader("Accept", "application/json");
- xhr.upload.onprogress = function(event) {
- if (event.lengthComputable) {
- const percentComplete = (event.loaded / event.total) * 100;
- progressBar.value = percentComplete;
- if (percentComplete < 100) {
- progressStatus.innerText = "Uploading files...";
- } else {
- progressStatus.innerText = "Files uploaded. Processing...";
- // Reset the progress bar and simulate conversion progress
- setTimeout(function() {
- progressBar.value = 0;
- simulateConversionProgress();
- }, 500);
- }
- }
- };
- function simulateConversionProgress() {
- let value = 0;
- progressBar.interval = setInterval(function() { // Store the interval ID on the progressBar object
- if (value >= 100) {
- clearInterval(progressBar.interval);
- return;
- }
- value++;
- progressBar.value = value;
- if (value === 100) {
- progressStatus.innerText = "Conversion complete.";
- }
- }, 50); // this will complete the progress bar in 5 seconds. Adjust as needed.
- }
- xhr.onload = function() {
- const response = JSON.parse(this.responseText);
- clearInterval(progressBar.interval);
- if (response.status === "success") {
- progressBar.value = 100;
- progressStatus.innerText = "Conversion complete.";
- if (!isEasyOptimizeActive) {
- downloadButton.style.display = 'block';
- }
- else {
- const targetBoardValue = targetBoard.value;
- progressStatus.innerText = `Conversion complete. Standby for auto download of Optimized_for_PROFFIE.zip`;
- triggerDownload(targetBoardValue);
- }
- } else if (response.status === "info") {
- console.log('Response was info');
- progressStatus.innerText = response.message;
- downloadButton.style.display = 'none';
- } else {
- console.log('Response was something else');
- progressStatus.innerText = response.message;
- downloadButton.style.display = 'none';
- }
- isEasyOptimizeActive = false;
- };
- xhr.setRequestHeader("Content-Type", "application/json");
- xhr.send(fileNamesJson);
- });
- downloadButton.addEventListener('click', function() {
- // Change button text upon clicking
- progressStatus.innerText = "Fetching converted files. Standby for .zip download ...";
- downloadButton.style.backgroundColor = 'dodgerblue';
- const targetBoardValue = targetBoard.value; // store this for later
- triggerDownload(targetBoardValue);
- });
- function checkIfBoardsAreSame() {
- if (sourceBoard.value === "CFX" && (targetBoard.value === "PROFFIE" || targetBoard.value === "GH3")) {
- let confirmAction;
- if (targetBoard.value === "PROFFIE") {
- confirmAction = window.confirm("Conversion from CFX to PROFFIE is not required.\nProffieboards already natively support Plecter fonts.\nDo you want to continue anyway?");
- if (confirmAction) {
- // Manually open the file dialog since we previously blocked it
- fileInput.click();
- } else {
- toggleOptimizeCheckbox();
- }
- } else if (targetBoard.value === "GH3") {
- window.alert("Conversion from CFX to GH3 is unsupported.\nGH3 already natively supports Plecter fonts.");
- }
- } else if (sourceBoard.value === targetBoard.value) {
- if (sourceBoard.value === "PROFFIE") {
- window.alert("You've chosen Proffie to Proffie, which is for the purpose of optimizing the folder structure for best performance when using a FAT32 file system (which is what the SD card uses.)");
- optimizeCheckbox.checked = true;
- optimizeCheckbox.disabled = true;
- } else {
- window.alert("Conversion from " + sourceBoard.value + " to " + targetBoard.value + " is unnecessary.\nPlease choose a different conversion.");
- }
- } else {
- // Re-enable the checkbox if both boards are not Proffie
- optimizeCheckbox.disabled = false;
- }
- }
- function resetMessage() {
- hideDownloadButton();
- progressBar.value = 0;
- progressStatus.innerText = "Waiting for files to be uploaded. Choose Files and click 'Convert'.";
- }
- function hideDownloadButton() {
- downloadButton.style.display = 'none';
- }
- function toggleOptimizeCheckbox() {
- var optimizeLabel = document.querySelector('label[for="optimizeForProffie"]');
- if (targetBoard.value === "PROFFIE") {
- optimizeCheckbox.style.display = 'inline-block';
- optimizeLabel.style.display = 'inline-block';
- } else {
- optimizeCheckbox.style.display = 'none';
- optimizeLabel.style.display = 'none';
- }
- }
- </script>
- </body>
- </html>
- ```
- SoundFontConverterController.java:
- ```
- package com.example.soundfontconverter;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.ResponseEntity;
- import org.springframework.http.HttpHeaders;
- import org.springframework.http.MediaType;
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import java.io.StringWriter;
- import java.io.PrintWriter;
- // import javax.servlet.http.HttpServletResponse;
- import jakarta.servlet.http.HttpServletResponse;
- import jakarta.servlet.http.HttpServletRequest;
- import java.util.Enumeration;
- // import org.springframework.http.server.ServletServerHttpResponse;
- // import org.springframework.http.server.ServerHttpRequest;
- @Controller
- public class SoundFontConverterController {
- @Autowired
- private SoundFontNamingService soundFontNamingService;
- @Autowired
- private HttpServletRequest request;
- @GetMapping("/")
- public String index() {
- return "index";
- }
- @GetMapping("/getConversionData")
- public ResponseEntity<Map<String, Object>> getConversionData(@RequestParam String targetBoard) {
- try {
- Map<String, Object> conversionData = getConversionDataForTargetBoard(targetBoard);
- return new ResponseEntity<>(conversionData, HttpStatus.OK);
- } catch (Exception e) {
- return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
- }
- }
- @GetMapping("/downloadConvertedFiles")
- public ResponseEntity<?> downloadConvertedFiles(@RequestParam String targetBoard) {
- try {
- Path fileLocation = Paths.get("temporaryDirectory", "Converted_to_" + targetBoard + ".zip");
- byte[] data = Files.readAllBytes(fileLocation);
- HttpHeaders headers = new HttpHeaders();
- headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileLocation.getFileName().toString());
- headers.setContentType(MediaType.parseMediaType("application/zip"));
- return new ResponseEntity<>(data, headers, HttpStatus.OK);
- } catch (Exception e) {
- return new ResponseEntity<>("Error occurred while downloading file.", HttpStatus.INTERNAL_SERVER_ERROR);
- }
- }
- @PostMapping("/convert")
- public ResponseEntity<?> convertSoundFont(
- @RequestParam String sourceBoard,
- @RequestParam String targetBoard,
- @RequestParam("fileNames") List<String> files,
- @RequestParam(required = false) String optimizeForProffie) {
- boolean optimize = "true".equals(optimizeForProffie); // Interpret the value
- // Log all request parameters
- Enumeration<String> parameterNames = request.getParameterNames();
- while (parameterNames.hasMoreElements()) {
- String paramName = parameterNames.nextElement();
- String[] paramValues = request.getParameterValues(paramName);
- for (String paramValue : paramValues) {
- System.out.println("Param: " + paramName + " Value: " + paramValue);
- }
- }
- // 1. Cleanup any existing temporaryDirectory before processing new files.
- //soundFontNamingService.cleanupTemporaryDirectory();
- List<String> savedFiles = new ArrayList<>();
- for (String fileName : files) {
- virtualFileSystem.put(fileName, fileName);
- if (fileName.endsWith(".DS_Store")) continue;
- String virtualPath = "temporaryDirectory/" + fileName;
- virtualFileSystem.put(virtualPath, fileName);
- }
- try {
- // 3. Convert files.
- soundFontNamingService.chainConvertSoundFont(virtualFileSystem, sourceBoard, targetBoard, optimize, "temporaryDirectory");
- // 4. Remove the original directory.
- String originalDirectoryName = savedFiles.get(0).getParent().getFileName().toString();
- soundFontNamingService.removeOriginalDirectory(originalDirectoryName);
- // 5. Zip the converted files.
- Path resultZip = soundFontNamingService.zipConvertedFiles("Converted_to_" + targetBoard);
- // 6.Return a JSON indicating success instead of the zipped file
- return new ResponseEntity<>(Map.of("status", "success", "message", "Conversion complete!"), HttpStatus.OK);
- } catch (Exception e) {
- return new ResponseEntity<>(Map.of("status", "error", "message", "Conversion failed due to " + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
- }
- }
- private ResponseEntity<String> generateErrorResponse(String message, Exception e) {
- StringWriter sw = new StringWriter();
- e.printStackTrace(new PrintWriter(sw));
- String exceptionAsString = sw.toString();
- return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(message + exceptionAsString);
- }
- }
- ```
- SoundFontNamingService.java:
- ```
- package com.example.soundfontconverter;
- import org.springframework.stereotype.Service;
- import java.io.IOException;
- import java.nio.file.*;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.util.stream.Stream;
- import java.util.Comparator;
- import java.util.stream.Collectors;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import java.util.ArrayList;
- @Service
- public class SoundFontNamingService {
- enum BoardType {
- CFX,
- GH3,
- PROFFIE,
- VERSO,
- XENO3;
- public static String getKey(BoardType source, BoardType target) {
- return source.name() + "_TO_" + target.name();
- }
- }
- private Map<String, String> fileContentMap = new HashMap<>();
- private StringBuilder logStringBuilder = new StringBuilder();
- private boolean chained = false;
- private String realTarget = "PROFFIE";
- private static final String DEFAULTS_PATH = "./inis";
- private static final Map<String, String> CFX_TO_PROFFIE = new HashMap<>();
- private static final Map<String, String> CFX_TO_VERSO = new HashMap<>();
- private static final Map<String, String> GH3_TO_PROFFIE = new HashMap<>();
- private static final Map<String, String> PROFFIE_TO_CFX = new HashMap<>();
- private static final Map<String, String> PROFFIE_TO_GH3 = new HashMap<>();
- private static final Map<String, String> PROFFIE_TO_VERSO = new HashMap<>();
- private static final Map<String, String> PROFFIE_TO_XENO3 = new HashMap<>();
- private static final Map<String, String> VERSO_TO_CFX = new HashMap<>();
- private static final Map<String, String> VERSO_TO_PROFFIE = new HashMap<>();
- private static final Map<String, String> XENO3_TO_PROFFIE = new HashMap<>();
- //... additional board mappings can be added here
- // Central mapping repository
- private static final Map<String, Map<String, String>> soundMappings = new HashMap<>();
- private static final Map<String, Integer> soundCounter = new HashMap<>();
- static {
- initializeMappings();
- }
- private static void loadMappingsFromCSV(String csvFilePath, Map<String, String> mapping) {
- try (BufferedReader reader = new BufferedReader(new FileReader(csvFilePath))) {
- String line;
- while ((line = reader.readLine()) != null) {
- String[] parts = line.split(",");
- if (parts.length >= 2) {
- mapping.put(parts[0], parts[1]);
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private static void safeLoadMappingsFromCSV(String csvFilePath, Map<String, String> mapping) {
- File f = new File(csvFilePath);
- if(f.exists() && !f.isDirectory()) {
- loadMappingsFromCSV(csvFilePath, mapping);
- }
- }
- private static void initializeMappings() {
- safeLoadMappingsFromCSV("./CSV/CFX_TO_PROFFIE.csv", CFX_TO_PROFFIE);
- // safeLoadMappingsFromCSV("./CSV/CFX_TO_VERSO.csv", CFX_TO_VERSO);
- // safeLoadMappingsFromCSV("./CSV/GH3_TO_PROFFIE.csv", GH3_TO_PROFFIE);
- safeLoadMappingsFromCSV("./CSV/PROFFIE_TO_CFX.csv", PROFFIE_TO_CFX);
- // safeLoadMappingsFromCSV("./CSV/PROFFIE_TO_GH3.csv", PROFFIE_TO_CFX);
- safeLoadMappingsFromCSV("./CSV/PROFFIE_TO_VERSO.csv", PROFFIE_TO_VERSO);
- safeLoadMappingsFromCSV("./CSV/PROFFIE_TO_XENO3.csv", PROFFIE_TO_XENO3);
- // safeLoadMappingsFromCSV("./CSV/VERSO_TO_PROFFIE.csv", VERSO_TO_PROFFIE);
- safeLoadMappingsFromCSV("./CSV/XENO3_TO_PROFFIE.csv", XENO3_TO_PROFFIE);
- // ... and so on for other mappings ...
- soundMappings.put(BoardType.getKey(BoardType.CFX, BoardType.PROFFIE), CFX_TO_PROFFIE);
- // soundMappings.put(BoardType.getKey(BoardType.CFX, BoardType.VERSO), CFX_TO_VERSO);
- soundMappings.put(BoardType.getKey(BoardType.PROFFIE, BoardType.CFX), PROFFIE_TO_CFX);
- soundMappings.put(BoardType.getKey(BoardType.PROFFIE, BoardType.GH3), PROFFIE_TO_CFX);
- soundMappings.put(BoardType.getKey(BoardType.PROFFIE, BoardType.VERSO), PROFFIE_TO_VERSO);
- soundMappings.put(BoardType.getKey(BoardType.PROFFIE, BoardType.XENO3), PROFFIE_TO_XENO3);
- soundMappings.put(BoardType.getKey(BoardType.GH3, BoardType.PROFFIE), CFX_TO_PROFFIE);
- // soundMappings.put(BoardType.getKey(BoardType.VERSO, BoardType.CFX), VERSO_TO_CFX);
- soundMappings.put(BoardType.getKey(BoardType.VERSO, BoardType.PROFFIE), VERSO_TO_PROFFIE);
- soundMappings.put(BoardType.getKey(BoardType.XENO3, BoardType.PROFFIE), XENO3_TO_PROFFIE);
- // Reverse Mapping fist so actual mappings will override
- // CFX to Proffie mapping
- for (Map.Entry<String, String> entry : PROFFIE_TO_CFX.entrySet()) {
- CFX_TO_PROFFIE.putIfAbsent(entry.getValue(), entry.getKey());
- }
- // for (Map.Entry<String, String> entry : VERSO_TO_CFX.entrySet()) {
- // CFX_TO_VERSO.putIfAbsent(entry.getValue(), entry.getKey());
- // }
- // Verso to Proffie mapping
- for (Map.Entry<String, String> entry : PROFFIE_TO_VERSO.entrySet()) {
- VERSO_TO_PROFFIE.putIfAbsent(entry.getValue(), entry.getKey());
- }
- // Xeno3 to Proffie mapping
- for (Map.Entry<String, String> entry : PROFFIE_TO_XENO3.entrySet()) {
- XENO3_TO_PROFFIE.putIfAbsent(entry.getValue(), entry.getKey());
- }
- }
- public void virtualFileSystemCopyFile(String sourcePath, String targetPath, Map<String, List<String>> virtualFileSystem) {
- List<String> sourceFiles = virtualFileSystem.get(sourcePath);
- if (sourceFiles != null) {
- virtualFileSystem.put(targetPath, new ArrayList<>(sourceFiles));
- }
- }
- public void virtualFileSystemMoveFile(String sourcePath, String targetPath, Map<String, List<String>> virtualFileSystem) {
- List<String> sourceFiles = virtualFileSystem.remove(sourcePath);
- if (sourceFiles != null) {
- virtualFileSystem.put(targetPath, sourceFiles);
- }
- }
- private static void copyFile(Path sourcePath, Path targetPath) {
- try {
- Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
- } catch (IOException ex) {
- System.err.println("Error copying file from " + sourcePath + " to " + targetPath);
- ex.printStackTrace();
- }
- }
- // This version takes the optimizeForProffie parameter. It's the main logic
- private void convertSounds(BoardType sourceBoard, Map<String, String> fileNamesAndPaths, BoardType targetBoard, String targetDir, boolean optimizeForProffie, Map<String, List<String>> virtualFileSystem) throws IOException {
- if (virtualFileSystem == null) {
- virtualFileSystem = new HashMap<>();
- }
- soundCounter.clear();
- String key = BoardType.getKey(sourceBoard, targetBoard);
- System.out.println("----------------------------------------------------------------\n.");
- if (targetBoard == BoardType.PROFFIE && realTarget == "PROFFIE") {
- System.out.println("Converting from " + sourceBoard + " to " + targetBoard + "\n.");
- } else if (targetBoard != BoardType.PROFFIE) {
- realTarget = targetBoard.toString();
- } else {
- System.out.println("Converting from " + sourceBoard + " to " + realTarget + "\n.");
- }
- // Since soundFileNames are now just strings without path information, we'll use a placeholder for sourceDirName
- String sourceDirName = "SourceDirectory";
- String finalTargetDir = targetDir + "/Converted_to_" + targetBoard + "/" +
- (targetBoard == BoardType.GH3 ? "sound1 - " : "") +
- sourceDirName;
- // Prepare Log file
- if (chained == false) {
- ensureDirectoryExists(finalTargetDir, virtualFileSystem);
- SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
- String currentDate = sdf.format(new Date());
- logStringBuilder.append("Converted with SoundFont Naming Converter 3.0\n");
- logStringBuilder.append("Brian Conner a.k.a NoSloppy\n\n");
- logStringBuilder.append(currentDate).append("\n");
- if (targetBoard == BoardType.PROFFIE && realTarget == "PROFFIE") {
- logStringBuilder.append("Converted: ").append(sourceBoard).append(" to ").append(targetBoard).append("\n");
- logStringBuilder.append("Optimized for Fat32 performance: ").append(optimizeForProffie ? "Yes" : "No").append("\n\n");
- } else if (targetBoard != BoardType.PROFFIE) {
- realTarget = targetBoard.toString();
- } else {
- logStringBuilder.append("Converted: ").append(sourceBoard).append(" to ").append(realTarget).append("\n");
- logStringBuilder.append("\n");
- }
- }
- // If it's Proffie to Proffie, skip the mapping
- Map<String, String> mapping;
- if (sourceBoard == BoardType.PROFFIE && targetBoard == BoardType.PROFFIE) {
- mapping = null; // No mapping required for Proffie to Proffie
- } else {
- if (!soundMappings.containsKey(key)) {
- System.out.println("Conversion from " + sourceBoard + " to " + targetBoard + " is not supported.");
- return;
- }
- mapping = soundMappings.get(key);
- }
- ensureDirectoryExists(finalTargetDir, virtualFileSystem);
- // Check if source has directories named something like "Bonus Files" or "extra"
- boolean hasExtrasDirectories = false;
- try {
- hasExtrasDirectories = Files.walk(Paths.get(new File(soundFileNames.get(0)).getParent()), 1) // Only check immediate children
- .filter(Files::isDirectory).anyMatch(path -> {
- String dirName = path.getFileName().toString().toLowerCase();
- return dirName.contains("bonus") || dirName.contains("extra");
- });
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- // If "extras" directory is needed, create it now
- if (hasExtrasDirectories) {
- ensureDirectoryExists(finalTargetDir + "/extras", virtualFileSystem);
- }
- // Main sound conversion
- List<String> paths = soundFileNames;
- Map<String, Integer> fileNameCounter = new HashMap<>();
- boolean fontSoundProcessed = false;
- paths.stream()
- .filter(path -> !new File(path).getName().startsWith(".")) // Filtering out hidden files
- .filter(path -> {
- String parentDirName = new File(path).getParentFile().getName().toLowerCase();
- if (parentDirName.contains("bonus") || parentDirName.contains("extra")) {
- virtualFileSystemCopyFile(path, finalTargetDir + "/extras/" + new File(path).getName(), virtualFileSystem);
- String logEntryExtras = "Moved extra/bonus file to " + finalTargetDir + "/extras/" + new File(path).getName();
- System.out.println(logEntryExtras);
- logStringBuilder.append(logEntryExtras).append("\n");
- return false;
- }
- return true;
- })
- .sorted() // As the list contains string file names, the default sorting should suffice
- .forEach(fileName -> {
- try {
- // This line is no longer needed as fileName is now directly obtained from the forEach loop.
- // Move non-wav files directly to the target folder
- if (!fileName.endsWith(".wav")) {
- virtualFileSystemCopyFile(fileName, finalTargetDir + "/" + fileName, virtualFileSystem);
- String logEntryNonWav = "Moved non-wav file: " + fileName;
- System.out.println(logEntryNonWav);
- logStringBuilder.append(logEntryNonWav).append("\n");
- return;
- }
- // Move "track" wav files to "tracks" folder
- if (fileName.contains("track")) {
- ensureDirectoryExists(finalTargetDir + "/tracks", virtualFileSystem);
- virtualFileSystemCopyFile(fileName, finalTargetDir + "/tracks/" + fileName, virtualFileSystem);
- String logEntryTrack = "Moved track file: " + fileName;
- System.out.println(logEntryTrack);
- logStringBuilder.append(logEntryTrack).append("\n");
- return;
- }
- // For other wav files, use the mapping
- String baseName = fileName.replaceAll(" (\\(\\d+\\))?\\.wav$|\\d+\\.wav$", ".wav");
- // If we're doing Proffie to Proffie, keep the baseName as is
- String convertedBaseName = (mapping == null) ? baseName : mapping.getOrDefault(baseName, baseName);
- String outputPath;
- if (convertedBaseName != null) {
- int count = soundCounter.getOrDefault(convertedBaseName, 0) + 1;
- soundCounter.put(convertedBaseName, count);
- String prefix = (convertedBaseName.contains(".")) ? convertedBaseName.substring(0, convertedBaseName.lastIndexOf('.')) : convertedBaseName;
- String formattedCount = String.valueOf(count);
- if (targetBoard == BoardType.CFX) {
- String newPrefix;
- int currentCounter;
- String switchKey = convertedBaseName.toLowerCase().replaceAll("\\.wav$", "");
- String commonKey;
- switch (switchKey) {
- // First, handle the special numbering and weird naming cases
- case "poweroff":
- commonKey = "pwroff";
- currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
- if (currentCounter == 1) {
- newPrefix = "poweroff";
- } else if (currentCounter == 2) {
- newPrefix = "pwroff2";
- } else {
- newPrefix = "poweroff" + (currentCounter - 1);
- }
- outputPath = finalTargetDir + "/" + newPrefix + ".wav";
- fileNameCounter.put(commonKey, currentCounter + 1);
- break;
- // case "clash":
- // commonKey = "clash";
- // currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
- // if (currentCounter == 1) {
- // newPrefix = "clash" + currentCounter;
- // } else if (currentCounter == 2) {
- // newPrefix = "fclash" + (currentCounter -1);
- // } else {
- // newPrefix = "clash" + (currentCounter - 1);
- // }
- // outputPath = finalTargetDir + "/" + newPrefix + ".wav";
- // fileNameCounter.put(commonKey, currentCounter + 1);
- // break;
- case "font":
- commonKey = "font";
- currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
- if (currentCounter == 1) {
- outputPath = finalTargetDir + "/font" + ".wav";
- } else {
- int nextBootCounter = fileNameCounter.getOrDefault("boot", 1);
- outputPath = finalTargetDir + "/boot" + (nextBootCounter == 1 ? "" : nextBootCounter) + ".wav";
- fileNameCounter.put("boot", nextBootCounter + 1);
- }
- fileNameCounter.put(commonKey, currentCounter + 1);
- break;
- // These get no number on the first file, then sequence the rest staring from 2
- case "boot":
- commonKey = "boot";
- currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
- outputPath = finalTargetDir + "/boot" + (currentCounter == 1 ? "" : currentCounter) + ".wav";
- fileNameCounter.put(commonKey, currentCounter + 1);
- break;
- case "color":
- commonKey = "color";
- currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
- outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + (currentCounter == 1 ? "" : currentCounter) + ".wav";
- fileNameCounter.put(commonKey, currentCounter + 1);
- break;
- case "blaster":
- commonKey = "blaster";
- currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
- outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + (currentCounter == 1 ? "" : currentCounter) + ".wav";
- fileNameCounter.put(commonKey, currentCounter + 1);
- break;
- case "poweron":
- commonKey = "poweron";
- currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
- outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + (currentCounter == 1 ? "" : currentCounter) + ".wav";
- fileNameCounter.put(commonKey, currentCounter + 1);
- break;
- case "lockup":
- commonKey = "lockup";
- currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
- outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + (currentCounter == 1 ? "" : currentCounter) + ".wav";
- fileNameCounter.put(commonKey, currentCounter + 1);
- break;
- case "drag":
- commonKey = "drag";
- currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
- outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + (currentCounter == 1 ? "" : currentCounter) + ".wav";
- fileNameCounter.put(commonKey, currentCounter + 1);
- break;
- case "force":
- commonKey = "force";
- currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
- outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + (currentCounter == 1 ? "" : currentCounter) + ".wav";
- fileNameCounter.put(commonKey, currentCounter + 1);
- break;
- default:
- currentCounter = fileNameCounter.getOrDefault(switchKey, 1);
- outputPath = finalTargetDir + "/" + convertedBaseName.substring(0, convertedBaseName.length() - 4) + currentCounter + ".wav";
- fileNameCounter.put(switchKey, currentCounter + 1);
- break;
- }
- } else if (targetBoard == BoardType.PROFFIE) {
- if (prefix.length() > 6 && count == 1 && soundCounter.containsKey(baseName)) {
- formattedCount = String.valueOf(count);
- } else {
- formattedCount = (prefix.length() > 6) ? String.valueOf(count) : String.format("%02d", count);
- }
- if (optimizeForProffie) {
- outputPath = count == 1 ? finalTargetDir + "/" + prefix + ".wav" : finalTargetDir + "/" + prefix + "/" + prefix + formattedCount + ".wav";
- if (count == 2) {
- String originalPath = finalTargetDir + "/" + prefix + ".wav";
- String newPath = finalTargetDir + "/" + prefix + "/" + prefix + (prefix.length() > 6 ? "1" : "01") + ".wav";
- ensureDirectoryExists(finalTargetDir + "/" + prefix, virtualFileSystem);
- virtualFileSystemMoveFile(originalPath, newPath, virtualFileSystem);
- Path originalPathObj = Paths.get(originalPath);
- Path newPathObj = Paths.get(newPath);
- String logEntryProffie = "Numbered and moved first file to subdirectory:\n"
- + " " + originalPathObj.subpath(2, originalPathObj.getNameCount())
- + " -> "
- + newPathObj.subpath(2, newPathObj.getNameCount());
- System.out.println(logEntryProffie);
- logStringBuilder.append(logEntryProffie).append("\n");
- }
- } else {
- outputPath = finalTargetDir + "/" + (count > 1 ? prefix + formattedCount : prefix) + ".wav";
- if (count == 2) {
- String originalPath = finalTargetDir + "/" + prefix + ".wav";
- String newPath = finalTargetDir + "/" + prefix + (prefix.length() > 6 ? "1" : "01") + ".wav";
- virtualFileSystemMoveFile(originalPath, newPath, virtualFileSystem);
- Path originalPathObj = Paths.get(originalPath);
- Path newPathObj = Paths.get(newPath);
- String logEntryProffie = "Numbered the first file:\n "
- + " " + originalPathObj.subpath(2, originalPathObj.getNameCount())
- + " -> "
- + newPathObj.subpath(2, newPathObj.getNameCount());
- System.out.println(logEntryProffie);
- logStringBuilder.append(logEntryProffie).append("\n");
- }
- }
- } else if (targetBoard == BoardType.VERSO && convertedBaseName.equals("font.wav")) {
- String commonKey = "font";
- int currentCounter = fileNameCounter.getOrDefault(commonKey, 1);
- fileNameCounter.put(commonKey, currentCounter + 1);
- if (currentCounter == 1) {
- outputPath = finalTargetDir + "/font.wav";
- virtualFileSystemMoveFile(fileName, outputPath, virtualFileSystem); // Changed path.toString() to fileName
- String logEntryVerso = "Converted: " + new File(fileName).getName() + " -> " + outputPath.replace("temporaryDirectory/", ""); // Changed path.getFileName().toString() to new File(fileName).getName()
- System.out.println(logEntryVerso);
- logStringBuilder.append(logEntryVerso).append("\n");
- } else {
- String logEntryVersoSkipped = "Skipped additional 'font' file: " + fileName;
- System.out.println(logEntryVersoSkipped);
- logStringBuilder.append(logEntryVersoSkipped).append("\n");
- }
- return;
- } else if (targetBoard == BoardType.XENO3) {
- outputPath = Paths.get(finalTargetDir, prefix + " (" + count + ").wav").toString();
- } else if (count > 1 || (targetBoard != BoardType.PROFFIE && count == 1)) {
- outputPath = Paths.get(finalTargetDir, prefix + formattedCount + ".wav").toString();
- } else {
- outputPath = Paths.get(finalTargetDir, prefix + ".wav").toString();
- }
- virtualFileSystemMoveFile(fileName, outputPath, virtualFileSystem);
- String logEntry = "Converted: " + new File(fileName).getName() + " -> " + outputPath.replace("temporaryDirectory/", ""); // Replaced path.getFileName().toString() with new File(fileName).getName()
- System.out.println(logEntry);
- logStringBuilder.append(logEntry).append("\n");
- } else { // convertedBaseName = null
- System.out.println("Skipped wav file without mapping: " + fileName);
- }
- } catch (IOException e) {
- System.err.println("An IOException occurred: " + e.getMessage());
- }
- });
- if (chained == true) {
- logStringBuilder.append("\n*********----- MTFBWY -----*********\n");
- } else {
- logStringBuilder.append("\n\n");
- }
- try {
- System.out.println("--- Writing _Conversion_Log.txt ---");
- Files.writeString(Paths.get(finalTargetDir + "/_Conversion_Log.txt"), logStringBuilder.toString());
- } catch (IOException e) {
- System.err.println("Failed to write log: " + e.getMessage());
- }
- // } catch (IOException ex) {
- // System.err.println("An error occurred while reading the file: " + ex.getMessage());
- // }
- // After processing all files, check for default INIs for Proffie
- if (targetBoard == BoardType.PROFFIE) {
- String[] defaultFiles = {"config.ini", "smoothsw.ini"};
- for (String defaultFile : defaultFiles) {
- File targetDefaultFile = new File(finalTargetDir, defaultFile);
- if (!targetDefaultFile.exists()) {
- File inisFile = new File(DEFAULTS_PATH + "/" + defaultFile);
- if (inisFile.exists()) {
- try {
- Files.copy(inisFile.toPath(), targetDefaultFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
- System.out.println("Copied default file: " + defaultFile);
- String content = Files.readString(inisFile.toPath()); // Read the content of inisFile
- addFileToVFS(finalTargetDir, defaultFile, content, virtualFileSystem, fileContentMap); // Use the content variable here
- } catch (IOException e) {
- // e.printStackTrace();
- System.err.println("Error while copying file: " + defaultFile);
- }
- }
- }
- }
- }
- }
- private static void ensureDirectoryExists(String dirPath, Map<String, List<String>> virtualFileSystem) {
- if (!virtualFileSystem.containsKey(dirPath)) {
- virtualFileSystem.put(dirPath, new ArrayList<>());
- System.out.println("Creating directory: " + dirPath);
- }
- }
- // Updated method signature
- private void addFileToVFS(String dirPath, String fileName, String content, Map<String, List<String>> virtualFileSystem, Map<String, String> fileContentMap) {
- ensureDirectoryExists(dirPath, virtualFileSystem); // Ensure the directory exists
- String filePath = dirPath + "/" + fileName;
- virtualFileSystem.get(dirPath).add(filePath); // Add file path to directory
- fileContentMap.put(filePath, content); // Store the file content
- }
- public class MutableInt {
- public int value;
- public MutableInt(int value) {
- this.value = value;
- }
- }
- private List<String> savedFiles = new ArrayList<>();
- private void convertSoundFont(Map<String, String> fileNamesAndPaths, String sourceBoard, String targetBoard, boolean optimize) throws IOException {
- BoardType srcBoard = BoardType.valueOf(sourceBoard.toUpperCase());
- BoardType tgtBoard = BoardType.valueOf(targetBoard.toUpperCase());
- String sourceDirName = new File(savedFiles.get(0).toString()).getParentFile().getName();
- List<String> soundFileNames = //... obtain or create the list of sound file names here;
- convertSounds(srcBoard, fileNamesAndPaths, tgtBoard, "temporaryDirectory", optimize, virtualFileSystem);
- }
- private void chainConvertSoundFont(Map<String, String> fileNamesAndPaths, String sourceBoard, String targetBoard, boolean optimize) throws IOException {
- // Clear the StringBuilder for subsequent log entries
- logStringBuilder.setLength(0);
- if ("PROFFIE".equals(sourceBoard) || "PROFFIE".equals(targetBoard)) {
- // Just convert normally.
- convertSoundFont(virtualFileSystem, sourceBoard, targetBoard, optimize);
- } else {
- // Do the chained conversion;
- // cCnvert to PROFFIE first and save it in /temporaryDirectory/Converted_to_PROFFIE.
- // Using realTarget for logging only
- realTarget = targetBoard;
- convertSoundFont(savedFiles, sourceBoard, "PROFFIE", false);
- chained = !chained;
- // Now use the converted PROFFIE files as source for the actual target.
- // Clear the StringBuilder for subsequent log entries
- //logStringBuilder.setLength(0);
- Path tempProffieDir = Paths.get("temporaryDirectory", "Converted_to_PROFFIE");
- Map<String, String> proffieFiles = Files.walk(tempProffieDir)
- .filter(Files::isRegularFile)
- .collect(Collectors.toList());
- convertSoundFont(virtualFileSystem, "PROFFIE", targetBoard, false);
- chained = !chained;
- // Optional: Cleanup the temporary directory used for the PROFFIE conversion.
- }
- }
- public Path zipConvertedFiles(String targetDir) throws IOException {
- Path zipPath = Paths.get(targetDir + ".zip");
- // Logging the structure
- Path sourcePath = Paths.get(targetDir);
- System.out.println("Logging directory structure before zipping:");
- Files.walk(sourcePath).forEach(p -> {
- // System.out.println(p.toString());
- });
- System.out.println("Starting to create ZIP file...");
- try (FileSystem zipFs = FileSystems.newFileSystem(zipPath, Map.of("create", "true"))) {
- // Exclude the top-level source directory itself when walking
- Files.walk(sourcePath).filter(p -> !p.equals(sourcePath)).forEach(path -> {
- try {
- if (Files.isRegularFile(path) && Files.size(path) > 0) { // Ensure it's a file and has content
- String sourceDirName = sourcePath.getFileName().toString();
- Path destPath = zipFs.getPath("/" + sourceDirName + "/" + sourcePath.relativize(path).toString());
- // Ensure the parent directory structure exists in the ZIP
- if (destPath.getParent() != null) {
- Files.createDirectories(destPath.getParent());
- }
- Files.copy(path, destPath, StandardCopyOption.REPLACE_EXISTING);
- }
- } catch (NoSuchFileException e) {
- System.err.println("Directory structure in ZIP does not match expected structure: " + e.getMessage());
- } catch (Exception e) {
- e.printStackTrace();
- System.err.println("Error processing file: " + path.toString() +
- ". Destination path in ZIP: " + zipFs.getPath("/" + sourcePath.relativize(path).toString()));
- }
- });
- } catch (Exception e) {
- e.printStackTrace();
- throw new IOException("Error encountered during zip operation: " + e.getMessage());
- }
- System.out.println("Conversion complete. Zip file saved and ready for download from " + targetDir + ".zip");
- return zipPath;
- }
- }
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement