-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
285 lines (246 loc) · 9.44 KB
/
script.js
File metadata and controls
285 lines (246 loc) · 9.44 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// State management
const state = {
originalFile: null,
processedFile: null,
originalFileName: ''
};
// DOM Elements
const xmlFileInput = document.getElementById('xmlFile');
const fileLabel = document.getElementById('fileLabel');
const fileInfo = document.getElementById('fileInfo');
const fileName = document.getElementById('fileName');
const fileSize = document.getElementById('fileSize');
const processBtn = document.getElementById('processBtn');
const downloadBtn = document.getElementById('downloadBtn');
const resetBtn = document.getElementById('resetBtn');
const statusMessage = document.getElementById('statusMessage');
const lowerParamsSelect = document.getElementById('lowerParams');
const upperMonitorParamsSelect = document.getElementById('upperMonitorParams');
// Drag and drop functionality
fileLabel.addEventListener('dragover', (e) => {
e.preventDefault();
fileLabel.classList.add('dragover');
});
fileLabel.addEventListener('dragleave', () => {
fileLabel.classList.remove('dragover');
});
fileLabel.addEventListener('drop', (e) => {
e.preventDefault();
fileLabel.classList.remove('dragover');
const files = e.dataTransfer.files;
if (files.length > 0) {
xmlFileInput.files = files;
handleFileSelect();
}
});
// File input change event
xmlFileInput.addEventListener('change', handleFileSelect);
function handleFileSelect() {
const file = xmlFileInput.files[0];
if (file) {
if (!file.name.endsWith('.qxw')) {
showStatus('Please load a valid QXW file', 'error');
xmlFileInput.value = '';
return;
}
state.originalFile = file;
state.originalFileName = file.name;
fileName.textContent = file.name;
fileSize.textContent = (file.size / 1024).toFixed(2) + ' KB';
fileInfo.classList.add('show');
processBtn.disabled = false;
downloadBtn.disabled = true;
state.processedFile = null;
showStatus(`File "${file.name}" loaded successfully`, 'success');
}
}
// Process button click
processBtn.addEventListener('click', async () => {
if (!state.originalFile) {
showStatus('Please load a file first', 'error');
return;
}
try {
processBtn.disabled = true;
showStatus('Processing...', 'info');
// Read the file
const fileContent = await readFileAsText(state.originalFile);
// Get selected MIDI parameters
const lowerParams = lowerParamsSelect.value;
const upperMonitorParams = upperMonitorParamsSelect.value;
// Process the XML
const modifiedContent = processXmlFile(fileContent, lowerParams, upperMonitorParams);
// Store the processed file
state.processedFile = modifiedContent;
downloadBtn.disabled = false;
showStatus('File processed successfully!', 'success');
} catch (error) {
showStatus('Error during processing: ' + error.message, 'error');
} finally {
processBtn.disabled = false;
}
});
// Download button click
downloadBtn.addEventListener('click', () => {
if (!state.processedFile) {
showStatus('No file to download', 'error');
return;
}
downloadFile(state.processedFile, state.originalFileName);
showStatus('Download started!', 'success');
});
// Reset button click
resetBtn.addEventListener('click', () => {
xmlFileInput.value = '';
state.originalFile = null;
state.processedFile = null;
state.originalFileName = '';
fileInfo.classList.remove('show');
processBtn.disabled = true;
downloadBtn.disabled = true;
statusMessage.classList.remove('show');
showStatus('Reset complete', 'info');
});
// ============================================
// XML PROCESSING LOGIC (from magic.py)
// ============================================
/**
* Calculate the Euclidean distance between two RGB colors
* @param {string} color1 - Color 1 in hex format (e.g., "ff0000")
* @param {string} color2 - Color 2 in hex format (e.g., "00ff00")
* @returns {number} Euclidean distance between the two colors
*/
function euclideanDistance(color1, color2) {
const r1 = parseInt(color1.substring(0, 2), 16);
const g1 = parseInt(color1.substring(2, 4), 16);
const b1 = parseInt(color1.substring(4, 6), 16);
const r2 = parseInt(color2.substring(0, 2), 16);
const g2 = parseInt(color2.substring(2, 4), 16);
const b2 = parseInt(color2.substring(4, 6), 16);
return Math.sqrt(
Math.pow(r1 - r2, 2) +
Math.pow(g1 - g2, 2) +
Math.pow(b1 - b2, 2)
);
}
/**
* Find the closest color in the colors array
* @param {string} hexColor - Color in hex format (without #)
* @returns {object|null} The closest color from the colors array
*/
function findCloserColor(hexColor) {
let closerColor = null;
let minDiff = Infinity;
for (const color of colors) {
const colorRgb = color.RGB.substring(1); // Rimuove il #
const diff = euclideanDistance(hexColor, colorRgb);
if (diff < minDiff) {
minDiff = diff;
closerColor = color;
}
}
return closerColor;
}
/**
* Extract the background color value from a Button element
* @param {Element} button - Button element from the XML DOM
* @returns {string|null} The closest color value or null
*/
function getBgColor(button) {
const appearance = button.querySelector('Appearance');
if (appearance) {
const bgColor = appearance.querySelector('BackgroundColor');
if (bgColor) {
const colorValue = bgColor.textContent;
// Check if it's a number
if (/^\d+$/.test(colorValue)) {
// Convert to hex as Python does: hex(int(value))[4:]
const hexValue = parseInt(colorValue).toString(16);
// Python does hex()[4:] which ignores '0x' and takes only the last 6 digits for ARGB
const hexColor = hexValue.length > 6 ? hexValue.substring(hexValue.length - 6) : hexValue.padStart(6, '0');
const closerColor = findCloserColor(hexColor);
return closerColor ? closerColor.value : null;
}
}
}
return null;
}
/**
* Modify the XML file content
* Implements the same logic as magic.py:
* - Find all Buttons
* - For each Button, extract the background color
* - If the Input channel is between 128 and 191, modify the MIDI values
*
* @param {string} xmlContent - The XML content to modify
* @param {string} lowerParams - Value for LowerParams attribute
* @param {string} upperMonitorParams - Value for UpperParams and MonitorParams attributes
* @returns {string} The modified XML content
*/
function processXmlFile(xmlContent, lowerParams = '6', upperMonitorParams = '11') {
// Parse the XML
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlContent, 'text/xml');
// Check for parsing errors
const parserError = xmlDoc.querySelector('parsererror');
if (parserError) {
throw new Error('XML parsing error: ' + parserError.textContent);
}
// Find all Buttons
const buttons = xmlDoc.querySelectorAll('Button');
// Process each button
buttons.forEach(button => {
const colorId = getBgColor(button);
if (colorId !== null) {
// Find the Input element
const input = button.querySelector('Input');
if (input) {
const channel = parseInt(input.getAttribute('Channel'));
// Check if the channel is between 128 and 191
if (channel >= 128 && channel <= 191) {
// Modify attributes with user-selected parameters
input.setAttribute('LowerValue', colorId);
input.setAttribute('UpperValue', colorId);
input.setAttribute('MonitorValue', colorId);
input.setAttribute('LowerParams', lowerParams);
input.setAttribute('UpperParams', upperMonitorParams);
input.setAttribute('MonitorParams', upperMonitorParams);
}
}
}
});
// Serialize the modified XML
const serializer = new XMLSerializer();
return serializer.serializeToString(xmlDoc);
}
// ============================================
// Utility functions
function readFileAsText(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.onerror = (e) => reject(new Error('File reading error'));
reader.readAsText(file);
});
}
function downloadFile(content, originalFileName) {
const element = document.createElement('a');
// Replace both .xml and .qxw with _modified
const fileName = originalFileName.replace(/\.(xml|qxw)$/i, '_modified.$1');
element.setAttribute('href', 'data:text/xml;charset=utf-8,' + encodeURIComponent(content));
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
function showStatus(message, type = 'info') {
statusMessage.textContent = message;
statusMessage.className = `status-message show ${type}`;
// Auto-hide after 5 seconds (except for errors)
if (type !== 'error') {
setTimeout(() => {
statusMessage.classList.remove('show');
}, 5000);
}
}