Skip to content

Commit

Permalink
improve "Resulting file names"
Browse files Browse the repository at this point in the history
make it show the actual resulting file names (if error) #1732
  • Loading branch information
mifi committed Oct 15, 2023
1 parent a3cbce6 commit 7f1fbe4
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 58 deletions.
17 changes: 7 additions & 10 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ import { askForOutDir, askForImportChapters, promptTimeOffset, askForFileOpenAct
import { openSendReportDialog } from './reporting';
import { fallbackLng } from './i18n';
import { createSegment, getCleanCutSegments, findSegmentsAtCursor, sortSegments, convertSegmentsToChapters, hasAnySegmentOverlap, isDurationValid, playOnlyCurrentSegment } from './segments';
import { getOutSegError as getOutSegErrorRaw, generateOutSegFileNames as generateOutSegFileNamesRaw, defaultOutSegTemplate } from './util/outputNameTemplate';
import { generateOutSegFileNames as generateOutSegFileNamesRaw, defaultOutSegTemplate } from './util/outputNameTemplate';
import { rightBarWidth, leftBarWidth, ffmpegExtractWindow, zoomMax } from './util/constants';
import BigWaveform from './components/BigWaveform';

Expand Down Expand Up @@ -1114,10 +1114,8 @@ const App = memo(() => {
}, [cleanupFilesWithDialog, isFileOpened, setWorking]);

const generateOutSegFileNames = useCallback(({ segments = segmentsToExport, template, forceSafeOutputFileName }) => (
generateOutSegFileNamesRaw({ segments, template, forceSafeOutputFileName, formatTimecode, isCustomFormatSelected, fileFormat, filePath, safeOutputFileName, maxLabelLength, outputFileNameMinZeroPadding })
), [fileFormat, filePath, formatTimecode, isCustomFormatSelected, maxLabelLength, outputFileNameMinZeroPadding, safeOutputFileName, segmentsToExport]);

const getOutSegError = useCallback((fileNames) => getOutSegErrorRaw({ fileNames, filePath, outputDir, safeOutputFileName }), [filePath, outputDir, safeOutputFileName]);
generateOutSegFileNamesRaw({ segments, template, forceSafeOutputFileName, formatTimecode, isCustomFormatSelected, fileFormat, filePath, outputDir, safeOutputFileName, maxLabelLength, outputFileNameMinZeroPadding })
), [fileFormat, filePath, formatTimecode, isCustomFormatSelected, maxLabelLength, outputDir, outputFileNameMinZeroPadding, safeOutputFileName, segmentsToExport]);

const closeExportConfirm = useCallback(() => setExportConfirmVisible(false), []);

