Skip to content

The swiss army knife of lossless video/audio editing

make dialog button order depend on OS

Mikael Finstad25110639639b
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index 5338ab82..79e90e21 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -67,19 +67,18 @@ import {
getOutPath, getOutDir,
isStoreBuild, dragPreventer,
havePermissionToReadFile, resolvePathIfNeeded, getPathReadAccessError, findExistingHtml5FriendlyFile,
- deleteFiles, isOutOfSpaceError, readFileSize, readFileSizes, checkFileSizes, setDocumentTitle, mustDisallowVob, readVideoTs, readDirRecursively, getImportProjectType,
+ isOutOfSpaceError, readFileSize, readFileSizes, checkFileSizes, setDocumentTitle, readVideoTs, readDirRecursively, getImportProjectType,
calcShouldShowWaveform, calcShouldShowKeyframes, mediaSourceQualities, isExecaError, getStdioString,
isMuxNotSupported,
getDownloadMediaOutPath,
isAbortedError,
shootConfetti,
isMasBuild,
- toastError,
} from './util';
import getSwal, { errorToast, showPlaybackFailedMessage } from './swal';
import { adjustRate } from './util/rate-calculator';
import { askExtractFramesAsImages } from './dialogs/extractFrames';
-import { askForOutDir, askForImportChapters, askForFileOpenAction, showCleanupFilesDialog, showDiskFull, showExportFailedDialog, showConcatFailedDialog, openYouTubeChaptersDialog, showRefuseToOverwrite, showOpenDialog, showMuxNotSupported, promptDownloadMediaUrl, CleanupChoicesType, showOutputNotWritable } from './dialogs';
+import { askForOutDir, askForImportChapters, askForFileOpenAction, showCleanupFilesDialog, showDiskFull, showExportFailedDialog, showConcatFailedDialog, openYouTubeChaptersDialog, showRefuseToOverwrite, showOpenDialog, showMuxNotSupported, promptDownloadMediaUrl, CleanupChoicesType, showOutputNotWritable, deleteFiles, mustDisallowVob, toastError } from './dialogs';
import { openSendReportDialog } from './reporting';
import { fallbackLng } from './i18n';
import { sortSegments, convertSegmentsToChaptersWithGaps, hasAnySegmentOverlap, isDurationValid, getPlaybackAction, getSegmentTags, filterNonMarkers } from './segments';
diff --git a/src/renderer/src/BottomBar.tsx b/src/renderer/src/BottomBar.tsx
index 50efbd36..d6205e6e 100644
--- a/src/renderer/src/BottomBar.tsx
+++ b/src/renderer/src/BottomBar.tsx
@@ -17,13 +17,13 @@ import CaptureFormatButton from './components/CaptureFormatButton';
import Select from './components/Select';
import SimpleModeButton from './components/SimpleModeButton';
-import { withBlur, mirrorTransform, checkAppPath } from './util';
+import { withBlur, mirrorTransform } from './util';
import getSwal from './swal';
import { getSegColor as getSegColorRaw } from './util/colors';
import { useSegColors } from './contexts';
import { isExactDurationMatch } from './util/duration';
import useUserSettings from './hooks/useUserSettings';
-import { askForPlaybackRate } from './dialogs';
+import { askForPlaybackRate, checkAppPath } from './dialogs';
import { FormatTimecode, ParseTimecode, PlaybackMode, SegmentColorIndex, SegmentToExport, StateSegment } from './types';
import { WaveformMode } from '../../../types';
import { Frame } from './ffmpeg';
diff --git a/src/renderer/src/components/Dialog.tsx b/src/renderer/src/components/Dialog.tsx
index 13f088a4..fb300096 100644
--- a/src/renderer/src/components/Dialog.tsx
+++ b/src/renderer/src/components/Dialog.tsx
@@ -4,6 +4,7 @@ import { ReactNode } from 'react';
import styles from './Dialog.module.css';
import { withClass } from './util';
import CloseButtonRaw from './CloseButton';
+import { dialogButtonOrder } from '../util';
export * from '@radix-ui/react-dialog';
@@ -26,7 +27,7 @@ export const CloseButton = () => (
export function ButtonRow({ children }: { children: ReactNode }) {
return (
- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '.5em', justifyContent: 'flex-end', marginTop: '1em' }}>
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '.5em', justifyContent: dialogButtonOrder === 'rtl' ? 'flex-start' : 'flex-end', marginTop: '1em', direction: dialogButtonOrder }}>
{children}
</div>
);
diff --git a/src/renderer/src/dialogs/index.tsx b/src/renderer/src/dialogs/index.tsx
index 52537d2d..6ddd326e 100644
--- a/src/renderer/src/dialogs/index.tsx
+++ b/src/renderer/src/dialogs/index.tsx
@@ -3,16 +3,19 @@ import i18n from 'i18next';
import { Trans } from 'react-i18next';
import invariant from 'tiny-invariant';
import { FaArrowRight, FaExclamationTriangle, FaInfoCircle, FaQuestionCircle } from 'react-icons/fa';
+import ky from 'ky';
+import pMap from 'p-map';
import { formatDuration } from '../util/duration';
import { parseYouTube } from '../edlFormats';
import CopyClipboardButton from '../components/CopyClipboardButton';
import Checkbox from '../components/Checkbox';
-import { isWindows } from '../util';
+import { appPath, isMac, isMasBuild, isWindows, isWindowsStoreBuild, testFailFsOperation, trashFile, unlinkWithRetry } from '../util';
import { ParseTimecode } from '../types';
import { FindKeyframeMode } from '../ffmpeg';
import { dangerColor } from '../colors';
import getSwal from '../swal';
+import isDev from '../isDev';
const remote = window.require('@electron/remote');
const { dialog } = remote;
@@ -622,3 +625,93 @@ export async function promptDownloadMediaUrl(outPath: string) {
await downloadMediaUrl(value, outPath);
return true;
}
+
+
+export async function deleteFiles({ paths, deleteIfTrashFails, signal }: { paths: string[], deleteIfTrashFails?: boolean | undefined, signal: AbortSignal }) {
+ const failedToTrashFiles: string[] = [];
+
+ // eslint-disable-next-line no-restricted-syntax
+ for (const path of paths) {
+ try {
+ if (testFailFsOperation) throw new Error('test trash failure');
+ // eslint-disable-next-line no-await-in-loop
+ await trashFile(path);
+ signal.throwIfAborted();
+ } catch (err) {
+ console.error(err);
+ failedToTrashFiles.push(path);
+ }
+ }
+
+ if (failedToTrashFiles.length === 0) return; // All good!
+
+ if (!deleteIfTrashFails) {
+ const { value } = await getSwal().Swal.fire({
+ icon: 'warning',
+ text: i18n.t('Unable to move file to trash. Do you want to permanently delete it?'),
+ confirmButtonText: i18n.t('Permanently delete'),
+ showCancelButton: true,
+ });
+ if (!value) return;
+ }
+
+ await pMap(failedToTrashFiles, async (path) => unlinkWithRetry(path, { signal }), { concurrency: 5 });
+}
+
+
+export function toastError(err: unknown) {
+ console.error('toastError', err);
+ const text = err instanceof Error ? err.message : String(err);
+ const textTruncated = text.slice(0, 300);
+ getSwal().toast.fire({ icon: 'error', title: i18n.t('Error'), text: textTruncated });
+}
+
+export async function checkAppPath() {
+ try {
+ const forceCheckMs = false;
+ const forceCheckTitle = false;
+ // this code is purposefully obfuscated to try to detect the most basic cloned app submissions to the MS Store
+ // eslint-disable-next-line no-useless-concat, one-var, one-var-declaration-per-line
+ const mf = 'mi' + 'fi.no', ap = 'Los' + 'slessC' + 'ut';
+ let payload: string | undefined;
+ if (isWindowsStoreBuild || (isDev && forceCheckMs)) {
+ const appPathOrMock = isDev ? 'C:\\Program Files\\WindowsApps\\37672NoveltyStudio.MediaConverter_9.0.6.0_x64__vjhnv588cyf84' : appPath;
+ const pathMatch = appPathOrMock.replaceAll('\\', '/').match(/Windows ?Apps\/([^/]+)/); // find the first component after WindowsApps
+ // example pathMatch: 37672NoveltyStudio.MediaConverter_9.0.6.0_x64__vjhnv588cyf84
+ if (!pathMatch) {
+ console.warn('Unknown path match', appPathOrMock);
+ return;
+ }
+ const pathSeg = pathMatch[1];
+ if (pathSeg == null) return;
+ if (pathSeg.startsWith(`57275${mf}.${ap}_`)) return;
+ // this will report the path and may return a msg
+ payload = `msstore-app-id:${pathSeg}`;
+ // also check non ms store fakes (different title:)
+ } else if (isMac || isWindows || (isDev && forceCheckTitle)) {
+ const { title } = document;
+ if (!title.includes(ap)) {
+ payload = `app-title:${title}`;
+ }
+ }
+
+ if (payload) {
+ // eslint-disable-next-line no-useless-concat
+ const url = 'htt' + 'ps:/' + '/los' + 'sles' + 'sc' + 'ut-anal' + 'ytics.mi' + 'fi.n' + `o/${payload.length}/${encodeURIComponent(btoa(payload))}`;
+ // console.log('Reporting app', pathSeg, url);
+ const response = await ky(url).json<{ invalid?: boolean, title: string, text: string }>();
+ if (response.invalid) getSwal().toast.fire({ timer: 60000, icon: 'error', title: response.title, text: response.text });
+ }
+ } catch (err) {
+ if (isDev) console.warn(err instanceof Error && err.message);
+ }
+}
+
+export function mustDisallowVob() {
+ // Because Apple is being nazi about the ability to open "copy protected DVD files"
+ if (isMasBuild) {
+ getSwal().toast.fire({ icon: 'error', text: 'Unfortunately .vob files are not supported in the App Store version of LosslessCut due to Apple restrictions' });
+ return true;
+ }
+ return false;
+}
diff --git a/src/renderer/src/hooks/useSegments.tsx b/src/renderer/src/hooks/useSegments.tsx
index 48914bf0..c871c569 100644
--- a/src/renderer/src/hooks/useSegments.tsx
+++ b/src/renderer/src/hooks/useSegments.tsx
@@ -9,9 +9,9 @@ import { FaLink } from 'react-icons/fa';
import TextInput from '../components/TextInput';
import { detectSceneChanges as ffmpegDetectSceneChanges, readFrames, mapTimesToSegments, findKeyframeNearTime } from '../ffmpeg';
-import { shuffleArray, toastError } from '../util';
+import { shuffleArray } from '../util';
import { errorToast } from '../swal';
-import { createNumSegments as createNumSegmentsDialog, createFixedByteSixedSegments as createFixedByteSixedSegmentsDialog, createRandomSegments as createRandomSegmentsDialog, labelSegmentDialog, askForShiftSegments, askForAlignSegments, selectSegmentsByLabelDialog, askForSegmentDuration } from '../dialogs';
+import { createNumSegments as createNumSegmentsDialog, createFixedByteSixedSegments as createFixedByteSixedSegmentsDialog, createRandomSegments as createRandomSegmentsDialog, labelSegmentDialog, askForShiftSegments, askForAlignSegments, selectSegmentsByLabelDialog, askForSegmentDuration, toastError } from '../dialogs';
import { createSegment, sortSegments, invertSegments, combineOverlappingSegments as combineOverlappingSegments2, combineSelectedSegments as combineSelectedSegments2, isDurationValid, addSegmentColorIndex, filterNonMarkers, makeDurationSegments, isInitialSegment } from '../segments';
import { parameters as allFfmpegParameters, FfmpegDialog, getHint, getLabel } from '../ffmpegParameters';
import { maxSegmentsAllowed } from '../util/constants';
diff --git a/src/renderer/src/swal.ts b/src/renderer/src/swal.ts
index 9fd2747e..b109d176 100644
--- a/src/renderer/src/swal.ts
+++ b/src/renderer/src/swal.ts
@@ -4,7 +4,7 @@ import withReactContent, { ReactSweetAlert, SweetAlert2 } from 'sweetalert2-reac
import i18n from './i18n';
import { emitter as animationsEmitter } from './animations';
-
+import { dialogButtonOrder } from './util';
export const swalContainerWrapperId = 'swal2-container-wrapper';
@@ -27,6 +27,7 @@ function initSwal(reducedMotion = false) {
icon: '',
},
}),
+ reverseButtons: dialogButtonOrder === 'ltr',
};
Swal = SwalRaw.mixin({
@@ -46,7 +47,6 @@ function initSwal(reducedMotion = false) {
self.addEventListener('mouseenter', Swal.stopTimer);
self.addEventListener('mouseleave', Swal.resumeTimer);
},
- reverseButtons: true,
});
ReactSwal = withReactContent(Swal);
diff --git a/src/renderer/src/util.ts b/src/renderer/src/util.ts
index 2a57fc9d..42de0a0e 100644
--- a/src/renderer/src/util.ts
+++ b/src/renderer/src/util.ts
@@ -1,6 +1,5 @@
import i18n from 'i18next';
import pMap from 'p-map';
-import ky from 'ky';
import prettyBytes from 'pretty-bytes';
import sortBy from 'lodash/sortBy';
import pRetry, { Options } from 'p-retry';
@@ -8,11 +7,9 @@ import { ExecaError } from 'execa';
import confetti from 'canvas-confetti';
import invariant from 'tiny-invariant';
-import isDev from './isDev';
import { ffmpegExtractWindow } from './util/constants';
import { appName } from '../../main/common';
import { Html5ifyMode } from '../../../types';
-import getSwal from './swal';
import { UserFacingError } from '../errors';
const { dirname, parse: parsePath, join, extname, isAbsolute, resolve, basename } = window.require('path');
@@ -28,7 +25,7 @@ const appPath = remote.app.getAppPath();
export { isWindows, isMac, appVersion, appPath };
-const trashFile = async (path: string) => ipcRenderer.invoke('tryTrashItem', path);
+export const trashFile = async (path: string) => ipcRenderer.invoke('tryTrashItem', path);
export const showItemInFolder = async (path: string) => ipcRenderer.invoke('showItemInFolder', path);
@@ -111,8 +108,8 @@ export async function dirExists(dirPath: string) {
return (await pathExists(dirPath)) && (await lstat(dirPath)).isDirectory();
}
-// const testFailFsOperation = isDev;
-const testFailFsOperation = false;
+// export const testFailFsOperation = isDev;
+export const testFailFsOperation = false;
// Retry because sometimes write operations fail on windows due to the file being locked for various reasons (often anti-virus) #272 #1797 #1704
export async function fsOperationWithRetry(operation: () => Promise<unknown>, { signal, retries = 10, minTimeout = 100, maxTimeout = 2000, ...opts }: Options & { retries?: number | undefined, minTimeout?: number | undefined, maxTimeout?: number | undefined } = {}) {
@@ -270,36 +267,6 @@ export function getHtml5ifiedPath(cod: string | undefined, fp: string, type: Htm
return getSuffixedOutPath({ customOutDir: cod, filePath: fp, nameSuffix: `${html5ifiedPrefix}${type}.${ext}` });
}
-export async function deleteFiles({ paths, deleteIfTrashFails, signal }: { paths: string[], deleteIfTrashFails?: boolean | undefined, signal: AbortSignal }) {
- const failedToTrashFiles: string[] = [];
-
- // eslint-disable-next-line no-restricted-syntax
- for (const path of paths) {
- try {
- if (testFailFsOperation) throw new Error('test trash failure');
- // eslint-disable-next-line no-await-in-loop
- await trashFile(path);
- signal.throwIfAborted();
- } catch (err) {
- console.error(err);
- failedToTrashFiles.push(path);
- }
- }
-
- if (failedToTrashFiles.length === 0) return; // All good!
-
- if (!deleteIfTrashFails) {
- const { value } = await getSwal().Swal.fire({
- icon: 'warning',
- text: i18n.t('Unable to move file to trash. Do you want to permanently delete it?'),
- confirmButtonText: i18n.t('Permanently delete'),
- showCancelButton: true,
- });
- if (!value) return;
- }
-
- await pMap(failedToTrashFiles, async (path) => unlinkWithRetry(path, { signal }), { concurrency: 5 });
-}
export const deleteDispositionValue = 'llc_disposition_remove';
@@ -335,54 +302,6 @@ export const isMuxNotSupported = (err: InvariantExecaError) => (
&& /Could not write header .*incorrect codec parameters .*Invalid argument/.test(getStdioString(err.stderr) ?? '')
);
-export function toastError(err: unknown) {
- console.error('toastError', err);
- const text = err instanceof Error ? err.message : String(err);
- const textTruncated = text.slice(0, 300);
- getSwal().toast.fire({ icon: 'error', title: i18n.t('Error'), text: textTruncated });
-}
-
-export async function checkAppPath() {
- try {
- const forceCheckMs = false;
- const forceCheckTitle = false;
- // this code is purposefully obfuscated to try to detect the most basic cloned app submissions to the MS Store
- // eslint-disable-next-line no-useless-concat, one-var, one-var-declaration-per-line
- const mf = 'mi' + 'fi.no', ap = 'Los' + 'slessC' + 'ut';
- let payload: string | undefined;
- if (isWindowsStoreBuild || (isDev && forceCheckMs)) {
- const appPathOrMock = isDev ? 'C:\\Program Files\\WindowsApps\\37672NoveltyStudio.MediaConverter_9.0.6.0_x64__vjhnv588cyf84' : appPath;
- const pathMatch = appPathOrMock.replaceAll('\\', '/').match(/Windows ?Apps\/([^/]+)/); // find the first component after WindowsApps
- // example pathMatch: 37672NoveltyStudio.MediaConverter_9.0.6.0_x64__vjhnv588cyf84
- if (!pathMatch) {
- console.warn('Unknown path match', appPathOrMock);
- return;
- }
- const pathSeg = pathMatch[1];
- if (pathSeg == null) return;
- if (pathSeg.startsWith(`57275${mf}.${ap}_`)) return;
- // this will report the path and may return a msg
- payload = `msstore-app-id:${pathSeg}`;
- // also check non ms store fakes (different title:)
- } else if (isMac || isWindows || (isDev && forceCheckTitle)) {
- const { title } = document;
- if (!title.includes(ap)) {
- payload = `app-title:${title}`;
- }
- }
-
- if (payload) {
- // eslint-disable-next-line no-useless-concat
- const url = 'htt' + 'ps:/' + '/los' + 'sles' + 'sc' + 'ut-anal' + 'ytics.mi' + 'fi.n' + `o/${payload.length}/${encodeURIComponent(btoa(payload))}`;
- // console.log('Reporting app', pathSeg, url);
- const response = await ky(url).json<{ invalid?: boolean, title: string, text: string }>();
- if (response.invalid) getSwal().toast.fire({ timer: 60000, icon: 'error', title: response.title, text: response.text });
- }
- } catch (err) {
- if (isDev) console.warn(err instanceof Error && err.message);
- }
-}
-
// https://stackoverflow.com/a/2450976/6519037
export function shuffleArray<T>(arrayIn: T[]) {
const array = [...arrayIn];
@@ -444,15 +363,6 @@ export function setDocumentTitle({ filePath, working, progress }: {
document.title = parts.join(' - ');
}
-export function mustDisallowVob() {
- // Because Apple is being nazi about the ability to open "copy protected DVD files"
- if (isMasBuild) {
- getSwal().toast.fire({ icon: 'error', text: 'Unfortunately .vob files are not supported in the App Store version of LosslessCut due to Apple restrictions' });
- return true;
- }
- return false;
-}
-
export async function readVideoTs(videoTsPath: string) {
const files = await readdir(videoTsPath);
const relevantFiles = files.filter((file) => /^vts_\d+_\d+\.vob$/i.test(file) && !/^vts_\d+_00\.vob$/i.test(file)); // skip menu
@@ -507,6 +417,8 @@ export function getMetaKeyName() {
return i18n.t('Meta');
}
+export const dialogButtonOrder = isWindows ? 'rtl' : 'ltr'; // use ltr for mac and linux, rtl for windows
+
export function formatKeyboardKey(key: string) {
const map: Record<string, string> = {
Escape: 'Esc',