Expand Down Expand Up @@ -1168,10 +1166,9 @@ const App = memo(() => {

console.log('outSegTemplateOrDefault', outSegTemplateOrDefault);

let outSegFileNames = generateOutSegFileNames({ segments: segmentsToExport, template: outSegTemplateOrDefault });
if (getOutSegError(outSegFileNames) != null) {
const { outSegFileNames, outSegError } = generateOutSegFileNames({ segments: segmentsToExport, template: outSegTemplateOrDefault });
if (outSegError != null) {
console.warn('Output segments file name invalid, using default instead', outSegFileNames);
outSegFileNames = generateOutSegFileNames({ segments: segmentsToExport, template: defaultOutSegTemplate, forceSafeOutputFileName: true });
}

// throw (() => { const err = new Error('test'); err.code = 'ENOENT'; return err; })();
Expand Down Expand Up @@ -1276,7 +1273,7 @@ const App = memo(() => {
setWorking();
setCutProgress();
}
}, [numStreamsToCopy, segmentsToExport, haveInvalidSegs, setWorking, segmentsToChaptersOnly, outSegTemplateOrDefault, generateOutSegFileNames, getOutSegError, cutMultiple, outputDir, customOutDir, fileFormat, duration, isRotationSet, effectiveRotation, copyFileStreams, allFilesMeta, keyframeCut, shortestFlag, ffmpegExperimental, preserveMovData, preserveMetadataOnMerge, movFastStart, avoidNegativeTs, customTagsByFile, paramsByStreamId, detectedFps, willMerge, enableOverwriteOutput, exportConfirmEnabled, mainFileFormatData, mainStreams, exportExtraStreams, areWeCutting, mergedOutFilePath, hideAllNotifications, cleanupChoices.cleanupAfterExport, cleanupFilesWithDialog, selectedSegmentsOrInverse, segmentsToChapters, invertCutSegments, autoConcatCutSegments, autoDeleteMergedSegments, nonCopiedExtraStreams, filePath, handleExportFailed]);
}, [numStreamsToCopy, segmentsToExport, haveInvalidSegs, setWorking, segmentsToChaptersOnly, outSegTemplateOrDefault, generateOutSegFileNames, cutMultiple, outputDir, customOutDir, fileFormat, duration, isRotationSet, effectiveRotation, copyFileStreams, allFilesMeta, keyframeCut, shortestFlag, ffmpegExperimental, preserveMovData, preserveMetadataOnMerge, movFastStart, avoidNegativeTs, customTagsByFile, paramsByStreamId, detectedFps, willMerge, enableOverwriteOutput, exportConfirmEnabled, mainFileFormatData, mainStreams, exportExtraStreams, areWeCutting, mergedOutFilePath, hideAllNotifications, cleanupChoices.cleanupAfterExport, cleanupFilesWithDialog, selectedSegmentsOrInverse, segmentsToChapters, invertCutSegments, autoConcatCutSegments, autoDeleteMergedSegments, nonCopiedExtraStreams, filePath, handleExportFailed]);

const onExportPress = useCallback(async () => {
if (!filePath) return;
Expand Down Expand Up @@ -2538,7 +2535,7 @@ const App = memo(() => {
)}
</Sheet>

<ExportConfirm filePath={filePath} areWeCutting={areWeCutting} nonFilteredSegmentsOrInverse={nonFilteredSegmentsOrInverse} selectedSegments={selectedSegmentsOrInverse} segmentsToExport={segmentsToExport} willMerge={willMerge} visible={exportConfirmVisible} onClosePress={closeExportConfirm} onExportConfirm={onExportConfirm} renderOutFmt={renderOutFmt} outputDir={outputDir} numStreamsTotal={numStreamsTotal} numStreamsToCopy={numStreamsToCopy} onShowStreamsSelectorClick={handleShowStreamsSelectorClick} outFormat={fileFormat} setOutSegTemplate={setOutSegTemplate} outSegTemplate={outSegTemplateOrDefault} generateOutSegFileNames={generateOutSegFileNames} currentSegIndexSafe={currentSegIndexSafe} getOutSegError={getOutSegError} mainCopiedThumbnailStreams={mainCopiedThumbnailStreams} needSmartCut={needSmartCut} mergedOutFileName={mergedOutFileName} setMergedOutFileName={setMergedOutFileName} />
<ExportConfirm filePath={filePath} areWeCutting={areWeCutting} nonFilteredSegmentsOrInverse={nonFilteredSegmentsOrInverse} selectedSegments={selectedSegmentsOrInverse} segmentsToExport={segmentsToExport} willMerge={willMerge} visible={exportConfirmVisible} onClosePress={closeExportConfirm} onExportConfirm={onExportConfirm} renderOutFmt={renderOutFmt} outputDir={outputDir} numStreamsTotal={numStreamsTotal} numStreamsToCopy={numStreamsToCopy} onShowStreamsSelectorClick={handleShowStreamsSelectorClick} outFormat={fileFormat} setOutSegTemplate={setOutSegTemplate} outSegTemplate={outSegTemplateOrDefault} generateOutSegFileNames={generateOutSegFileNames} currentSegIndexSafe={currentSegIndexSafe} mainCopiedThumbnailStreams={mainCopiedThumbnailStreams} needSmartCut={needSmartCut} mergedOutFileName={mergedOutFileName} setMergedOutFileName={setMergedOutFileName} />

<LastCommandsSheet
visible={lastCommandsVisible}
Expand Down
4 changes: 2 additions & 2 deletions src/components/ExportConfirm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const HelpIcon = ({ onClick, style }) => <IoIosHelpCircle size={20} role="button
const ExportConfirm = memo(({
areWeCutting, selectedSegments, segmentsToExport, willMerge, visible, onClosePress, onExportConfirm,
outFormat, renderOutFmt, outputDir, numStreamsTotal, numStreamsToCopy, onShowStreamsSelectorClick, outSegTemplate,
setOutSegTemplate, generateOutSegFileNames, filePath, currentSegIndexSafe, getOutSegError, nonFilteredSegmentsOrInverse,
setOutSegTemplate, generateOutSegFileNames, filePath, currentSegIndexSafe, nonFilteredSegmentsOrInverse,
mainCopiedThumbnailStreams, needSmartCut, mergedOutFileName, setMergedOutFileName,
}) => {
const { t } = useTranslation();
Expand Down Expand Up @@ -191,7 +191,7 @@ const ExportConfirm = memo(({
{canEditTemplate && (
<tr>
<td colSpan={2}>
<OutSegTemplateEditor filePath={filePath} outSegTemplate={outSegTemplate} setOutSegTemplate={setOutSegTemplate} generateOutSegFileNames={generateOutSegFileNames} currentSegIndexSafe={currentSegIndexSafe} getOutSegError={getOutSegError} />
<OutSegTemplateEditor filePath={filePath} outSegTemplate={outSegTemplate} setOutSegTemplate={setOutSegTemplate} generateOutSegFileNames={generateOutSegFileNames} currentSegIndexSafe={currentSegIndexSafe} />
</td>
<td>
<HelpIcon onClick={onOutSegTemplateHelpPress} />
Expand Down
3 changes: 1 addition & 2 deletions src/components/OutSegTemplateEditor.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,8 @@ const OutSegTemplateEditor = memo(({ outSegTemplate, setOutSegTemplate, generate
if (debouncedText == null) return;

try {
const newOutSegFileNames = generateOutSegFileNames({ template: debouncedText });
const { outSegFileNames: newOutSegFileNames, outSegError } = generateOutSegFileNames({ template: debouncedText });
setOutSegFileNames(newOutSegFileNames);
const outSegError = getOutSegError(newOutSegFileNames);
if (outSegError) {
setError(outSegError);
setValidText();
Expand Down
98 changes: 54 additions & 44 deletions src/util/outputNameTemplate.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ export const segSuffixVariable = 'SEG_SUFFIX';

const { parse: parsePath, sep: pathSep, join: pathJoin, normalize: pathNormalize } = window.require('path');

// eslint-disable-next-line import/prefer-default-export
export function getOutSegError({ fileNames, filePath, outputDir, safeOutputFileName }) {
function getOutSegError({ fileNames, filePath, outputDir, safeOutputFileName }) {
let error;

// eslint-disable-next-line no-restricted-syntax
Expand Down Expand Up @@ -90,49 +89,60 @@ function interpolateSegmentFileName({ template, epochMs, inputFileNameWithoutExt
return compiled(data);
}

export function generateOutSegFileNames({ segments, template, forceSafeOutputFileName, formatTimecode, isCustomFormatSelected, fileFormat, filePath, safeOutputFileName, maxLabelLength, outputFileNameMinZeroPadding }) {
const epochMs = Date.now();

return segments.map((segment, i) => {
const { start, end, name = '' } = segment;
const segNum = formatSegNum(i, segments.length, outputFileNameMinZeroPadding);
export function generateOutSegFileNames({ segments, template: desiredTemplate, formatTimecode, isCustomFormatSelected, fileFormat, filePath, outputDir, safeOutputFileName, maxLabelLength, outputFileNameMinZeroPadding }) {
function generate({ template, forceSafeOutputFileName }) {
const epochMs = Date.now();

return segments.map((segment, i) => {
const { start, end, name = '' } = segment;
const segNum = formatSegNum(i, segments.length, outputFileNameMinZeroPadding);

// Fields that did not come from the source file's name must be sanitized, because they may contain characters that are not supported by the target operating/file system
// however we disable this when the user has chosen to (safeOutputFileName === false)
const filenamifyOrNot = (fileName) => (safeOutputFileName || forceSafeOutputFileName ? filenamify(fileName) : fileName).substr(0, maxLabelLength);

function getSegSuffix() {
if (name) return `-${filenamifyOrNot(name)}`;
// https://github.com/mifi/lossless-cut/issues/583
if (segments.length > 1) return `-seg${segNum}`;
return '';
}

const { name: inputFileNameWithoutExt } = parsePath(filePath);

const segFileName = interpolateSegmentFileName({
template,
epochMs,
segNum,
inputFileNameWithoutExt,
segSuffix: getSegSuffix(),
ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath }),
segLabel: filenamifyOrNot(name),
cutFrom: formatTimecode({ seconds: start, fileNameFriendly: true }),
cutTo: formatTimecode({ seconds: end, fileNameFriendly: true }),
tags: Object.fromEntries(Object.entries(getSegmentTags(segment)).map(([tag, value]) => [tag, filenamifyOrNot(value)])),
});

// Now split the path by its separator, so we can check the actual file name (last path seg)
const pathSegs = segFileName.split(pathSep);
if (pathSegs.length === 0) return '';
const [lastSeg] = pathSegs.slice(-1);
const rest = pathSegs.slice(0, -1);

return [
...rest,
// If sanitation is enabled, make sure filename (last seg of the path) is not too long
safeOutputFileName ? lastSeg.substring(0, 200) : lastSeg,
].join(pathSep);
});
}

// Fields that did not come from the source file's name must be sanitized, because they may contain characters that are not supported by the target operating/file system
// however we disable this when the user has chosen to (safeOutputFileName === false)
const filenamifyOrNot = (fileName) => (safeOutputFileName || forceSafeOutputFileName ? filenamify(fileName) : fileName).substr(0, maxLabelLength);
let outSegFileNames = generate({ template: desiredTemplate, forceSafeOutputFileName: false });

function getSegSuffix() {
if (name) return `-${filenamifyOrNot(name)}`;
// https://github.com/mifi/lossless-cut/issues/583
if (segments.length > 1) return `-seg${segNum}`;
return '';
}

const { name: inputFileNameWithoutExt } = parsePath(filePath);

const segFileName = interpolateSegmentFileName({
template,
epochMs,
segNum,
inputFileNameWithoutExt,
segSuffix: getSegSuffix(),
ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath }),
segLabel: filenamifyOrNot(name),
cutFrom: formatTimecode({ seconds: start, fileNameFriendly: true }),
cutTo: formatTimecode({ seconds: end, fileNameFriendly: true }),
tags: Object.fromEntries(Object.entries(getSegmentTags(segment)).map(([tag, value]) => [tag, filenamifyOrNot(value)])),
});
const outSegError = getOutSegError({ fileNames: outSegFileNames, filePath, outputDir, safeOutputFileName });
if (outSegError != null) {
outSegFileNames = generate({ template: defaultOutSegTemplate, forceSafeOutputFileName: true });
}

// Now split the path by its separator, so we can check the actual file name (last path seg)
const pathSegs = segFileName.split(pathSep);
if (pathSegs.length === 0) return '';
const [lastSeg] = pathSegs.slice(-1);
const rest = pathSegs.slice(0, -1);

return [
...rest,
// If sanitation is enabled, make sure filename (last seg of the path) is not too long
safeOutputFileName ? lastSeg.substring(0, 200) : lastSeg,
].join(pathSep);
});
return { outSegFileNames, outSegError };
}

0 comments on commit 7f1fbe4

Please sign in to comment.