1
0
mirror of https://github.com/laurent22/joplin.git synced 2026-04-18 19:42:23 +02:00

Compare commits

..

37 Commits

Author SHA1 Message Date
Laurent Cozic 17a7fcff2d fixed tests 2026-04-17 08:40:24 +01:00
Laurent Cozic a937934bb1 update 2026-04-17 07:32:49 +01:00
renovate[bot] 0fe4de184d chore(deps): update dependency sass to v1.97.2 (#15131)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-04-17 00:05:57 +00:00
summoner 594d70fc88 ALL: Translation: Update hu_HU.po (#15125) 2026-04-16 17:15:38 -04:00
renovate[bot] 8358a2a9f2 chore(deps): update dependency sass to v1.97.0 (#15121)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-04-16 21:41:43 +01:00
Henry Heino 67e51bff41 Desktop: Importing from OneNote: Disable unresponsiveness warning while importing (#15127) 2026-04-16 21:35:52 +01:00
renovate[bot] 7acdb9b67e fix(deps): update dependency @react-native-community/push-notification-ios to v1.12.0 (#15126)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-04-16 21:06:08 +01:00
renovate[bot] e0410db26c chore(deps): update dependency @docusaurus/plugin-sitemap to v3.9.2 (#15123)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-04-16 15:56:34 +00:00
Henry Heino 4387c82fda Desktop: Fixes #15092: Importing from OneNote: Support importing nested ink containers (#15109) 2026-04-16 16:54:00 +01:00
Sriram Varun Kumar 7f2e78bee5 Mobile: Fixes #15071: Fix share error toast cut off on Android 15+ (#15072) 2026-04-16 12:16:53 +01:00
Dmitriy Q b9fb6cbd33 Update russian translate (#15080) 2026-04-16 12:15:53 +01:00
renovate[bot] 953d8fc050 chore(deps): update dependency @docusaurus/plugin-sitemap to v3 (#15096)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-04-16 12:15:10 +01:00
Laurent Cozic 26160b7924 Desktop: Fix copy/paste not working in Settings text fields (#15099) 2026-04-16 12:04:09 +01:00
Henry Heino 738a83c57c Mobile: Fixes #14975: Fix E2EE password validation: Upgrade react-native-quick-crypto to v1.0.19 (#15103) 2026-04-16 12:03:31 +01:00
Henry Heino b5abc12486 Desktop: Importing from OneNote: Fix incorrect import of vertically-scaled ink (#15110) 2026-04-16 12:02:12 +01:00
Henry Heino 9a1b978288 Chore: Desktop: Importing from OneNote: Fix character escaping when building output (#15114) 2026-04-16 11:53:59 +01:00
Laurent Cozic 270a2d0a3a Desktop: Resolves #14788: Add sync status icon and collapsible sync report to sidebar (#15115) 2026-04-16 11:53:44 +01:00
Henry Heino 4b9918a770 Desktop: Importing from OneNote: Fix large .one files with many attachments fail to import (#15117) 2026-04-16 11:53:35 +01:00
Sriram Varun Kumar 400dc70f32 Mobile: Fixes #15116: Fix markdown editor not scrolling to search results (#15119) 2026-04-16 11:52:55 +01:00
Laurent Cozic babea9f388 Desktop: Fixes #15100: Fix pasting images from clipboard when no image/* format is reported (#15101) 2026-04-16 11:42:25 +01:00
Laurent Cozic 3279ea227a Chore: Trying to make CodeRabbit less noisy 2026-04-15 21:39:05 +01:00
mrjo118 cbdb3f124a Mobile: Remove unnecessary padding at bottom of note in view mode (#15108) 2026-04-15 10:46:59 +01:00
Joplin Bot 94560fb340 Doc: Auto-update documentation
Auto-updated using release-website.sh
2026-04-14 19:26:05 +00:00
Laurent Cozic 1f0519722f Android 3.6.16 2026-04-14 17:01:31 +01:00
Laurent Cozic 1548d7008f Doc: Tell Claude what commands to use to compile TypeScript files 2026-04-14 16:08:15 +01:00
Laurent Cozic d406e27f28 Doc: Update Claude instructions for spell checking 2026-04-14 13:07:03 +01:00
Laurent Cozic e3a55ad1c6 Chore: Handle new Renovate commit message format in git-changelog 2026-04-14 13:06:40 +01:00
Laurent Cozic be1a018746 Desktop release v3.6.9 2026-04-14 13:00:42 +01:00
Laurent Cozic ae390469b5 Lock file 2026-04-14 12:57:10 +01:00
Laurent Cozic c31a7392cc Chore: Add android-log command to package.json 2026-04-14 12:56:50 +01:00
Henry Heino 9ca213cefd Desktop: Fixes #15029: Accessibility: Fix focus unexpectedly jumps to the note list while editing/navigating (#15090) 2026-04-14 11:12:12 +01:00
Henry Heino a6a5ab9bc9 Desktop: Markdown editor: Fix unselected <span>s are hidden in HTML notes (#15089) 2026-04-14 11:12:01 +01:00
Henry Heino 0a94d02795 Chore: Importing from OneNote: Add debug tool for inspecting .one files (#15084) 2026-04-14 11:07:46 +01:00
Sriram Varun Kumar 222bb002c8 Mobile: Fixes #15061: Fix profile list not scrollable to last item on Manage Profiles screen (#15074) 2026-04-14 10:53:27 +01:00
Sriram Varun Kumar af8eb30844 Mobile: Fixes #15060: Fix shared note not persisted to active notebook (#15064) 2026-04-14 10:51:34 +01:00
Ashutosh Singh cb009cb084 Desktop: Fixes #11805: Add global shortcut to show/hide Joplin (#15013)
Co-authored-by: Ashutoshx7 <ashutoshx7@gmail.com>
2026-04-14 10:03:01 +01:00
Laurent Cozic fc212d0144 Add note on running yarn updateIgnored for TypeScript
Added a note about running 'yarn updateIgnored' after adding a new TypeScript file.
2026-04-13 18:38:14 +01:00
102 changed files with 7502 additions and 1020 deletions
+18 -16
View File
@@ -4,9 +4,11 @@ reviews:
high_level_summary: false
estimate_code_review_effort: false
poem: false
review_status: false
review_details: false
auto_review:
enabled: true
drafts: false
drafts: true
ignore_usernames:
- "renovate[bot]"
auto_apply_labels: true
@@ -86,21 +88,21 @@ reviews:
- label: "windows"
instructions: "Apply when the PR is mainly about changes specific to Windows"
pre_merge_checks:
description:
mode: "warning"
custom_checks:
- name: "PR Description Must Follow Guidelines"
mode: "error"
instructions: |
Fail if the pull request description does not include clear sections for:
- Problem or user-impact description
- A high-level Solution explanation
- Any Test Plan or verification steps
The description should align with our PR guidelines
at https://github.com/joplin/gsoc/blob/master/pull_request_guidelines.md
and should not just restate the diff or implementation details.
# pre_merge_checks:
# description:
# mode: "warning"
# custom_checks:
# - name: "PR Description Must Follow Guidelines"
# mode: "error"
# instructions: |
# Fail if the pull request description does not include clear sections for:
# - Problem or user-impact description
# - A high-level Solution explanation
# - Any Test Plan or verification steps
#
# The description should align with our PR guidelines
# at https://github.com/joplin/gsoc/blob/master/pull_request_guidelines.md
# and should not just restate the diff or implementation details.
knowledge_base:
code_guidelines:
enabled: true
+2 -2
View File
@@ -201,6 +201,8 @@ packages/app-desktop/gui/ConfigScreen/ButtonBar.js
packages/app-desktop/gui/ConfigScreen/ConfigScreen.js
packages/app-desktop/gui/ConfigScreen/Sidebar.js
packages/app-desktop/gui/ConfigScreen/controls/FontSearch.js
packages/app-desktop/gui/ConfigScreen/controls/GlobalHotkeyInput.test.js
packages/app-desktop/gui/ConfigScreen/controls/GlobalHotkeyInput.js
packages/app-desktop/gui/ConfigScreen/controls/MissingPasswordHelpLink.js
packages/app-desktop/gui/ConfigScreen/controls/SettingComponent.js
packages/app-desktop/gui/ConfigScreen/controls/SettingDescription.js
@@ -358,8 +360,6 @@ packages/app-desktop/gui/NoteList/utils/useMoveNote.js
packages/app-desktop/gui/NoteList/utils/useOnKeyDown.js
packages/app-desktop/gui/NoteList/utils/useOnNoteClick.js
packages/app-desktop/gui/NoteList/utils/useOnNoteDoubleClick.js
packages/app-desktop/gui/NoteList/utils/useRefocusOnDeletion.test.js
packages/app-desktop/gui/NoteList/utils/useRefocusOnDeletion.js
packages/app-desktop/gui/NoteList/utils/useScroll.js
packages/app-desktop/gui/NoteList/utils/useVisibleRange.test.js
packages/app-desktop/gui/NoteList/utils/useVisibleRange.js
+2 -2
View File
@@ -174,6 +174,8 @@ packages/app-desktop/gui/ConfigScreen/ButtonBar.js
packages/app-desktop/gui/ConfigScreen/ConfigScreen.js
packages/app-desktop/gui/ConfigScreen/Sidebar.js
packages/app-desktop/gui/ConfigScreen/controls/FontSearch.js
packages/app-desktop/gui/ConfigScreen/controls/GlobalHotkeyInput.test.js
packages/app-desktop/gui/ConfigScreen/controls/GlobalHotkeyInput.js
packages/app-desktop/gui/ConfigScreen/controls/MissingPasswordHelpLink.js
packages/app-desktop/gui/ConfigScreen/controls/SettingComponent.js
packages/app-desktop/gui/ConfigScreen/controls/SettingDescription.js
@@ -331,8 +333,6 @@ packages/app-desktop/gui/NoteList/utils/useMoveNote.js
packages/app-desktop/gui/NoteList/utils/useOnKeyDown.js
packages/app-desktop/gui/NoteList/utils/useOnNoteClick.js
packages/app-desktop/gui/NoteList/utils/useOnNoteDoubleClick.js
packages/app-desktop/gui/NoteList/utils/useRefocusOnDeletion.test.js
packages/app-desktop/gui/NoteList/utils/useRefocusOnDeletion.js
packages/app-desktop/gui/NoteList/utils/useScroll.js
packages/app-desktop/gui/NoteList/utils/useVisibleRange.test.js
packages/app-desktop/gui/NoteList/utils/useVisibleRange.js
+3
View File
@@ -11,6 +11,9 @@
- Focus on testing essential behaviour and edge cases — avoid adding tests for every minor detail.
- Avoid duplicating code in tests; when testing the same logic with different inputs, use `test.each` or shared helpers instead of repeating similar test blocks.
- Do not make white space changes - do not add unnecessary new lines, or spaces to existing code, or wrap existing code.
- If you add a new TypeScript file, run `yarn updateIgnored` from the root.
- When an unknown word is detected by cSpell, handle is as per the specification in `readme/dev/spellcheck.md`
- To compile TypeScript, use `yarn tsc`. To type-check without emitting files, use `yarn tsc --noEmit`.
## Full Documentation
@@ -59,6 +59,7 @@ export default class ElectronAppWrapper {
private secondaryWindows_: Map<SecondaryWindowId, SecondaryWindowData> = new Map();
private willQuitApp_ = false;
private enableUnresponsiveCheck_ = true;
private tray_: Tray = null;
private buildDir_: string = null;
private rendererProcessQuitReply_: RendererProcessQuitReply = null;
@@ -307,6 +308,8 @@ export default class ElectronAppWrapper {
let unresponsiveTimeout: ReturnType<typeof setTimeout>|null = null;
this.win_.webContents.on('unresponsive', () => {
if (!this.enableUnresponsiveCheck_) return;
// Don't show the "unresponsive" dialog immediately -- the "unresponsive" event
// can be fired when showing a dialog or modal (e.g. the update dialog).
//
@@ -896,6 +899,10 @@ export default class ElectronAppWrapper {
return this.customProtocolHandlers_.pluginContent;
}
public setEnableUnresponsiveCheck(enabled: boolean) {
this.enableUnresponsiveCheck_ = enabled;
}
private async fixLinuxAccessibility_() {
if (this.electronApp().accessibilitySupportEnabled) return;
@@ -939,6 +946,7 @@ export default class ElectronAppWrapper {
this.electronApp_.on('before-quit', () => {
this.appLogger_.info('[appClose] before-quit event fired, setting willQuitApp_ = true');
this.willQuitApp_ = true;
bridge().unregisterGlobalHotkey();
});
this.electronApp_.on('window-all-closed', () => {
+4
View File
@@ -150,6 +150,10 @@ class Application extends BaseApplication {
bridge().extraAllowedOpenExtensions = Setting.value('linking.extraAllowedExtensions');
}
if ((action.type === 'SETTING_UPDATE_ONE' && action.key === 'globalHotkey') || action.type === 'SETTING_UPDATE_ALL') {
bridge().updateGlobalHotkey(Setting.value('globalHotkey'));
}
if (['EVENT_NOTE_ALARM_FIELD_CHANGE', 'NOTE_DELETE'].indexOf(action.type) >= 0) {
await AlarmService.updateNoteNotification(action.id, action.type === 'NOTE_DELETE');
}
+54 -1
View File
@@ -1,7 +1,7 @@
import ElectronAppWrapper from './ElectronAppWrapper';
import shim, { MessageBoxType } from '@joplin/lib/shim';
import { _, setLocale } from '@joplin/lib/locale';
import { BrowserWindow, nativeTheme, nativeImage, shell, dialog, MessageBoxSyncOptions, safeStorage, Menu, MenuItemConstructorOptions, MenuItem, BrowserWindowConstructorOptions, FileFilter, SaveDialogOptions } from 'electron';
import { BrowserWindow, nativeTheme, nativeImage, shell, dialog, MessageBoxSyncOptions, safeStorage, Menu, MenuItemConstructorOptions, MenuItem, BrowserWindowConstructorOptions, FileFilter, SaveDialogOptions, globalShortcut } from 'electron';
import { dirname, toSystemSlashes } from '@joplin/lib/path-utils';
import { fileUriToPath } from '@joplin/utils/url';
import { urlDecode } from '@joplin/lib/string-utils';
@@ -46,6 +46,7 @@ export class Bridge {
private extraAllowedExtensions_: string[] = [];
private onAllowedExtensionsChangeListener_: OnAllowedExtensionsChange = ()=>{};
private registeredGlobalHotkey_ = '';
public constructor(electronWrapper: ElectronAppWrapper, appId: string, appName: string, rootProfileDir: string, autoUploadCrashDumps: boolean, altInstanceId: string) {
this.electronWrapper_ = electronWrapper;
@@ -207,6 +208,54 @@ export class Bridge {
this.onAllowedExtensionsChangeListener_ = listener;
}
public updateGlobalHotkey(accelerator: string) {
// Skip if the accelerator hasn't changed
if (accelerator === this.registeredGlobalHotkey_) return;
// Unregister the previous shortcut (only Joplin's own)
this.unregisterGlobalHotkey();
if (!accelerator) return;
try {
const registered = globalShortcut.register(accelerator, () => {
const win = this.mainWindow();
if (!win) return;
if (win.isVisible() && win.isFocused()) {
win.hide();
} else {
if (win.isMinimized()) win.restore();
win.show();
// eslint-disable-next-line no-restricted-properties
win.focus();
}
});
if (registered) {
this.registeredGlobalHotkey_ = accelerator;
} else {
// eslint-disable-next-line no-console
console.warn(`Bridge: Failed to register global shortcut: ${accelerator}`);
}
} catch (error) {
// eslint-disable-next-line no-console
console.error(`Bridge: Error registering global shortcut "${accelerator}":`, error);
}
}
public unregisterGlobalHotkey() {
if (this.registeredGlobalHotkey_) {
try {
globalShortcut.unregister(this.registeredGlobalHotkey_);
} catch (error) {
// eslint-disable-next-line no-console
console.warn('Bridge: Error removing global shortcut:', error);
}
this.registeredGlobalHotkey_ = '';
}
}
public async captureException(error: unknown) {
Sentry.captureException(error);
// We wait to give the "beforeSend" event handler time to process the crash dump and write
@@ -434,6 +483,10 @@ export class Bridge {
setLocale(locale);
}
public setEnableUnresponsiveCheck(enabled: boolean) {
this.electronWrapper_.setEnableUnresponsiveCheck(enabled);
}
public get Menu() {
return Menu;
}
@@ -0,0 +1,24 @@
import * as React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import GlobalHotkeyInput from './GlobalHotkeyInput';
describe('GlobalHotkeyInput', () => {
test('should render ShortcutRecorder with Save and Restore buttons', () => {
const onChange = jest.fn();
render(<GlobalHotkeyInput value="CommandOrControl+Shift+J" themeId={1} onChange={onChange} />);
// ShortcutRecorder is always visible with its built-in buttons
expect(screen.getByText('Save')).toBeTruthy();
expect(screen.getByText('Restore')).toBeTruthy();
expect(screen.getByText('Cancel')).toBeTruthy();
});
test('should clear value when Restore is clicked', () => {
const onChange = jest.fn();
render(<GlobalHotkeyInput value="CommandOrControl+Shift+J" themeId={1} onChange={onChange} />);
fireEvent.click(screen.getByText('Restore'));
expect(onChange).toHaveBeenCalledWith({ value: '' });
});
});
@@ -0,0 +1,53 @@
import * as React from 'react';
import { useCallback } from 'react';
import { ShortcutRecorder } from '../../KeymapConfig/ShortcutRecorder';
interface OnChangeEvent {
value: string;
}
interface Props {
value: string;
themeId: number;
onChange: (event: OnChangeEvent)=> void;
}
// A thin wrapper around ShortcutRecorder for the global hotkey setting.
// Reuses ShortcutRecorder directly instead of maintaining a separate display mode.
export default function GlobalHotkeyInput(props: Props) {
const value = props.value || '';
const onSave = useCallback((event: { commandName: string; accelerator: string }) => {
// Normalize platform-specific modifiers to CommandOrControl for
// consistent cross-platform storage.
const accelerator = event.accelerator
.replace(/\bCmd\b/, 'CommandOrControl')
.replace(/\bCtrl\b/, 'CommandOrControl');
props.onChange({ value: accelerator });
}, [props.onChange]);
const onReset = useCallback(() => {
props.onChange({ value: '' });
}, [props.onChange]);
// No-op: global hotkeys don't have a separate editing mode to cancel out of.
const onCancel = useCallback(() => {}, []);
// No-op: ShortcutRecorder validates against the keymap (command
// conflicts), which doesn't apply to global hotkeys.
const onError = useCallback((_event: { recorderError: Error }) => {}, []);
return (
<ShortcutRecorder
onSave={onSave}
onReset={onReset}
onCancel={onCancel}
onError={onError}
initialAccelerator={value}
commandName="globalHotkey"
themeId={props.themeId}
skipKeymapValidation
autoFocus={false}
/>
);
}
@@ -3,6 +3,7 @@ import { themeStyle } from '@joplin/lib/theme';
import * as React from 'react';
import { useCallback, useId } from 'react';
import control_PluginsStates from './plugins/PluginsStates';
import control_GlobalHotkeyInput from './GlobalHotkeyInput';
import bridge from '../../../services/bridge';
import { _ } from '@joplin/lib/locale';
import Button, { ButtonLevel, ButtonSize } from '../../Button/Button';
@@ -11,8 +12,10 @@ import * as pathUtils from '@joplin/lib/path-utils';
import SettingLabel from './SettingLabel';
import SettingDescription from './SettingDescription';
const settingKeyToControl: Record<string, typeof control_PluginsStates> = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Each control component has different prop types
const settingKeyToControl: Record<string, React.FC<any>> = {
'plugins.states': control_PluginsStates,
'globalHotkey': control_GlobalHotkeyInput,
};
export interface UpdateSettingValueEvent {
@@ -15,9 +15,14 @@ export interface ShortcutRecorderProps {
initialAccelerator: string;
commandName: string;
themeId: number;
// When true, skip keymap conflict validation (useful for global hotkeys
// that aren't part of the internal command keymap).
skipKeymapValidation?: boolean;
// Controls whether the input auto-focuses on mount. Defaults to true.
autoFocus?: boolean;
}
export const ShortcutRecorder = ({ onSave, onReset, onCancel, onError, initialAccelerator, commandName, themeId }: ShortcutRecorderProps) => {
export const ShortcutRecorder = ({ onSave, onReset, onCancel, onError, initialAccelerator, commandName, themeId, skipKeymapValidation, autoFocus = true }: ShortcutRecorderProps) => {
const styles = styles_(themeId);
const [accelerator, setAccelerator] = useState(initialAccelerator);
@@ -29,7 +34,9 @@ export const ShortcutRecorder = ({ onSave, onReset, onCancel, onError, initialAc
// Otherwise performing a save means that it's going to be disabled
if (accelerator) {
keymapService.validateAccelerator(accelerator);
keymapService.validateKeymap({ accelerator, command: commandName });
if (!skipKeymapValidation) {
keymapService.validateKeymap({ accelerator, command: commandName });
}
}
// Discard previous errors
@@ -86,7 +93,7 @@ export const ShortcutRecorder = ({ onSave, onReset, onCancel, onError, initialAc
onKeyDown={handleKeyDown}
readOnly
autoFocus
autoFocus={autoFocus}
/>
<button style={styles.inlineButton} disabled={!saveAllowed} onClick={() => onSave({ commandName, accelerator })}>
+5
View File
@@ -200,6 +200,11 @@ function menuItemSetEnabled(id: string, enabled: boolean) {
const menu = Menu.getApplicationMenu();
const menuItem = menu.getMenuItemById(id);
if (!menuItem) return;
// Don't disable menu items that have a role (e.g. copy, paste, cut,
// selectAll). Since Electron 40, disabling a role-based menu item also
// prevents the native role behaviour, which breaks clipboard operations
// in non-editor input fields such as the Settings screen.
if (!enabled && menuItem.role) return;
menuItem.enabled = enabled;
}
@@ -90,6 +90,19 @@ export function resourcesStatus(resourceInfos: any) {
return joplinRendererUtils.resourceStatusName(lowestIndex);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const clipboardImageToResource = async (image: any, mime: string) => {
const fileExt = mimeUtils.toFileExtension(mime);
const filePath = `${Setting.value('tempDir')}/${md5(Date.now())}.${fileExt}`;
await shim.writeImageToFile(image, mime, filePath);
try {
const md = await commandAttachFileToBody('', [filePath]);
return md;
} finally {
await shim.fsDriver().remove(filePath);
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
export async function getResourcesFromPasteEvent(event: any) {
const output = [];
@@ -104,19 +117,22 @@ export async function getResourcesFromPasteEvent(event: any) {
continue;
}
if (event) event.preventDefault();
const image = clipboard.readImage();
const fileExt = mimeUtils.toFileExtension(format);
const filePath = `${Setting.value('tempDir')}/${md5(Date.now())}.${fileExt}`;
await shim.writeImageToFile(image, format, filePath);
const md = await commandAttachFileToBody('', [filePath]);
await shim.fsDriver().remove(filePath);
const md = await clipboardImageToResource(clipboard.readImage(), format);
if (md) output.push(md);
}
}
// Some applications (e.g. macshot) copy images to the clipboard without
// an image/* format, but clipboard.readImage() can still read them.
if (!output.length) {
const image = clipboard.readImage();
if (!image.isEmpty()) {
if (event) event.preventDefault();
const md = await clipboardImageToResource(image, 'image/png');
if (md) output.push(md);
}
}
return output;
}
@@ -31,7 +31,6 @@ import { stateUtils } from '@joplin/lib/reducer';
import { connect } from 'react-redux';
import useOnNoteDoubleClick from './utils/useOnNoteDoubleClick';
import useAutoScroll from './utils/useAutoScroll';
import useRefocusOnDeletion from './utils/useRefocusOnDeletion';
const commands = {
focusElementNoteList,
@@ -75,7 +74,6 @@ const NoteList = (props: Props) => {
const { activeNoteId, setActiveNoteId } = useActiveDescendantId(props.selectedFolderId, props.selectedNoteIds);
const focusNote = useFocusNote(listRef, props.notes, makeItemIndexVisible, setActiveNoteId);
useRefocusOnDeletion(props.notes.length, props.selectedNoteIds, props.focusedField, props.selectedFolderId, focusNote);
const moveNote = useMoveNote(
props.notesParentType,
@@ -1,41 +0,0 @@
import { renderHook } from '@testing-library/react';
import useRefocusOnDeletion from './useRefocusOnDeletion';
describe('useRefocusOnDeletion', () => {
it('should refocus when a note is deleted in the same folder', () => {
const focusNote = jest.fn();
const { rerender } = renderHook(
({ noteCount }: { noteCount: number }) =>
useRefocusOnDeletion(noteCount, ['note-1'], '', 'folder-1', focusNote),
{ initialProps: { noteCount: 3 } },
);
rerender({ noteCount: 2 });
expect(focusNote).toHaveBeenCalledWith('note-1');
});
test.each([
['note count increases', 2, 3, '', ['note-1']],
['another field has focus', 3, 2, 'editor', ['note-1']],
['multiple notes are selected', 3, 2, '', ['note-1', 'note-2']],
])('should not refocus when %s', (_label, initialCount, newCount, focusedField, noteIds) => {
const focusNote = jest.fn();
const { rerender } = renderHook(
({ noteCount }: { noteCount: number }) =>
useRefocusOnDeletion(noteCount, noteIds, focusedField, 'folder-1', focusNote),
{ initialProps: { noteCount: initialCount } },
);
rerender({ noteCount: newCount });
expect(focusNote).not.toHaveBeenCalled();
});
it('should not refocus when switching to a folder with fewer notes', () => {
const focusNote = jest.fn();
const { rerender } = renderHook(
({ noteCount, folderId }: { noteCount: number; folderId: string }) =>
useRefocusOnDeletion(noteCount, ['note-1'], '', folderId, focusNote),
{ initialProps: { noteCount: 3, folderId: 'folder-1' } },
);
rerender({ noteCount: 2, folderId: 'folder-2' });
expect(focusNote).not.toHaveBeenCalled();
});
});
@@ -1,20 +0,0 @@
import { useEffect } from 'react';
import usePrevious from '@joplin/lib/hooks/usePrevious';
const useRefocusOnDeletion = (
noteCount: number,
selectedNoteIds: string[],
focusedField: string,
selectedFolderId: string,
focusNote: (noteId: string)=> void,
) => {
const previousNoteCount = usePrevious(noteCount, 0);
const previousFolderId = usePrevious(selectedFolderId, '');
useEffect(() => {
const noteWasRemoved = noteCount < previousNoteCount;
const folderDidNotChange = selectedFolderId === previousFolderId;
if (noteWasRemoved && folderDidNotChange && selectedNoteIds.length === 1 && !focusedField) {
focusNote(selectedNoteIds[0]);
}
}, [noteCount, previousNoteCount, selectedNoteIds, focusedField, selectedFolderId, previousFolderId, focusNote]);
};
export default useRefocusOnDeletion;
+40 -43
View File
@@ -1,9 +1,9 @@
import * as React from 'react';
import { useCallback } from 'react';
import { StyledSyncReportText, StyledSyncReport, StyledSynchronizeButton, StyledRoot } from './styles';
import { ButtonLevel } from '../Button/Button';
import CommandService from '@joplin/lib/services/CommandService';
import Synchronizer from '@joplin/lib/Synchronizer';
import Setting from '@joplin/lib/models/Setting';
import { _ } from '@joplin/lib/locale';
import { AppState } from '../../app.reducer';
import { StateDecryptionWorker, StateResourceFetcher } from '@joplin/lib/reducer';
@@ -11,8 +11,6 @@ import { connect } from 'react-redux';
import { themeStyle } from '@joplin/lib/theme';
import { Dispatch } from 'redux';
import FolderAndTagList from './FolderAndTagList';
import Setting from '@joplin/lib/models/Setting';
import time from '@joplin/lib/time';
interface Props {
@@ -23,18 +21,26 @@ interface Props {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
syncReport: any;
syncStarted: boolean;
syncReportLogExpanded: boolean;
syncPending: boolean;
syncReportIsVisible: boolean;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- The generated report does not currently have a type
const syncCompletedWithoutError = (syncReport: any) => {
return syncReport.completedTime && (!syncReport.errors || !syncReport.errors.length);
};
const SidebarComponent = (props: Props) => {
const renderSynchronizeButton = (type: string) => {
const label = type === 'sync' ? _('Synchronise') : _('Cancel');
const nothingToSync = type === 'sync' && !props.syncPending && syncCompletedWithoutError(props.syncReport);
const iconName = nothingToSync ? 'fas fa-check' : 'icon-sync';
return (
<StyledSynchronizeButton
level={ButtonLevel.SidebarSecondary}
className={`sidebar-sync-button ${type === 'sync' ? '' : '-syncing'}`}
iconName="icon-sync"
className={`sidebar-sync-button ${type === 'sync' ? '' : '-syncing'} ${nothingToSync ? '-synced' : ''}`}
iconName={iconName}
key="sync_button"
title={label}
onClick={() => {
@@ -56,56 +62,46 @@ const SidebarComponent = (props: Props) => {
resourceFetcherText = _('Fetching resources: %d/%d', props.resourceFetcher.fetchingCount, props.resourceFetcher.toFetchCount);
}
const syncReportExpanded = props.syncReportLogExpanded;
const toggleSyncReport = useCallback(() => {
Setting.setValue('syncReportLogExpanded', !syncReportExpanded);
}, [syncReportExpanded]);
const lines = Synchronizer.reportToLines(props.syncReport);
if (resourceFetcherText) lines.push(resourceFetcherText);
if (decryptionReportText) lines.push(decryptionReportText);
const completedTime = props.syncReport && props.syncReport.completedTime
? time.formatMsToLocal(props.syncReport.completedTime)
: null;
const syncReportText = [];
for (let i = 0; i < lines.length; i++) {
syncReportText.push(
<StyledSyncReportText key={i}>
{lines[i]}
</StyledSyncReportText>,
);
}
const syncButton = renderSynchronizeButton(props.syncStarted ? 'cancel' : 'sync');
// Toggle to show/hide sync log output
const toggleButton = (
const hasSyncReport = syncReportText.length > 0;
const syncReportComp = !hasSyncReport || !props.syncReportIsVisible ? null : (
<StyledSyncReport key="sync_report" id="sync-report">
{syncReportText}
</StyledSyncReport>
);
const syncReportToggle = (
<button
className="sidebar-sync-toggle"
onClick={toggleSyncReport}
aria-expanded={syncReportExpanded}
aria-label={syncReportExpanded ? _('Hide sync log') : _('Show sync log')}
title={syncReportExpanded ? _('Hide sync log') : _('Show sync log')}
className="sync-report-toggle"
style={{ color: theme.color2 }}
onClick={() => Setting.toggle('syncReportIsVisible')}
aria-label={_('Sync report')}
aria-expanded={props.syncReportIsVisible}
aria-controls="sync-report"
>
<i className={`fas fa-caret-${syncReportExpanded ? 'down' : 'right'}`} />
{(completedTime || props.syncStarted) ? (
<span className="timestamp">
{props.syncStarted ? _('Last sync: In progress...') : _('Last sync: %s', completedTime)}
</span>
) : ''}
<i className={`fas fa-chevron-${props.syncReportIsVisible ? 'down' : 'up'}`}/>
</button>
);
// Sync log output, only visible when expanded
const syncReportComp = (syncReportExpanded && lines.length > 0) ? (
<StyledSyncReport key="sync_report">
{lines.map((line, i) => (
<StyledSyncReportText key={i}>
{line}
</StyledSyncReportText>
))}
</StyledSyncReport>
) : null;
return (
<StyledRoot className='sidebar _scrollbar2' role='navigation' aria-label={_('Sidebar')}>
<div style={{ flex: 1 }}><FolderAndTagList /></div>
<div style={{ flex: 1 }}><FolderAndTagList/></div>
<div style={{ flex: 0, padding: theme.mainPadding }}>
{(completedTime || props.syncStarted) ? toggleButton : null}
{syncReportToggle}
{syncReportComp}
{syncButton}
</div>
@@ -117,6 +113,7 @@ const mapStateToProps = (state: AppState) => {
return {
searches: state.searches,
syncStarted: state.syncStarted,
syncPending: state.syncPending,
syncReport: state.syncReport,
selectedSearchId: state.selectedSearchId,
selectedSmartFilterId: state.selectedSmartFilterId,
@@ -125,7 +122,7 @@ const mapStateToProps = (state: AppState) => {
collapsedFolderIds: state.collapsedFolderIds,
decryptionWorker: state.decryptionWorker,
resourceFetcher: state.resourceFetcher,
syncReportLogExpanded: state.settings.syncReportLogExpanded,
syncReportIsVisible: state.settings.syncReportIsVisible,
};
};
+1 -2
View File
@@ -6,5 +6,4 @@
@use 'styles/sidebar-header-container.scss';
@use 'styles/sidebar-spacer-item.scss';
@use 'styles/sidebar-header-button.scss';
@use 'styles/sidebar-sync-button.scss';
@use 'styles/sidebar-sync-toggle.scss';
@use 'styles/sidebar-sync-button.scss';
@@ -105,7 +105,7 @@ export const StyledSyncReport = styled.div`
opacity: 0.5;
display: flex;
flex-direction: column;
margin-left: 25px;
margin-left: 5px;
margin-right: 5px;
margin-bottom: 10px;
word-wrap: break-word;
@@ -5,6 +5,25 @@
}
}
@keyframes icon-fade-in-a {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes icon-fade-in-b {
from { opacity: 0; }
to { opacity: 1; }
}
.sidebar-sync-button > .icon {
display: inline-flex !important;
align-items: center;
justify-content: center;
width: 16px !important;
height: 16px;
margin-right: 8px !important;
}
.sidebar-sync-button {
&.-syncing > .icon {
animation: icon-infinite-rotation 1s linear infinite;
@@ -13,4 +32,29 @@
animation: none;
}
}
&:not(.-syncing).-synced > .icon {
animation: icon-fade-in-a 300ms ease-in-out;
font-size: 0.85em;
}
&:not(.-syncing):not(.-synced) > .icon {
animation: icon-fade-in-b 300ms ease-in-out;
}
}
.sync-report-toggle {
display: block;
width: 100%;
background: none;
border: none;
padding: 0;
text-align: center;
cursor: pointer;
opacity: 0.5;
margin-bottom: 4px;
&:hover {
opacity: 1;
}
}
@@ -1,31 +0,0 @@
.sidebar-sync-toggle {
display: flex;
align-items: center;
justify-content: flex-start;
padding: 4px 5px 4px 5px;
background: none;
border: none;
color: var(--joplin-color2);
opacity: 0.5;
cursor: pointer;
width: 100%;
font-size: calc(var(--joplin-font-size) * 1.6);
transition: opacity 0.2s;
&:hover {
opacity: 1;
}
i {
width: 16px;
display: inline-flex;
justify-content: center;
font-size: calc(var(--joplin-toolbar-icon-size) * 0.8);
}
>.timestamp {
font-size: 0.6em;
margin-left: 4px;
}
}
@@ -7,26 +7,40 @@ import activateMainMenuItem from './util/activateMainMenuItem';
import setSettingValue from './util/setSettingValue';
import { toForwardSlashes } from '@joplin/utils/path';
import mockClipboard from './util/mockClipboard';
import { ElectronApplication, Page } from '@playwright/test';
const importAndOpenHtmlExport = async (mainWindow: Page, electronApp: ElectronApplication, noteTitle: string) => {
const mainScreen = await new MainScreen(mainWindow).setup();
await mainScreen.waitFor();
await mainScreen.importHtmlDirectory(electronApp, join(__dirname, 'resources', 'html-import'));
const importedFolder = mainScreen.sidebar.container.getByText('html-import');
await importedFolder.waitFor();
// Retry -- focusing the imported-folder may fail in some cases
await expect(async () => {
await importedFolder.click();
await mainScreen.noteList.focusContent(electronApp);
const importedHtmlFileItem = mainScreen.noteList.getNoteItemByTitle(noteTitle);
await importedHtmlFileItem.click({ timeout: 300 });
}).toPass();
return { mainScreen };
};
test.describe('markdownEditor', () => {
test('editor should render the full content of HTML notes', async ({ mainWindow, electronApp }) => {
const { mainScreen } = await importAndOpenHtmlExport(mainWindow, electronApp, 'test-html-file-with-spans');
const editor = mainScreen.noteEditor.codeMirrorEditor;
// Regression test: The <span> should not be hidden by inline Markdown rendering (since this is an HTML note):
await expect(editor).toHaveText('<p><span style="margin-left: 100px;">test</span></p>');
});
test('preview pane should render images in HTML notes', async ({ mainWindow, electronApp }) => {
const mainScreen = await new MainScreen(mainWindow).setup();
await mainScreen.waitFor();
await mainScreen.importHtmlDirectory(electronApp, join(__dirname, 'resources', 'html-import'));
const importedFolder = mainScreen.sidebar.container.getByText('html-import');
await importedFolder.waitFor();
// Retry -- focusing the imported-folder may fail in some cases
await expect(async () => {
await importedFolder.click();
await mainScreen.noteList.focusContent(electronApp);
const importedHtmlFileItem = mainScreen.noteList.getNoteItemByTitle('test-html-file-with-image');
await importedHtmlFileItem.click({ timeout: 300 });
}).toPass();
const { mainScreen } = await importAndOpenHtmlExport(mainWindow, electronApp, 'test-html-file-with-image');
const viewerFrame = mainScreen.noteEditor.getNoteViewerFrameLocator();
// Should render headers
@@ -101,6 +101,35 @@ test.describe('noteList', () => {
await expect(testNoteItem).toBeVisible();
});
test('should remain focused after deleting a note to the trash', async ({ electronApp, mainWindow }) => {
const mainScreen = await new MainScreen(mainWindow).setup();
await mainScreen.createNewNote('test note 1');
await mainScreen.createNewNote('test note 2');
await mainScreen.createNewNote('test note 3');
const noteList = mainScreen.noteList;
await noteList.sortByTitle(electronApp);
await noteList.focusContent(electronApp);
// The most-recently created note should be selected
await noteList.expectNoteToBeSelected('test note 3');
// All three notes should be visible
const getNote = (i: number) => noteList.getNoteItemByTitle(`test note ${i}`);
await expect(getNote(1)).toBeVisible();
await expect(getNote(2)).toBeVisible();
await expect(getNote(3)).toBeVisible();
await getNote(3).press('Delete');
await expect(getNote(3)).not.toBeVisible();
// Pressing the up arrow should change the selection
// (Regression test for https://github.com/laurent22/joplin/issues/10753)
await noteList.expectNoteToBeSelected('test note 2');
await noteList.container.press('ArrowUp');
await noteList.expectNoteToBeSelected('test note 1');
});
test('arrow keys should navigate the note list', async ({ electronApp, mainWindow }) => {
const mainScreen = await new MainScreen(mainWindow).setup();
const sidebar = mainScreen.sidebar;
@@ -0,0 +1 @@
<p><span style="margin-left: 100px;">test</span></p>
@@ -1,5 +1,6 @@
import { test, expect } from './util/test';
import MainScreen from './models/MainScreen';
import { Second } from '@joplin/utils/time';
test.describe('sidebar', () => {
test('should be able to create new folders', async ({ mainWindow }) => {
@@ -44,6 +45,54 @@ test.describe('sidebar', () => {
await expect(mainWindow.locator(':focus')).toHaveText('All notes');
});
// Regression test for https://github.com/laurent22/joplin/issues/15029
test('should remain focused when navigating with the arrow keys', async ({ electronApp, mainWindow }) => {
const mainScreen = await new MainScreen(mainWindow).setup();
const sidebar = mainScreen.sidebar;
// Build the folder hierarchy: Navigating upwards through the list
// should transition from a notebook with more notes to a notebook with
// fewer notes.
const folderAHeader = await sidebar.createNewFolder('Folder A');
await mainScreen.createNewNote('Test');
await expect(folderAHeader).toBeVisible();
const folderBHeader = await sidebar.createNewFolder('Folder B');
await mainScreen.createNewNote('Test 2');
await mainScreen.createNewNote('Test 3');
const folderCHeader = await sidebar.createNewFolder('Folder C');
const folderDHeader = await sidebar.createNewFolder('Folder D');
await folderBHeader.dragTo(folderAHeader);
await folderCHeader.dragTo(folderAHeader);
// Should have the correct initial state
await sidebar.forceUpdateSorting(electronApp);
await sidebar.expectToHaveDepths([
[folderAHeader, 2],
[folderBHeader, 3],
[folderCHeader, 3],
[folderDHeader, 2],
]);
const assertFocused = async (title: RegExp) => {
await expect(mainWindow.locator(':focus')).toHaveText(title);
// Pause to help check that focus is stable. This is present to help this test more reliably detect
// timing-related issues.
await mainWindow.waitForTimeout(Second);
await expect(mainWindow.locator(':focus')).toHaveText(title);
};
await folderDHeader.click();
// Focus should remain on the correct folder header while navigating
await mainWindow.keyboard.press('ArrowUp');
await assertFocused(/^Folder C/);
await mainWindow.keyboard.press('ArrowUp');
await assertFocused(/^Folder B/);
await mainWindow.keyboard.press('ArrowUp');
await assertFocused(/^Folder A/);
});
test('should allow changing the focused folder by pressing the first character of the title', async ({ electronApp, mainWindow }) => {
const mainScreen = await new MainScreen(mainWindow).setup();
const sidebar = mainScreen.sidebar;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@joplin/app-desktop",
"version": "3.6.8",
"version": "3.6.9",
"description": "Joplin for Desktop",
"main": "main.bundle.js",
"private": true,
+2 -2
View File
@@ -83,8 +83,8 @@ android {
applicationId "net.cozic.joplin"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 2097803
versionName "3.6.15"
versionCode 2097804
versionName "3.6.16"
buildConfigField "String", "REACT_NATIVE_RELEASE_LEVEL", "\"${findProperty('reactNativeReleaseLevel') ?: 'stable'}\""
@@ -38,6 +38,9 @@ const useStyle = (themeId: number) => {
right: 0,
bottom: 0,
},
profileList: {
flex: 1,
},
profileListItem: {
paddingLeft: theme.margin,
paddingRight: theme.margin,
@@ -206,15 +209,15 @@ export default (props: Props) => {
return (
<View style={style.root}>
<ScreenHeader title={_('Profiles')} showSaveButton={false} showSideMenuButton={false} showSearchButton={false} />
<View>
<FlatList
data={profiles}
renderItem={renderProfileItem}
keyExtractor={profile => profile.id}
// Needed so that the list rerenders when its dependencies change:
extraData={extraListItemData}
/>
</View>
<FlatList
style={style.profileList}
data={profiles}
renderItem={renderProfileItem}
keyExtractor={profile => profile.id}
// Needed so that the list rerenders when its dependencies change:
extraData={extraListItemData}
contentContainerStyle={{ paddingBottom: 80 }}
/>
<FAB
icon="plus"
accessibilityLabel={_('New profile')}
@@ -404,6 +404,29 @@ describe('screens/Note', () => {
unmount();
});
it('should set title, body, and parent_id correctly when a note is created via share', async () => {
const folder = await Folder.save({ title: 'Share target folder', parent_id: '' });
const note = await Note.save({ parent_id: folder.id }, { provisional: true });
store.dispatch({
type: 'NAV_GO',
routeName: 'Note',
noteId: note.id,
sharedData: { title: 'Shared title', text: 'https://example.com' },
});
store.dispatch({ type: 'NOTE_UPDATE_ONE', note: { ...note }, provisional: true });
const { unmount } = render(<WrappedNoteScreen />);
await waitForNoteToMatch(note.id, {
title: 'Shared title',
body: 'https://example.com',
parent_id: folder.id,
});
unmount();
});
it('should always start in edit mode for provisional notes regardless of noteVisiblePanes', async () => {
store.dispatch({
type: 'NOTE_VISIBLE_PANES_SET',
@@ -1678,9 +1678,7 @@ class NoteScreenComponent extends BaseScreenComponent<ComponentProps, State> imp
!note || !note.body.trim() ? null : (
<NoteBodyViewer
style={this.styles().noteBodyViewer}
// Extra bottom padding to make it possible to scroll past the
// action button (so that it doesn't overlap the text)
paddingBottom={150}
paddingBottom={0}
noteBody={note.body}
noteMarkupLanguage={note.markup_language}
noteResources={this.state.noteResources}
@@ -408,7 +408,7 @@
);
inputPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Joplin/Pods-Joplin-frameworks.sh",
"${PODS_XCFRAMEWORKS_BUILD_DIR}/OpenSSL-Universal/OpenSSL.framework/OpenSSL",
"${PODS_XCFRAMEWORKS_BUILD_DIR}/QuickCrypto/OpenSSL.framework/OpenSSL",
"${PODS_XCFRAMEWORKS_BUILD_DIR}/React-Core-prebuilt/React.framework/React",
"${PODS_XCFRAMEWORKS_BUILD_DIR}/ReactNativeDependencies/ReactNativeDependencies.framework/ReactNativeDependencies",
"${PODS_XCFRAMEWORKS_BUILD_DIR}/hermes-engine/Pre-built/hermes.framework/hermes",
+32 -35
View File
@@ -113,7 +113,30 @@ PODS:
- ReactCommon/turbomodule/core
- ReactNativeDependencies
- Yoga
- OpenSSL-Universal (3.3.3001)
- QuickCrypto (1.0.19):
- hermes-engine
- NitroModules
- RCTRequired
- RCTTypeSafety
- React-callinvoker
- React-Core
- React-Core-prebuilt
- React-debug
- React-Fabric
- React-featureflags
- React-graphics
- React-ImageManager
- React-jsi
- React-NativeModulesApple
- React-RCTFabric
- React-renderercss
- React-rendererdebug
- React-utils
- ReactCodegen
- ReactCommon/turbomodule/bridging
- ReactCommon/turbomodule/core
- ReactNativeDependencies
- Yoga
- RCTDeprecation (0.81.6)
- RCTRequired (0.81.6)
- RCTTypeSafety (0.81.6):
@@ -1467,30 +1490,6 @@ PODS:
- React-Core
- react-native-quick-base64 (2.2.2):
- React-Core
- react-native-quick-crypto (0.7.17):
- hermes-engine
- OpenSSL-Universal
- RCTRequired
- RCTTypeSafety
- React
- React-Core
- React-Core-prebuilt
- React-debug
- React-Fabric
- React-featureflags
- React-graphics
- React-ImageManager
- React-jsi
- React-NativeModulesApple
- React-RCTFabric
- React-renderercss
- React-rendererdebug
- React-utils
- ReactCodegen
- ReactCommon/turbomodule/bridging
- ReactCommon/turbomodule/core
- ReactNativeDependencies
- Yoga
- react-native-rsa-native (2.0.5):
- React
- react-native-saf-x (3.6.0):
@@ -2066,7 +2065,7 @@ PODS:
- React
- RNSecureRandom (1.0.1):
- React
- RNShare (12.2.1):
- RNShare (12.2.2):
- hermes-engine
- RCTRequired
- RCTTypeSafety
@@ -2133,7 +2132,7 @@ PODS:
- ReactCommon/turbomodule/core
- ReactNativeDependencies
- Yoga
- SDWebImage/Core (5.21.7)
- SDWebImage/Core (5.21.5)
- SDWebImageWebPCoder (0.15.0):
- libwebp (~> 1.0)
- SDWebImage/Core (~> 5.17)
@@ -2184,6 +2183,7 @@ DEPENDENCIES:
- JoplinCommonShareExtension (from `ShareExtension`)
- JoplinRNShareExtension (from `ShareExtension`)
- NitroModules (from `../node_modules/react-native-nitro-modules`)
- QuickCrypto (from `../node_modules/react-native-quick-crypto`)
- RCTDeprecation (from `../node_modules/react-native/ReactApple/Libraries/RCTFoundation/RCTDeprecation`)
- RCTRequired (from `../node_modules/react-native/Libraries/Required`)
- RCTTypeSafety (from `../node_modules/react-native/Libraries/TypeSafety`)
@@ -2225,7 +2225,6 @@ DEPENDENCIES:
- react-native-image-picker (from `../node_modules/react-native-image-picker`)
- "react-native-netinfo (from `../node_modules/@react-native-community/netinfo`)"
- react-native-quick-base64 (from `../node_modules/react-native-quick-base64`)
- react-native-quick-crypto (from `../node_modules/react-native-quick-crypto`)
- react-native-rsa-native (from `../node_modules/react-native-rsa-native`)
- "react-native-saf-x (from `../node_modules/@joplin/react-native-saf-x`)"
- react-native-safe-area-context (from `../node_modules/react-native-safe-area-context`)
@@ -2286,7 +2285,6 @@ DEPENDENCIES:
SPEC REPOS:
trunk:
- libwebp
- OpenSSL-Universal
- SDWebImage
- SDWebImageWebPCoder
- ZXingObjC
@@ -2325,6 +2323,8 @@ EXTERNAL SOURCES:
:path: ShareExtension
NitroModules:
:path: "../node_modules/react-native-nitro-modules"
QuickCrypto:
:path: "../node_modules/react-native-quick-crypto"
RCTDeprecation:
:path: "../node_modules/react-native/ReactApple/Libraries/RCTFoundation/RCTDeprecation"
RCTRequired:
@@ -2405,8 +2405,6 @@ EXTERNAL SOURCES:
:path: "../node_modules/@react-native-community/netinfo"
react-native-quick-base64:
:path: "../node_modules/react-native-quick-base64"
react-native-quick-crypto:
:path: "../node_modules/react-native-quick-crypto"
react-native-rsa-native:
:path: "../node_modules/react-native-rsa-native"
react-native-saf-x:
@@ -2538,7 +2536,7 @@ SPEC CHECKSUMS:
JoplinRNShareExtension: e158a4b53ee0aa9cd3037a16221dc8adbd6f7860
libwebp: 02b23773aedb6ff1fd38cec7a77b81414c6842a8
NitroModules: 114b4f79e10be9b202723e721d6a54382fa4b599
OpenSSL-Universal: 6082b0bf950e5636fe0d78def171184e2b3899c2
QuickCrypto: 0708a392535332365b7f4a16a0b229482be9a1e0
RCTDeprecation: ff38238d8b6ddfe1fcfeb2718d1c14da9564c1c3
RCTRequired: 5916f53ff05efcc2bf095b0de01a0e5b00112a55
RCTTypeSafety: bfbd8d69504a7459a65040705fc6ce10806c383b
@@ -2579,7 +2577,6 @@ SPEC CHECKSUMS:
react-native-image-picker: 48d850454b4a389753053e1d7378b624d3b47d77
react-native-netinfo: cec9c4e86083cb5b6aba0e0711f563e2fbbff187
react-native-quick-base64: 6568199bb2ac8e72ecdfdc73a230fbc5c1d3aac4
react-native-quick-crypto: 1a2467cf17acc57dce5bb076a953978b79e3fd11
react-native-rsa-native: a7931cdda1f73a8576a46d7f431378c5550f0c38
react-native-saf-x: 50d176763ed692b379c190bf55ae7293a3ee09bb
react-native-safe-area-context: 37e680fc4cace3c0030ee46e8987d24f5d3bdab2
@@ -2632,9 +2629,9 @@ SPEC CHECKSUMS:
RNLocalize: 44b09911588826d01c5b949e8e3f9ed5fae16b32
RNQuickAction: c2c8f379e614428be0babe4d53a575739667744d
RNSecureRandom: b64d263529492a6897e236a22a2c4249aa1b53dc
RNShare: 0e600372fb35783fe30d413efd28d11de2bf6cf0
RNShare: a075abc351f03fd89517bbee912593f299eb8a64
RNSVG: cf9ae78f2edf2988242c71a6392d15ff7dd62522
SDWebImage: e9fc87c1aab89a8ab1bbd74eba378c6f53be8abf
SDWebImage: e9c98383c7572d713c1a0d7dd2783b10599b9838
SDWebImageWebPCoder: 0e06e365080397465cc73a7a9b472d8a3bd0f377
WhisperVoiceTyping: 343ea840cbde2a5f3508f8b016ebcf1c089179ea
Yoga: 786fa7d9d2ff6060b4e688062243fa69c323d140
+3 -2
View File
@@ -7,6 +7,7 @@
"scripts": {
"start": "BROWSERSLIST_IGNORE_OLD_DATA=true react-native start --reset-cache",
"android": "react-native run-android",
"android-log": "adb logcat 'ReactNative:V' 'ReactNativeJS:V' 'chromium:V' '*:S'",
"build": "NO_FLIPPER=1 gulp build",
"web": "webpack --mode production --config ./web/webpack.config.ts --progress && cp -r ./web/public/* ./web/dist/",
"serve-web-hot-reload": "yarn serve-web --env HOT_RELOAD",
@@ -34,7 +35,7 @@
"@react-native-community/datetimepicker": "8.5.1",
"@react-native-community/geolocation": "3.4.0",
"@react-native-community/netinfo": "11.4.1",
"@react-native-community/push-notification-ios": "1.11.0",
"@react-native-community/push-notification-ios": "1.12.0",
"@react-native-documents/picker": "10.1.7",
"@react-native-vector-icons/fontawesome5": "patch:@react-native-vector-icons/fontawesome5@npm%3A12.3.0#~/.yarn/patches/@react-native-vector-icons-fontawesome5-npm-12.3.0-a1ca46610f.patch",
"@react-native-vector-icons/get-image": "12.3.0",
@@ -73,7 +74,7 @@
"react-native-popup-menu": "0.17.0",
"react-native-quick-actions": "0.3.13",
"react-native-quick-base64": "2.2.2",
"react-native-quick-crypto": "0.7.17",
"react-native-quick-crypto": "1.0.19",
"react-native-rsa-native": "2.0.5",
"react-native-safe-area-context": "5.6.2",
"react-native-securerandom": "1.0.1",
+31 -11
View File
@@ -23,6 +23,15 @@ import { AppState as RNAppState, EmitterSubscription, View, Text, Linking, Nativ
import getResponsiveValue from './components/getResponsiveValue';
import NetInfo, { NetInfoSubscription } from '@react-native-community/netinfo';
const DropdownAlert = require('react-native-dropdownalert').default;
// Mirrors the DropdownAlertData type from react-native-dropdownalert
interface DropdownAlertData {
type?: string;
title?: string;
message?: string;
interval?: number;
resolve?: (_value: DropdownAlertData)=> void;
}
import SafeAreaView from './components/SafeAreaView';
const { connect, Provider } = require('react-redux');
import { Provider as PaperProvider, MD3DarkTheme, MD3LightTheme } from 'react-native-paper';
@@ -103,7 +112,7 @@ import SamlShared from '@joplin/lib/components/shared/SamlShared';
import NoteRevisionViewer from './components/screens/NoteRevisionViewer';
import DocumentScanner from './components/screens/DocumentScanner/DocumentScanner';
import buildStartupTasks from './utils/buildStartupTasks';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { SafeAreaProvider, useSafeAreaInsets } from 'react-native-safe-area-context';
import appReducer from './utils/appReducer';
import SyncWizard from './components/SyncWizard/SyncWizard';
import Synchronizer from '@joplin/lib/Synchronizer';
@@ -111,6 +120,15 @@ import Synchronizer from '@joplin/lib/Synchronizer';
const logger = Logger.create('root');
const perfLogger = PerformanceLogger.create();
interface DropdownAlertWrapperProps {
alert: (func: (data?: DropdownAlertData)=> Promise<DropdownAlertData>)=> void;
}
const DropdownAlertWrapper = ({ alert }: DropdownAlertWrapperProps) => {
const insets = useSafeAreaInsets();
return <DropdownAlert alert={alert} translucent alertViewStyle={{ padding: 8, marginTop: insets.top }} />;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
let storeDispatch: any = function(_action: any) {};
@@ -287,8 +305,7 @@ class AppComponent extends React.Component<AppComponentProps, AppComponentState>
private themeChangeListener_: NativeEventSubscription|null = null;
private keyboardShowListener_: EmitterSubscription|null = null;
private keyboardHideListener_: EmitterSubscription|null = null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
private dropdownAlert_ = (_data: any) => new Promise<any>(res => res);
private dropdownAlert_: (data?: DropdownAlertData)=> Promise<DropdownAlertData> = (_data?: DropdownAlertData) => new Promise<DropdownAlertData>(res => res);
private callbackUrl: string|null = null;
private lastSyncStarted_ = false;
@@ -586,14 +603,18 @@ class AppComponent extends React.Component<AppComponentProps, AppComponentState>
if (sharedData) {
reg.logger().info('Received shared data');
// selectedFolderId can be null if no screens other than "All notes"
// have been opened.
const targetFolder = this.props.selectedFolderId ?? (await Folder.defaultFolder())?.id;
if (targetFolder) {
const activeFolder = await Folder.getValidActiveFolder();
if (activeFolder) {
logger.info('Sharing: handleShareData: Processing...');
await handleShared(sharedData, targetFolder, this.props.dispatch);
await handleShared(sharedData, activeFolder.id, this.props.dispatch);
} else {
reg.logger().info('Cannot handle share - default folder id is not set');
reg.logger().warn('Cannot handle share - no valid active folder found');
void this.dropdownAlert_({
type: 'error',
title: _('Cannot share'),
message: _('No valid notebook is available. Please create or select a notebook and try again.'),
});
ShareExtension.close();
}
} else {
logger.info('Sharing: received empty share data.');
@@ -771,10 +792,9 @@ class AppComponent extends React.Component<AppComponentProps, AppComponentState>
<View style={{ flex: 1, backgroundColor: theme.backgroundColor }}>
{ shouldShowMainContent && <AppNav screens={appNavInit} dispatch={this.props.dispatch} /> }
</View>
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied */}
<DropdownAlert alert={(func: any) => (this.dropdownAlert_ = func)} />
<SyncWizard/>
</SafeAreaView>
<DropdownAlertWrapper alert={(func) => { this.dropdownAlert_ = func; }} />
</View>
</SideMenu>
<PluginRunnerWebView />
+2 -2
View File
@@ -29,7 +29,7 @@ const pbkdf2Raw = (password: string, salt: CryptoBuffer, iterations: number, key
const encryptRaw = (data: CryptoBuffer, algorithm: CipherAlgorithm, key: CryptoBuffer, iv: CryptoBuffer, authTagLength: number, associatedData: CryptoBuffer) => {
const cipher = QuickCrypto.createCipheriv(algorithm, key, iv, { authTagLength: authTagLength } as CipherGCMOptions) as CipherGCM;
const cipher = QuickCrypto.createCipheriv(algorithm, key, iv, { authTagLength: authTagLength } as CipherGCMOptions) as unknown as CipherGCM;
cipher.setAAD(associatedData, { plaintextLength: Buffer.byteLength(data) });
@@ -41,7 +41,7 @@ const encryptRaw = (data: CryptoBuffer, algorithm: CipherAlgorithm, key: CryptoB
const decryptRaw = (data: CryptoBuffer, algorithm: CipherAlgorithm, key: CryptoBuffer, iv: CryptoBuffer, authTagLength: number, associatedData: CryptoBuffer) => {
const decipher = QuickCrypto.createDecipheriv(algorithm, key, iv, { authTagLength: authTagLength } as CipherGCMOptions) as DecipherGCM;
const decipher = QuickCrypto.createDecipheriv(algorithm, key, iv, { authTagLength: authTagLength } as CipherGCMOptions) as unknown as DecipherGCM;
const authTag = data.subarray(-authTagLength);
const encryptedData = data.subarray(0, data.byteLength - authTag.byteLength);
@@ -109,7 +109,9 @@ const configFromSettings = (settings: EditorSettings, context: RenderedContentCo
extensions.push(Prec.low(keymap.of(defaultKeymap)));
}
if (settings.inlineRenderingEnabled) {
// Only enable in-editor rendering for Markdown notes. In-editor rendering can result in
// confusing output in HTML notes (e.g. some, but not most, tags hidden).
if (settings.inlineRenderingEnabled && settings.language === EditorLanguageType.Markdown) {
extensions.push(renderingExtension());
}
@@ -174,6 +174,19 @@ const searchExtension = (onEvent: OnEventCallback, settings: EditorSettings): Ex
},
} : undefined),
// On mobile, scrolling is handled externally (page-level native scroll), so
// .cm-scroller has no internal scroll. A @codemirror/view upgrade (6.35→6.41)
// added rect-clipping after each failed scroll attempt, which prevents the
// fallback window.scrollBy from firing. Use native element.scrollIntoView to
// fix findNext/findPrevious and GoDocEnd.
settings.useExternalSearch ? EditorView.scrollHandler.of((view, range) => {
const { node } = view.domAtPos(range.head);
const el = node.nodeType === Node.ELEMENT_NODE ? node as Element : node.parentElement;
if (!el) return false;
el.scrollIntoView({ block: 'nearest', inline: 'nearest' });
return true;
}) : [],
autoScrollToMatchPlugin,
EditorState.transactionExtender.of((tr) => {
@@ -304,7 +304,10 @@ shared.reloadNote = async (comp: BaseNoteScreenComponent) => {
const fromShare = !!comp.props.sharedData;
if (note) {
const folder = Folder.byId(comp.props.folders, note.parent_id);
let folder = Folder.byId(comp.props.folders, note.parent_id);
if (!folder && note.parent_id) {
folder = await Folder.load(note.parent_id);
}
comp.setState({
lastSavedNote: { ...note },
note: note,
@@ -337,12 +340,24 @@ shared.reloadNote = async (comp: BaseNoteScreenComponent) => {
shared.initState = async function(comp: BaseNoteScreenComponent) {
const note = await shared.reloadNote(comp);
if (comp.props.sharedData) {
if (comp.props.sharedData && note) {
// Use the note returned by reloadNote directly to avoid a race condition where
// comp.state.note is still the initial empty note (Note.new() with parent_id='')
// because React hasn't flushed reloadNote's setState yet. Without this, the
// scheduled save would overwrite parent_id with an empty string in the DB.
const updatedNote = { ...note };
const fieldsToSave: NoteEntity = { id: note.id };
if (comp.props.sharedData.title) {
this.noteComponent_change(comp, 'title', comp.props.sharedData.title);
updatedNote.title = comp.props.sharedData.title;
fieldsToSave.title = comp.props.sharedData.title;
}
if (comp.props.sharedData.text) {
this.noteComponent_change(comp, 'body', comp.props.sharedData.text);
updatedNote.body = comp.props.sharedData.text;
fieldsToSave.body = comp.props.sharedData.text;
}
if (fieldsToSave.title !== undefined || fieldsToSave.body !== undefined) {
await Note.save(fieldsToSave);
comp.setState({ note: updatedNote, lastSavedNote: updatedNote });
}
if (comp.props.sharedData.resources) {
for (let i = 0; i < comp.props.sharedData.resources.length; i++) {
@@ -1177,6 +1177,25 @@ const builtInMetadata = (Setting: typeof SettingType) => {
startMinimized: { value: false, type: SettingItemType.Bool, storage: SettingStorage.File, isGlobal: true, section: 'application', public: true, appTypes: [AppType.Desktop], label: () => _('Start application minimised in the tray icon'), show: settings => !!settings['showTrayIcon'] },
'globalHotkey': {
value: '',
type: SettingItemType.String,
section: 'application',
public: true,
appTypes: [AppType.Desktop],
label: () => _('Global shortcut to show/hide Joplin'),
description: () => _('A system-wide keyboard shortcut that toggles the Joplin window. Works even when Joplin is not focused. Example: CommandOrControl+Shift+J. Leave empty to disable.'),
storage: SettingStorage.File,
isGlobal: true,
autoSave: true,
// Electron's globalShortcut API does not yet work under Wayland,
// so we hide this option when running on a Wayland session.
show: () => {
if (platform !== 'linux') return true;
return process.env.XDG_SESSION_TYPE !== 'wayland' && !process.env.WAYLAND_DISPLAY;
},
},
collapsedFolderIds: { value: [] as string[], type: SettingItemType.Array, public: false },
'keychain.supported': { value: -1, type: SettingItemType.Int, public: false },
@@ -1460,7 +1479,7 @@ const builtInMetadata = (Setting: typeof SettingType) => {
noteVisiblePanes: { value: ['editor', 'viewer'], type: SettingItemType.Array, storage: SettingStorage.File, isGlobal: true, public: false, appTypes: [AppType.Desktop] },
tagHeaderIsExpanded: { value: true, type: SettingItemType.Bool, public: false, appTypes: [AppType.Desktop] },
folderHeaderIsExpanded: { value: true, type: SettingItemType.Bool, public: false, appTypes: [AppType.Desktop] },
syncReportLogExpanded: { value: false, type: SettingItemType.Bool, public: false, appTypes: [AppType.Desktop] },
syncReportIsVisible: { value: false, type: SettingItemType.Bool, public: false, appTypes: [AppType.Desktop] },
editor: { value: '', type: SettingItemType.String, subType: 'file_path_and_args', storage: SettingStorage.File, isGlobal: true, public: true, appTypes: [AppType.Cli, AppType.Desktop], label: () => _('Text editor command'), description: () => _('The editor command (may include arguments) that will be used to open a note. If none is provided it will try to auto-detect the default editor.') },
'export.pdfPageSize': { value: 'A4', type: SettingItemType.String, advanced: true, storage: SettingStorage.File, isGlobal: true, isEnum: true, public: true, appTypes: [AppType.Desktop], label: () => _('Page size for PDF export'), options: () => {
return {
+11 -1
View File
@@ -162,7 +162,17 @@ export default class ExternalEditWatcher {
return;
}
let noteContent = await shim.fsDriver().readFile(path, 'utf-8');
let noteContent: string;
try {
noteContent = await shim.fsDriver().readFile(path, 'utf-8');
} catch (error) {
if (error.code === 'ENOENT') {
this.logger().warn(`ExternalEditWatcher: Watched file no longer exists: ${path}`);
void this.stopWatching(id);
return;
}
throw error;
}
// In some very rare cases, the "change" event is going to be emitted but the file will be empty.
// This is likely to be the editor that first clears the file, then writes the content to it, so if
@@ -67,6 +67,16 @@ export async function checkDecryptTestData(data: DecryptTestData, options: Check
messages.push(`Failed to decrypt data: Error: ${error}`);
}
try {
const decrypted = await EncryptionService.instance().decrypt(data.method, `${data.password}-bad`, data.ciphertext);
messages.push('Data could be decrypted with incorrect password');
messages.push('Expected:', data.plaintext);
messages.push('Got:', decrypted);
hasError = true;
} catch (error) {
messages.push(`Could not decrypt data with an invalid password (${error})`);
}
if (hasError && options.throwOnError) {
const label = options.testLabel ? ` (test ${options.testLabel})` : '';
throw new Error(`Testing Crypto failed${label}: \n${messages.join('\n')}`);
@@ -299,6 +299,14 @@ describe('InteropService_Importer_OneNote', () => {
expect(normalizeNoteForSnapshot(note2Content)).toMatchSnapshot();
});
it('should import vertically-scaled ink', async () => {
const notes = await importNote(`${supportDir}/onenote/scaled_ink.one`);
const note = notes.find(n => n.title === 'Scaled');
expectWithInstructions(note).toBeTruthy();
expectWithInstructions(normalizeNoteForSnapshot(note.body)).toMatchSnapshot();
});
it('should support directly importing .one files', async () => {
const notes = await importNote(`${supportDir}/onenote/onenote_desktop.one`);
@@ -368,4 +376,14 @@ describe('InteropService_Importer_OneNote', () => {
// The other section should import successfully
expect(notes.map(note => note.title).sort()).toEqual(['Test note', 'Test section']);
});
it('should import nested ink', async () => {
const notes = await importNote(`${supportDir}/onenote/desktop_missing_ink.one`);
expect(
notes
.filter(note => note.title === 'Ink Missing - only one example missing part')
.map(note => normalizeNoteForSnapshot(note.body))
.sort(),
).toMatchSnapshot();
});
});
@@ -35,6 +35,12 @@ const getOneNoteConverter = (): NativeOneNoteConverter => {
}
};
const setEnableUnresponsiveCheck = (enabled: boolean) => {
if (shim.isElectron()) {
shim.electronBridge().setEnableUnresponsiveCheck(enabled);
}
};
// See onenote-converter README.md for more information
export default class InteropService_Importer_OneNote extends InteropService_Importer_Base {
protected importedNotes: Record<string, NoteEntity> = {};
@@ -119,6 +125,11 @@ export default class InteropService_Importer_OneNote extends InteropService_Impo
}
try {
// HACK: The OneNote importer currently runs in the renderer process on desktop.
// If importing a large file takes a long time, the "unresponsive" dialog can be
// shown. Work around this by temporarily disabling the dialog:
setEnableUnresponsiveCheck(false);
await oneNoteConverter(notebookFilePath, resolve(outputDirectory2), notebookBaseDir);
} catch (error) {
// Forward only the error message. Usually the stack trace points to bytes in the WASM file.
@@ -126,6 +137,8 @@ export default class InteropService_Importer_OneNote extends InteropService_Impo
// length for auto-creating a forum post:
this.options_.onError?.(error.message ?? error);
console.error(error);
} finally {
setEnableUnresponsiveCheck(true);
}
}
@@ -942,6 +942,66 @@ exports[`InteropService_Importer_OneNote should import a simple OneNote notebook
</body></html>"
`;
exports[`InteropService_Importer_OneNote should import nested ink 1`] = `
[
"<!DOCTYPE HTML>
<html><head>
<meta charset="UTF-8">
<title>Ink Missing - only one example missing part</title>
<style>
/* (For testing: Removed default CSS) */
</style>
</head>
<body>
<div class="title" style="left: 48px; position: absolute; top: 24px;"><div class="container-outline" style="width: 753px;"><div class="outline-element" style="margin-left: 0px;"><span style="font-family: Calibri Light; font-size: 20pt; line-height: 32px;">Ink Missing - only one example missing part</span></div>
</div><div class="container-outline" style="width: 753px;"><div class="outline-element" style="margin-left: 0px;"><span style="color: rgb(118,118,118); font-family: Calibri; font-size: 10pt; line-height: 16px;">Mittwoch, 1. April 2026</span></div>
<div class="outline-element" style="margin-left: 0px;"><span style="color: rgb(118,118,118); font-family: Calibri; font-size: 10pt; line-height: 16px;">04:25</span></div>
</div></div><div class="container-outline" style="left: 277px; position: absolute; top: 485px; width: 474px;"><div class="outline-element" style="margin-left: 0px;"><p><span style="height: 54px; width: 90px;" class="ink-text"><img style="height: 54px; left: 22.9px; pointer-events: none; position: absolute; top: -2.61px; width: 90px;" src=":/id-here"></span><span class="ink-space" style="padding-left: 25px; padding-top: 77px;"></span><span style="height: 86px; width: 283px;" class="ink-text"><img style="height: 86px; left: -2.61px; pointer-events: none; position: absolute; top: 5.78px; width: 283px;" src=":/id-here"></span></p></div>
<div class="outline-element" style="margin-left: 0px;"><p><span style="height: 70px; width: 190px;" class="ink-text"><img style="height: 70px; left: -2.61px; pointer-events: none; position: absolute; top: -10.05px; width: 190px;" src=":/id-here"></span></p></div>
<div class="outline-element" style="margin-left: 0px;"><p><span style="height: 68px; width: 344px;" class="ink-text"><img style="height: 68px; left: 34.28px; pointer-events: none; position: absolute; top: 7.56px; width: 344px;" src=":/id-here"></span></p></div>
</div><div class="container-outline" style="left: 262px; position: absolute; top: 130px; width: 624px;"><div class="outline-element" style="margin-left: 0px;"><p style="font-family: Calibri; font-size: 11pt; line-height: 17px;">&nbsp;</p></div>
</div><div class="container-outline" style="left: 285px; position: absolute; top: 243px; width: 624px;"><div class="outline-element" style="margin-left: 0px;"><p style="font-family: Calibri; font-size: 11pt;">&nbsp;</p></div>
</div><div class="container-outline" style="left: 560px; position: absolute; top: 195px; width: 624px;"><div class="outline-element" style="margin-left: 0px;"><p style="font-family: Calibri; font-size: 11pt; line-height: 17px;">&nbsp;</p></div>
</div>
</body></html>",
]
`;
exports[`InteropService_Importer_OneNote should import vertically-scaled ink 1`] = `
"<!DOCTYPE HTML>
<html><head>
<meta charset="UTF-8">
<title>Scaled</title>
<style>
/* (For testing: Removed default CSS) */
</style>
</head>
<body>
<div class="title" style="left: 48px; position: absolute; top: 24px;"><div class="container-outline" style="width: 624px;"><div class="outline-element" style="margin-left: 0px;"><span style="font-family: Calibri Light; font-size: 20pt; line-height: 32px;">Scaled</span></div>
</div><div class="container-outline" style="width: 624px;"><div class="outline-element" style="margin-left: 0px;"><span style="color: rgb(118,118,118); font-family: Calibri; font-size: 10pt; line-height: 16px;">Wednesday, April 15, 2026</span></div>
<div class="outline-element" style="margin-left: 0px;"><span style="color: rgb(118,118,118); font-family: Calibri; font-size: 10pt; line-height: 16px;">12:36 AM</span></div>
</div></div><img style="height: 492.21px; left: 128.13px; pointer-events: none; position: absolute; top: 144.3px; width: 187.42px;" src=":/id-here">
</body></html>"
`;
@@ -1414,7 +1474,7 @@ exports[`InteropService_Importer_OneNote should use default value for EntityGuid
</div><div class="container-outline" style="left: 72px; position: absolute; top: 475px; width: 146px;"><div class="outline-element" style="margin-left: 0px;"><p style="color: rgb(91,155,213); font-family: Trebuchet MS; font-size: 12pt; line-height: 19px;">Customer Success Management</p></div>
<div class="outline-element" style="margin-left: 0px;"><p style="color: rgb(91,155,213); font-family: Trebuchet MS; font-size: 12pt; line-height: 19px;">and</p></div>
<div class="outline-element" style="margin-left: 0px;"><p style="color: rgb(91,155,213); font-family: Trebuchet MS; font-size: 12pt; line-height: 19px;">Training</p></div>
</div><img style="height: 170px; left: 57.15px; pointer-events: none; position: absolute; top: 435.1px; width: 310px;" src=":/id-here">
</div><img style="height: 173px; left: 57.15px; pointer-events: none; position: absolute; top: 443.15px; width: 310px;" src=":/id-here">
+8 -26
View File
@@ -287,25 +287,15 @@ export default class PluginService extends BaseService {
return this.loadPlugin(baseDir, r.manifestText, r.scriptText, pluginIdIfNotSpecified);
}
public async loadPluginFromPackage(baseDir: string, path: string, manifestOnly = false): Promise<Plugin> {
public async loadPluginFromPackage(baseDir: string, path: string): Promise<Plugin> {
baseDir = rtrimSlashes(baseDir);
const fname = filename(path);
const hash = await shim.fsDriver().md5File(path);
const unpackDir = `${Setting.value('cacheDir')}/${fname}`;
const manifestFilePath = `${unpackDir}/manifest.json`;
if (manifestOnly) {
// When loading only the manifest (e.g. for disabled plugins), try
// to use an already-extracted manifest from cache to avoid the
// expensive MD5 hash and tar extraction.
const manifest = await this.loadManifestToObject(manifestFilePath);
if (manifest) {
return this.loadPlugin(unpackDir, JSON.stringify(manifest), '', makePluginId(fname));
}
}
const hash = await shim.fsDriver().md5File(path);
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
let manifest: any = await this.loadManifestToObject(manifestFilePath);
@@ -328,7 +318,7 @@ export default class PluginService extends BaseService {
await shim.fsDriver().writeFile(manifestFilePath, JSON.stringify(manifest, null, '\t'), 'utf8');
}
return this.loadPluginFromPath(unpackDir, manifestOnly);
return this.loadPluginFromPath(unpackDir);
}
// Loads the manifest as a simple object with no validation. Used only
@@ -343,7 +333,7 @@ export default class PluginService extends BaseService {
}
}
public async loadPluginFromPath(path: string, manifestOnly = false): Promise<Plugin> {
public async loadPluginFromPath(path: string): Promise<Plugin> {
path = rtrimSlashes(path);
const fsDriver = shim.fsDriver();
@@ -351,7 +341,7 @@ export default class PluginService extends BaseService {
if (path.toLowerCase().endsWith('.js')) {
return this.loadPluginFromJsBundle(dirname(path), await fsDriver.readFile(path), filename(path));
} else if (path.toLowerCase().endsWith('.jpl')) {
return this.loadPluginFromPackage(dirname(path), path, manifestOnly);
return this.loadPluginFromPackage(dirname(path), path);
} else {
let distPath = path;
if (!(await fsDriver.exists(`${distPath}/manifest.json`))) {
@@ -360,8 +350,8 @@ export default class PluginService extends BaseService {
logger.info(`Loading plugin from ${path}`);
const scriptText = await fsDriver.readFile(`${distPath}/index.js`);
const manifestText = await fsDriver.readFile(`${distPath}/manifest.json`);
const scriptText = manifestOnly ? '' : await fsDriver.readFile(`${distPath}/index.js`);
const pluginId = makePluginId(filename(path));
return this.loadPlugin(distPath, manifestText, scriptText, pluginId);
@@ -459,16 +449,8 @@ export default class PluginService extends BaseService {
}
try {
// Load only the manifest first to check if the plugin is
// enabled before doing the expensive full load.
let plugin = await this.loadPluginFromPath(pluginPath, true);
const plugin = await this.loadPluginFromPath(pluginPath);
const enabled = this.pluginEnabled(settings, plugin.id);
if (enabled) {
logger.info(`Loading full plugin: ${plugin.id}`);
plugin = await this.loadPluginFromPath(pluginPath, false);
} else {
logger.info(`Loading manifest only for disabled plugin: ${plugin.id}`);
}
const existingPlugin = this.plugins_[plugin.id];
if (existingPlugin) {
@@ -1,5 +1,5 @@
import Setting from '../../models/Setting';
import PluginService, { defaultPluginSetting } from '../../services/plugins/PluginService';
import PluginService from '../../services/plugins/PluginService';
import { setupDatabaseAndSynchronizer, switchClient, withWarningSilenced } from '../../testing/test-utils';
import loadPlugins, { Props as LoadPluginsProps } from './loadPlugins';
import MockPluginRunner from './testing/MockPluginRunner';
@@ -8,9 +8,6 @@ import { Action, createStore } from 'redux';
import MockPlatformImplementation from './testing/MockPlatformImplementation';
import createTestPlugin from '../../testing/plugins/createTestPlugin';
import Plugin from './Plugin';
import { PluginManifest } from './utils/types';
import { writeFile, mkdirp } from 'fs-extra';
import { join } from 'path';
const createMockReduxStore = () => {
return createStore((state: State = defaultState, action: Action<string>) => {
@@ -139,33 +136,6 @@ describe('loadPlugins', () => {
expect([...pluginRunner.runningPluginIds].sort()).toMatchObject(expectedRunningIds);
});
test('should not load the script for disabled plugins', async () => {
const createDirPlugin = async (manifest: PluginManifest, enabled: boolean) => {
const dir = join(Setting.value('pluginDir'), manifest.id);
await mkdirp(dir);
await writeFile(join(dir, 'manifest.json'), JSON.stringify(manifest), 'utf-8');
await writeFile(join(dir, 'index.js'), 'joplin.plugins.register({ onStart: async function() {} });', 'utf-8');
const newStates = {
...Setting.value('plugins.states'),
[manifest.id]: { ...defaultPluginSetting(), enabled },
};
Setting.setValue('plugins.states', newStates);
};
const enabledId = 'joplin.test.plugin.enabled';
const disabledId = 'joplin.test.plugin.disabled';
await createDirPlugin({ ...defaultManifestProperties, id: enabledId, name: 'Enabled' }, true);
await createDirPlugin({ ...defaultManifestProperties, id: disabledId, name: 'Disabled' }, false);
const pluginRunner = new MockPluginRunner();
const store = createMockReduxStore();
PluginService.instance().initialize('2.3.4', platformImplementation, pluginRunner, store);
await PluginService.instance().loadAndRunPlugins(Setting.value('pluginDir'), Setting.value('plugins.states'));
expect(PluginService.instance().plugins[disabledId].scriptText).toBe('');
expect(PluginService.instance().plugins[enabledId].scriptText).not.toBe('');
});
test('should not block allPluginsStarted when a plugin fails to start', async () => {
// This tests the fix for https://github.com/laurent22/joplin/issues/12793
// When a plugin crashes before calling register(), it should not block
+1 -1
View File
@@ -491,7 +491,7 @@ const shim = {
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
writeImageToFile: (_image: any, _format: any, _filePath: string): void => {
writeImageToFile: (_image: any, _format: any, _filePath: string): Promise<void> => {
throw new Error('Not implemented');
},
+16
View File
@@ -90,7 +90,23 @@ Suppose that the importer's Rust code is failing to parse a specific `example.on
2. Setting up Rust and Rust debugging. See [the relevant VSCode documentation](https://code.visualstudio.com/docs/languages/rust#_debugging) for details.
3. Clicking the "Debug" button for the test added in step 1. This button should be provided by extensions set up in step 2.
### Inspecting `.one` files
The `inspect` binary target of the `parser` crate allows inspecting `.one` file data.
For example, to inspect lower-level OneStore data:
```console
bash$ cd parser/
bash$ cargo run -- ../test-data/ink.one --onestore
```
To inspect higher-level (parsed) section data:
```console
bash$ cd parser/
bash$ cargo run -- ../test-data/ink.one --section
```
**Note**: `inspect`'s output is unstable and should not be relied upon by scripts.
### Developing
@@ -30,9 +30,17 @@ function normalizeAndWriteFile(filePath, data) {
function fileReader(path) {
const fd = fs.openSync(path);
const size = fs.fstatSync(fd).size;
// TODO: When Node v20 is EOL, replace this with the { bigint: true }
// parameter variant.
const size = BigInt(fs.fstatSync(fd).size);
return {
read: (position, length) => {
read: (bigPosition, bigLength) => {
// Rust uses u64 for position/length which is transferred to JS as a BigInt.
// Convert:
const length = Number(bigLength);
const position = Number(bigPosition);
const data = Buffer.alloc(length);
const sizeRead = fs.readSync(fd, data, { length, position });
@@ -0,0 +1,15 @@
/// A struct that has a specific `fmt::Debug` serialization.
/// Useful when customizing a `struct`'s debug output.
pub struct DebugOutput<'a>(&'a str);
impl<'a> From<&'a str> for DebugOutput<'a> {
fn from(value: &'a str) -> Self {
Self(value)
}
}
impl<'a> std::fmt::Debug for DebugOutput<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
@@ -1,6 +1,7 @@
//! OneNote parsing error handling.
use std::borrow::Cow;
use std::num::TryFromIntError;
use std::{io, string};
use thiserror::Error;
@@ -27,7 +28,11 @@ impl From<ErrorKind> for Error {
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Self {
ErrorKind::from(err).into()
if err.kind() == std::io::ErrorKind::UnexpectedEof {
ErrorKind::UnexpectedEof(err.to_string().into()).into()
} else {
ErrorKind::from(err).into()
}
}
}
@@ -43,6 +48,18 @@ impl From<widestring::error::MissingNulTerminator> for Error {
}
}
impl From<widestring::error::Utf16Error> for Error {
fn from(err: widestring::error::Utf16Error) -> Self {
ErrorKind::from(err).into()
}
}
impl From<TryFromIntError> for Error {
fn from(err: TryFromIntError) -> Self {
ErrorKind::from(err).into()
}
}
impl From<uuid::Error> for Error {
fn from(err: uuid::Error) -> Self {
ErrorKind::from(err).into()
@@ -107,6 +124,12 @@ pub enum ErrorKind {
#[error("Failed to resolve: {0}")]
ResolutionFailed(Cow<'static, str>),
#[error("Type conversion failed: {err}")]
TypeConversionFailed {
#[from]
err: TryFromIntError,
},
/// A malformed UUID was encountered
#[error("Invalid UUID: {err}")]
InvalidUuid {
@@ -128,6 +151,13 @@ pub enum ErrorKind {
err: string::FromUtf16Error,
},
/// A different type of malformed UTF-16 string was encountered during parsing.
#[error("Malformed UTF-16 string: {err}")]
Utf16LibError {
#[from]
err: widestring::error::Utf16Error,
},
/// A UTF-16 string without a null terminator was encountered during parsing.
#[error("UTF-16 string is missing null terminator: {err}")]
Utf16MissingNull {
@@ -2,7 +2,9 @@ use sanitize_filename::{Options as SanitizeOptions, sanitize_with_options};
use std::io::{Read, Seek};
pub type ApiResult<T> = std::result::Result<T, std::io::Error>;
pub trait FileHandle: Read + Seek {}
pub trait FileHandle: Read + Seek {
fn byte_length(&self) -> u64;
}
pub trait FileApiDriver: Send + Sync {
fn is_windows(&self) -> bool;
@@ -2,6 +2,7 @@ use super::ApiResult;
use super::FileApiDriver;
use super::FileHandle;
use std::fs;
use std::io::BufReader;
use std::path;
use std::path::Path;
@@ -38,7 +39,7 @@ impl FileApiDriver for FileApiDriverImpl {
}
fn open_file(&self, path: &str) -> ApiResult<Box<dyn FileHandle>> {
Ok(Box::new(fs::File::open(path)?))
Ok(Box::new(BufReader::new(fs::File::open(path)?)))
}
fn write_file(&self, path: &str, data: &[u8]) -> ApiResult<()> {
@@ -87,7 +88,11 @@ impl FileApiDriver for FileApiDriverImpl {
}
}
impl FileHandle for fs::File {}
impl FileHandle for BufReader<fs::File> {
fn byte_length(&self) -> u64 {
self.get_ref().metadata().map(|m| m.len()).unwrap_or(0)
}
}
#[cfg(test)]
mod test {
@@ -48,12 +48,12 @@ extern "C" {
#[wasm_bindgen(structural, method, catch)]
fn read(
this: &JsFileHandle,
offset: usize,
size: usize,
offset: u64,
size: u64,
) -> std::result::Result<Uint8Array, JsValue>;
#[wasm_bindgen(structural, method)]
fn size(this: &JsFileHandle) -> usize;
fn size(this: &JsFileHandle) -> u64;
#[wasm_bindgen(structural, method, catch)]
fn close(this: &JsFileHandle) -> std::result::Result<(), JsValue>;
@@ -181,7 +181,7 @@ impl FileApiDriver for FileApiDriverImpl {
struct SeekableFileHandle {
handle: JsFileHandle,
offset: usize,
offset: u64,
}
impl Read for SeekableFileHandle {
@@ -193,12 +193,12 @@ impl Read for SeekableFileHandle {
0
};
let maximum_read_size = bytes_remaining.min(out.len());
let maximum_read_size = bytes_remaining.min(out.len() as u64);
match self.handle.read(self.offset, maximum_read_size) {
Ok(data) => {
let data = data.to_vec();
let size = data.len();
self.offset += size;
self.offset += size as u64;
// Verify that handle.read respected the maximum length:
if size > out.len() {
@@ -228,25 +228,25 @@ impl Seek for SeekableFileHandle {
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
match pos {
SeekFrom::Start(pos) => {
self.offset = pos as usize;
self.offset = pos;
}
SeekFrom::Current(offset) => {
// Disallow seeking to a negative position
if offset < 0 && (-offset) as usize > self.offset {
if offset < 0 && offset.unsigned_abs() > self.offset {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Attempted to seek before the beginning of the file.",
));
}
self.offset = (self.offset as i64 + offset) as usize;
self.offset = (self.offset as i64 + offset) as u64;
}
SeekFrom::End(offset) => {
self.offset = self.handle.size();
self.seek(SeekFrom::Current(offset))?;
}
}
Ok(self.offset as u64)
Ok(self.offset)
}
}
@@ -261,4 +261,8 @@ impl Drop for SeekableFileHandle {
}
}
impl FileHandle for BufReader<SeekableFileHandle> {}
impl FileHandle for BufReader<SeekableFileHandle> {
fn byte_length(&self) -> u64 {
self.get_ref().handle.size()
}
}
@@ -2,6 +2,7 @@
use widestring::U16CString;
pub mod debug;
pub mod errors;
mod file_api;
pub mod log;
@@ -26,6 +27,6 @@ impl Utf16ToString for &[u8] {
.collect();
let value = U16CString::from_vec_truncate(data);
Ok(value.to_string().unwrap())
value.to_string().map_err(|err| err.into())
}
}
@@ -1,72 +1,182 @@
use crate::errors::{ErrorKind, Result};
use crate::{
FileHandle,
errors::{ErrorKind, Result},
};
use bytes::Buf;
use paste::paste;
use std::mem;
use std::{
cell::RefCell,
io::{Read, Seek, SeekFrom},
mem,
rc::Rc,
};
macro_rules! try_get {
($this:ident, $typ:tt) => {{
if $this.buff.remaining() < mem::size_of::<$typ>() {
if $this.remaining() < mem::size_of::<$typ>() as u64 {
Err(ErrorKind::UnexpectedEof(format!("Getting {:}", stringify!($typ)).into()).into())
} else {
Ok(paste! {$this.buff. [< get_ $typ >]()})
let mut buff = [0; mem::size_of::<$typ>()];
$this.read_exact(&mut buff)?;
let mut buff_ref: &[u8] = &mut buff;
Ok(paste! {buff_ref. [< get_ $typ >]()})
}
}};
($this:ident, $typ:tt::$endian:tt) => {{
if $this.buff.remaining() < mem::size_of::<$typ>() {
if $this.remaining() < mem::size_of::<$typ>() as u64 {
Err(ErrorKind::UnexpectedEof(
format!("Getting {:} ({:})", stringify!($typ), stringify!($endian)).into(),
)
.into())
} else {
Ok(paste! {$this.buff. [< get_ $typ _ $endian >]()})
let mut buff = [0; mem::size_of::<$typ>()];
$this.read_exact(&mut buff)?;
let mut buff_ref: &[u8] = &mut buff;
Ok(paste! {buff_ref. [< get_ $typ _ $endian >]()})
}
}};
}
pub struct Reader<'a> {
buff: &'a [u8],
original: &'a [u8],
type ReaderFileHandle = Rc<RefCell<Box<dyn FileHandle>>>;
enum ReaderData<'a> {
/// Wraps a buffer owned by calling logic. This is more efficient for
/// small amounts of data.
BufferRef { buffer: &'a [u8] },
/// Wraps a handle to a file. This handles large amounts of data
/// that won't necessarily fit into memory.
/// Invariant: The internal file handle's offset should match the
/// `data_offset` of the main reader.
File(ReaderFileHandle),
}
impl<'a> Clone for Reader<'a> {
fn clone(&self) -> Self {
let mut result = Self::new(self.original);
result
.advance(self.absolute_offset())
.expect("should re-advance to the original's position");
result
pub struct Reader<'a> {
data: ReaderData<'a>,
data_len: u64,
data_offset: u64,
}
pub struct ReaderOffset(u64);
impl<'a> Seek for Reader<'a> {
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
let new_offset = match pos {
SeekFrom::Start(n) => n as i64,
SeekFrom::Current(n) => self.data_offset as i64 + n,
SeekFrom::End(n) => (self.data_len as i64) + n,
};
if new_offset < 0 || new_offset as u64 > self.data_len {
Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
format!(
"New offset {} is out-of-bounds (data length: {}).",
new_offset, self.data_len
),
))
} else {
self.data_offset = new_offset as u64;
// Sync the internal file with the new offset. This is done rather than seek the file
// directly to avoid inconsistency if e.g. the file resizes and we're seeking from the end.
if let ReaderData::File(f) = &mut self.data {
f.borrow_mut().seek(SeekFrom::Start(self.data_offset))?;
}
Ok(self.data_offset)
}
}
}
impl<'a> Reader<'a> {
pub fn new(data: &'a [u8]) -> Reader<'a> {
pub fn new(buffer: &'a [u8]) -> Self {
Reader {
buff: data,
original: data,
data_len: buffer.len() as u64,
data_offset: 0,
data: ReaderData::BufferRef { buffer },
}
}
pub fn read(&mut self, cnt: usize) -> Result<&'a [u8]> {
if self.remaining() < cnt {
return Err(ErrorKind::UnexpectedEof("Unexpected EOF (Reader.read)".into()).into());
pub fn read(&mut self, count: usize) -> Result<Vec<u8>> {
let mut buff = vec![0; count];
self.read_exact(&mut buff)?;
Ok(buff)
}
fn read_exact(&mut self, output: &mut [u8]) -> Result<()> {
let count = output.len();
if self.remaining() < count as u64 {
return Err(
ErrorKind::UnexpectedEof("Unexpected EOF (Reader.read_exact)".into()).into(),
);
}
let data = &self.buff[0..cnt];
self.buff.advance(cnt);
match &mut self.data {
ReaderData::BufferRef { buffer } => {
let start = self.data_offset as usize;
(&buffer[start..start + count]).copy_to_slice(output);
}
ReaderData::File(file) => {
file.borrow_mut().read_exact(output)?;
}
};
self.data_offset += count as u64;
Ok(data)
Ok(())
}
pub fn bytes(&self) -> &[u8] {
self.buff.chunk()
pub fn peek_u8(&mut self) -> Result<Option<u8>> {
match &mut self.data {
ReaderData::BufferRef { buffer, .. } => {
Ok(buffer.get(self.data_offset as usize).copied())
}
ReaderData::File(file) => {
let mut file = file.borrow_mut();
let mut buf = [0u8];
let read_result = file.read(&mut buf);
// Reset the original position
file.seek(SeekFrom::Start(self.data_offset))?;
match read_result {
Ok(size) => Ok(if size < 1 { None } else { Some(buf[0]) }),
Err(error) => Err(error)?,
}
}
}
}
pub fn remaining(&self) -> usize {
self.buff.remaining()
pub fn as_data_ref(&mut self, size: usize) -> Result<ReaderDataRef> {
if self.remaining() < size as u64 {
return Err(
ErrorKind::UnexpectedEof("Unexpected EOF (Reader.as_data_ref)".into()).into(),
);
}
match &mut self.data {
ReaderData::BufferRef { buffer } => {
let start = self.data_offset as usize;
// Cloning needs to be done early with BufferRef, since we don't own the original
// data. Large data should generally use `ReaderData::File`.
Ok(ReaderDataRef::Vec(buffer[start..start + size].to_vec()))
}
ReaderData::File(file) => Ok(ReaderDataRef::FilePointer {
file: file.clone(),
offset: self.data_offset,
size,
}),
}
}
pub fn advance(&mut self, count: usize) -> Result<()> {
pub fn remaining(&self) -> u64 {
assert!(self.data_len >= self.data_offset);
self.data_len - self.data_offset
}
pub fn advance(&mut self, count: u64) -> Result<()> {
if self.remaining() < count {
return Err(ErrorKind::UnexpectedEof(
format!(
@@ -79,41 +189,23 @@ impl<'a> Reader<'a> {
.into());
}
self.buff.advance(count);
assert!(count < i64::MAX as u64);
self.seek(SeekFrom::Current(count as i64))?;
Ok(())
}
pub fn absolute_offset(&self) -> usize {
// Use pointer arithmetic (in a way similar to the [subslice offset](https://docs.rs/crate/subslice-offset/latest/source/src/lib.rs)
// crate and [this StackOverflow post](https://stackoverflow.com/questions/50781561/how-to-find-the-starting-offset-of-a-string-slice-of-another-string/50781657))
// to calculate the offset.
let offset = (self.buff.as_ptr() as usize) - (self.original.as_ptr() as usize);
if offset > self.original.len() {
panic!("self.buff must be a subslice of self.original!");
}
offset
pub fn save_position(&self) -> ReaderOffset {
ReaderOffset(self.data_offset)
}
pub fn with_updated_bounds(&self, start: usize, end: usize) -> Result<Reader<'a>> {
if start > self.original.len() {
return Err(ErrorKind::UnexpectedEof(
"Reader.with_updated_bounds: start is out of bounds".into(),
)
.into());
}
if end > self.original.len() {
return Err(ErrorKind::UnexpectedEof(
"Reader.with_updated_bounds: end is out of bounds".into(),
)
.into());
}
pub fn restore_position(&mut self, offset: ReaderOffset) -> Result<()> {
self.seek(SeekFrom::Start(offset.0))?;
Ok(())
}
Ok(Reader {
buff: &self.original[start..end],
original: self.original,
})
pub fn offset(&self) -> u64 {
self.data_offset
}
pub fn get_u8(&mut self) -> Result<u8> {
@@ -141,6 +233,61 @@ impl<'a> Reader<'a> {
}
}
impl<'a> TryFrom<Box<dyn FileHandle>> for Reader<'a> {
type Error = crate::errors::Error;
fn try_from(mut handle: Box<dyn FileHandle>) -> Result<Self> {
let initial_offset = handle.seek(SeekFrom::Current(0))?;
Ok(Self {
data_len: handle.byte_length(),
data_offset: initial_offset,
data: ReaderData::File(Rc::new(RefCell::new(handle))),
})
}
}
impl<'a> From<&'a [u8]> for Reader<'a> {
fn from(value: &'a [u8]) -> Self {
Self {
data_len: value.len() as u64,
data_offset: 0,
data: ReaderData::BufferRef { buffer: value },
}
}
}
pub enum ReaderDataRef {
Vec(Vec<u8>),
FilePointer {
file: ReaderFileHandle,
offset: u64,
size: usize,
},
}
impl ReaderDataRef {
pub fn bytes(&self) -> Result<Vec<u8>> {
match self {
ReaderDataRef::Vec(slice) => Ok(slice.clone()),
ReaderDataRef::FilePointer { file, offset, size } => {
let mut file = file.borrow_mut();
let original_offset = file.seek(SeekFrom::Current(0))?;
let read_result = (|| {
file.seek(SeekFrom::Start(*offset))?;
let mut result = vec![0; *size];
file.read_exact(&mut result)?;
Ok(result)
})();
file.seek(SeekFrom::Start(original_offset))?;
read_result
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
@@ -148,27 +295,23 @@ mod test {
#[test]
fn with_start_index_should_seek() {
let data: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
let mut reader = Reader::new(&data);
let mut reader = Reader::from(&data as &[u8]);
assert_eq!(reader.get_u8().unwrap(), 1);
assert_eq!(reader.get_u8().unwrap(), 2);
assert_eq!(reader.get_u8().unwrap(), 3);
{
let mut reader = reader.with_updated_bounds(0, 8).unwrap();
assert_eq!(reader.get_u8().unwrap(), 1);
assert_eq!(reader.get_u8().unwrap(), 2);
assert_eq!(reader.get_u8().unwrap(), 3);
assert_eq!(reader.get_u8().unwrap(), 4);
let mut reader = reader.with_updated_bounds(1, 7).unwrap();
assert_eq!(reader.get_u8().unwrap(), 2);
assert_eq!(reader.get_u8().unwrap(), 3);
let mut reader = reader.with_updated_bounds(1, 7).unwrap();
assert_eq!(reader.get_u8().unwrap(), 2);
assert_eq!(reader.get_u8().unwrap(), 3);
let reader = reader.with_updated_bounds(5, 7).unwrap();
assert_eq!(reader.remaining(), 2);
let reader = reader.with_updated_bounds(6, 6).unwrap();
assert_eq!(reader.remaining(), 0);
}
reader.seek(SeekFrom::Start(0)).unwrap();
assert_eq!(reader.get_u8().unwrap(), 1);
assert_eq!(reader.get_u8().unwrap(), 2);
assert_eq!(reader.get_u8().unwrap(), 3);
assert_eq!(reader.get_u8().unwrap(), 4);
reader.seek_relative(-3).unwrap();
assert_eq!(reader.get_u8().unwrap(), 2);
assert_eq!(reader.get_u8().unwrap(), 3);
reader.seek_relative(-2).unwrap();
assert_eq!(reader.get_u8().unwrap(), 2);
assert_eq!(reader.get_u8().unwrap(), 3);
assert_eq!(reader.get_u8().unwrap(), 4);
}
}
@@ -33,3 +33,6 @@ features = [
[lib]
crate-type = ["cdylib", "lib"]
[[bin]]
name = "inspect"
@@ -0,0 +1,111 @@
use parser::Parser;
use parser_utils::errors::Error;
use std::{
env::{self, Args},
process::exit,
};
pub fn main() {
let config = match Config::from_args(&mut env::args()) {
Ok(config) => config,
Err(error) => {
print_help_text(&error.program_name, error.reason);
exit(1)
}
};
let input_path_string = &config.input_file;
let mut parser = Parser::new();
if config.output_mode == OutputMode::Section {
let parsed_section = match parser.parse_section(input_path_string) {
Ok(section) => section,
Err(error) => handle_parse_error(&config, error),
};
println!("{:#?}", parsed_section);
} else {
let parsed_onestore = match parser.parse_onestore_raw(input_path_string) {
Ok(section) => section,
Err(error) => handle_parse_error(&config, error),
};
println!("{:#?}", parsed_onestore);
}
}
fn handle_parse_error(config: &Config, error: Error) -> ! {
let error = format!("Parse error: {error}");
print_help_text(&config.program_name, &error);
exit(3)
}
fn print_help_text(program_name: &str, error: &str) {
let error_info = if error.is_empty() { "" } else { error };
eprintln!("Usage: {program_name} <input_file> [--section|--onestore]");
eprintln!("Description: Prints debug information about the given <input_file>");
eprintln!("{error_info}");
}
struct ConfigParseError {
reason: &'static str,
program_name: String,
}
#[derive(PartialEq)]
enum OutputMode {
/// Lower-level output
FileContent,
/// Higher-level output, including the parsed objects
Section,
}
struct Config {
input_file: String,
output_mode: OutputMode,
program_name: String,
}
impl Config {
pub fn from_args(args: &mut Args) -> Result<Self, ConfigParseError> {
let Some(program_name) = &args.next() else {
return Err(ConfigParseError {
reason: "Missing program name",
program_name: "??".into(),
});
};
let program_name = program_name.to_string();
let Some(input_file) = args.next() else {
return Err(ConfigParseError {
reason: "Not enough arguments",
program_name,
});
};
let output_mode = args.next().unwrap_or("--onestore".into());
let output_mode = match output_mode.as_str() {
"--onestore" => Ok(OutputMode::FileContent),
"--section" => Ok(OutputMode::Section),
_ => {
return Err(ConfigParseError {
reason: "Invalid output mode (expected --onestore or --section)",
program_name,
});
}
}?;
if args.next().is_some() {
return Err(ConfigParseError {
reason: "Too many arguments",
program_name,
});
}
Ok(Config {
input_file,
output_mode,
program_name,
})
}
}
@@ -13,7 +13,7 @@ pub(crate) struct BinaryItem(Vec<u8>);
impl BinaryItem {
pub(crate) fn parse(reader: Reader) -> Result<BinaryItem> {
let size = CompactU64::parse(reader)?.value();
let data = reader.read(size as usize)?.to_vec();
let data = reader.read(size.try_into()?)?;
Ok(BinaryItem(data))
}
@@ -25,6 +25,9 @@ impl BinaryItem {
impl From<BinaryItem> for FileBlob {
fn from(value: BinaryItem) -> Self {
value.0.into()
let size = value.0.len();
let data = value.0;
FileBlob::new(Box::new(data), size)
}
}
@@ -24,8 +24,7 @@ impl ObjectHeader {
/// Parse a 16-bit or 32-bit stream object header.
pub(crate) fn parse(reader: Reader) -> Result<ObjectHeader> {
let header_type = reader
.bytes()
.first()
.peek_u8()?
.ok_or(ErrorKind::UnexpectedEof("Reading ObjectHeader".into()))?;
match header_type & 0b11 {
@@ -199,7 +198,7 @@ impl ObjectHeader {
}
pub(crate) fn has_end_8(reader: Reader, object_type: ObjectType) -> Result<bool> {
let data = reader.bytes().first().ok_or(ErrorKind::UnexpectedEof(
let data = reader.peek_u8()?.ok_or(ErrorKind::UnexpectedEof(
"Reading ObjectHeader.has_end_8".into(),
))?;
@@ -42,7 +42,7 @@ impl DataElement {
let offset = CompactU64::parse(reader)?.value();
let length = CompactU64::parse(reader)?.value();
let data = reader.read(size as usize)?.to_vec();
let data = reader.read(size as usize)?;
let chunk_reference = DataElementFragmentChunkReference { offset, length };
let fragment = DataElementFragment {
@@ -22,7 +22,7 @@ impl ObjectDataBlob {
impl fmt::Debug for ObjectDataBlob {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ObjectDataBlob({} bytes)", self.0.as_ref().len())
write!(f, "ObjectDataBlob({} bytes)", self.0.len())
}
}
@@ -11,7 +11,6 @@ mod one;
mod onenote;
mod onestore;
mod shared;
mod utils;
pub use onenote::Parser;
@@ -1,3 +1,5 @@
use std::io::{Seek, SeekFrom};
use parser_utils::{errors::ErrorKind, errors::Result, parse::Parse};
/// See [\[MS-ONESTORE\] 2.2.4](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/0d86b13d-d58c-44e8-b931-4728b9d39a4b)
@@ -7,10 +9,7 @@ pub trait FileChunkReference {
fn data_location(&self) -> usize;
fn data_size(&self) -> usize;
fn resolve_to_reader<'a>(
&self,
original_reader: &parser_utils::reader::Reader<'a>,
) -> Result<parser_utils::reader::Reader<'a>> {
fn seek_reader_to(&self, reader: &mut parser_utils::reader::Reader) -> Result<()> {
if self.is_fcr_nil() {
return Err(ErrorKind::ResolutionFailed(
"Failed to resolve node reference -- is nil".into(),
@@ -18,10 +17,8 @@ pub trait FileChunkReference {
.into());
}
original_reader.with_updated_bounds(
self.data_location(),
self.data_location() + self.data_size(),
)
reader.seek(SeekFrom::Start(self.data_location() as u64))?;
Ok(())
}
}
@@ -56,8 +56,15 @@ impl FileNode {
)?),
2 => FileNodeDataRef::ElementList({
let list_ref = FileNodeChunkReference::parse(reader, stp_format, cb_format)?;
let mut resolved_reader = list_ref.resolve_to_reader(reader)?;
FileNodeList::parse(&mut resolved_reader, context, list_ref.data_size())
let reader_offset = reader.save_position();
let result = {
list_ref.seek_reader_to(reader)?;
FileNodeList::parse(reader, context, list_ref.data_size())
};
reader.restore_position(reader_offset)?;
result
}?),
_ => FileNodeDataRef::InvalidData,
};
@@ -162,7 +169,7 @@ impl FileNode {
0 => FileNodeData::Null,
other => {
log_warn!("Unknown node type: {:#0x}, size {}", other, size);
let size_used = remaining_0 - remaining_1;
let size_used = (remaining_0 - remaining_1) as usize;
assert!(size_used <= size);
let remaining_size = size - size_used;
FileNodeData::UnknownNode(UnknownNode::parse(reader, remaining_size)?)
@@ -170,7 +177,7 @@ impl FileNode {
};
let remaining_2 = reader.remaining();
let actual_size = remaining_0 - remaining_2;
let actual_size = (remaining_0 - remaining_2) as usize;
let node = Self {
node_type_id: node_id,
@@ -452,9 +459,14 @@ impl<RefSize: Parse> ParseWithRef for ObjectDeclarationWithSizedRefCount<RefSize
fn read_property_set(reader: Reader, property_set_ref: &FileNodeDataRef) -> Result<ObjectPropSet> {
match property_set_ref {
FileNodeDataRef::SingleElement(data_ref) => {
let mut prop_set_reader = data_ref.resolve_to_reader(reader)?;
let prop_set = ObjectPropSet::parse(&mut prop_set_reader)?;
Ok(prop_set)
let reader_offset = reader.save_position();
let prop_set = {
data_ref.seek_reader_to(reader)?;
ObjectPropSet::parse(reader)
};
reader.restore_position(reader_offset)?;
prop_set
}
FileNodeDataRef::ElementList(_) => Err(ErrorKind::MalformedOneStoreData(
"Expected a single element (reading PropertySet)".into(),
@@ -539,7 +551,7 @@ pub struct RootObjectReference3FND {
pub struct RevisionRoleDeclarationFND {
pub rid: ExGuid,
/// "should be 0x01"
revision_role: u32,
pub revision_role: u32,
}
#[derive(Debug, Clone, Parse)]
@@ -564,7 +576,7 @@ impl Parse for StringInStorageBuffer {
let characer_count = reader.get_u32()? as usize;
let string_size = characer_count * 2; // 2 bytes per character
let data = reader.read(string_size)?;
let data = data.utf16_to_string()?;
let data = (&data as &[u8]).utf16_to_string()?;
Ok(Self {
cch: characer_count,
data,
@@ -654,10 +666,14 @@ impl ParseWithRef for ObjectInfoDependencyOverridesFND {
fn parse(reader: parser_utils::Reader, obj_ref: &FileNodeDataRef) -> Result<Self> {
if let FileNodeDataRef::SingleElement(obj_ref) = obj_ref {
if !obj_ref.is_fcr_nil() {
let data = ObjectInfoDependencyOverrideData::parse(
&mut obj_ref.resolve_to_reader(reader)?,
)?;
Ok(Self { data })
let reader_offset = reader.save_position();
let data = {
obj_ref.seek_reader_to(reader)?;
ObjectInfoDependencyOverrideData::parse(reader)
};
reader.restore_position(reader_offset)?;
Ok(Self { data: data? })
} else {
Ok(Self {
data: ObjectInfoDependencyOverrideData::parse(reader)?,
@@ -705,14 +721,15 @@ pub struct FileData(pub FileBlob);
impl Debug for FileData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "FileData(size={:} KiB)", self.0.as_ref().len() / 1024)
write!(f, "FileData(size={:} KiB)", self.0.len() / 1024)
}
}
impl ParseWithCount for FileData {
fn parse(reader: parser_utils::Reader, size: usize) -> Result<Self> {
let data = reader.read(size)?.to_vec();
Ok(FileData(data.into()))
let data_ref = FileBlob::new(Box::new(reader.as_data_ref(size)?), size);
reader.advance(size as u64)?;
Ok(FileData(data_ref))
}
}
@@ -727,9 +744,15 @@ impl ParseWithRef for FileDataStoreObjectReferenceFND {
fn parse(reader: parser_utils::Reader, data_ref: &FileNodeDataRef) -> Result<Self> {
let guid = Guid::parse(reader)?;
if let FileNodeDataRef::SingleElement(data_ref) = data_ref {
let mut reader = data_ref.resolve_to_reader(reader)?;
let reader_offset = reader.save_position();
let target = {
data_ref.seek_reader_to(reader)?;
FileDataStoreObject::parse(reader)
};
reader.restore_position(reader_offset)?;
Ok(Self {
target: FileDataStoreObject::parse(&mut reader)?,
target: target?,
guid,
})
} else {
@@ -945,7 +968,7 @@ pub struct UnknownNode {}
impl ParseWithCount for UnknownNode {
fn parse(reader: Reader, size: usize) -> Result<Self> {
reader.advance(size)?;
reader.advance(size as u64)?;
Ok(UnknownNode {})
}
}
@@ -20,9 +20,9 @@ impl FileNodeList {
let mut next_fragment_ref =
builder.add_fragment(FileNodeListFragment::parse(reader, context, size)?)?;
while !next_fragment_ref.is_fcr_nil() && !next_fragment_ref.is_fcr_zero() {
let mut reader = next_fragment_ref.resolve_to_reader(reader)?;
next_fragment_ref.seek_reader_to(reader)?;
let fragment =
FileNodeListFragment::parse(&mut reader, context, next_fragment_ref.cb as usize)?;
FileNodeListFragment::parse(reader, context, next_fragment_ref.cb as usize)?;
next_fragment_ref = builder.add_fragment(fragment)?;
}
Ok(Self {
@@ -49,13 +49,13 @@ impl FileNodeListFragment {
file_nodes.push(file_node);
}
assert_eq!(remaining_0 - reader.remaining(), file_node_size);
assert_eq!(remaining_0 - reader.remaining(), file_node_size as u64);
}
context.update_remaining_nodes_in_fragment(&header, maximum_node_count);
let padding_length = size - 36 - file_node_size;
reader.advance(padding_length)?;
reader.advance(padding_length as u64)?;
let next_fragment = FileChunkReference64x32::parse(reader)?;
@@ -6,7 +6,7 @@ use crate::{
},
shared::exguid::ExGuid,
};
use parser_utils::{errors::Result, log};
use parser_utils::errors::Result;
use std::fmt::Debug;
use std::rc::Rc;
@@ -73,8 +73,9 @@ impl ObjectGroupList {
if matches!(item, FileNodeData::ObjectGroupEndFND) {
break;
} else if let FileNodeData::DataSignatureGroupDefinitionFND(_) = item {
// Marks the end of a signature block. Ignored.
// See https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/0fa4c886-011a-4c19-9651-9a69e43a19c6
iterator.next();
log!("Ignoring DataSignatureGroupDefinitionFND");
} else if let Some(object) = Object::try_parse(iterator, &parse_context)? {
objects.push(Rc::new(object));
} else {
@@ -60,8 +60,15 @@ impl RevisionManifestList {
let revision = revisions_map.get(&data.base.rid);
if let Some(_revision) = revision {
iterator.next();
// TODO: Find a test .one file that uses this and implement:
log_warn!("TO-DO: Apply the new role and context to the revision");
// According to MS-ONESTORE 2.1.12, revision_role *should* always be 0x1
if data.base.revision_role != 0x1 {
// TODO: Find a test .one file that uses this and implement:
log_warn!(
"TO-DO: Apply the new role and context to the revision (role {:x})",
data.base.revision_role
);
}
} else {
return Err(
ErrorKind::MalformedOneStoreData("RevisionRoleAndContextDeclarationFND points to a non-existent revision".into()).into()
@@ -77,8 +77,8 @@ impl Parse for OneStoreFile {
let mut free_chunk_list = Vec::new();
let mut free_chunk_ref = header.fcr_free_chunk_list.clone();
while !free_chunk_ref.is_fcr_nil() && !free_chunk_ref.is_fcr_zero() {
let mut reader = free_chunk_ref.resolve_to_reader(reader)?;
let fragment = FreeChunkListFragment::parse(&mut reader, free_chunk_ref.cb.into())?;
free_chunk_ref.seek_reader_to(reader)?;
let fragment = FreeChunkListFragment::parse(reader, free_chunk_ref.cb.into())?;
free_chunk_ref = fragment.fcr_next_chunk.clone();
free_chunk_list.push(fragment);
}
@@ -86,10 +86,9 @@ impl Parse for OneStoreFile {
let mut transaction_log = Vec::new();
let mut transaction_log_ref = header.fcr_transaction_log.clone();
loop {
let mut reader = transaction_log_ref.resolve_to_reader(reader)?;
transaction_log_ref.seek_reader_to(reader)?;
let fragment =
TransactionLogFragment::parse(&mut reader, transaction_log_ref.cb as usize)?;
let fragment = TransactionLogFragment::parse(reader, transaction_log_ref.cb as usize)?;
transaction_log_ref = fragment.next_fragment.clone();
transaction_log.push(fragment);
@@ -104,9 +103,9 @@ impl Parse for OneStoreFile {
let mut hashed_chunk_list = Vec::new();
let mut hash_chunk_ref = header.fcr_hashed_chunk_list.clone();
while !hash_chunk_ref.is_fcr_nil() && !hash_chunk_ref.is_fcr_zero() {
let mut reader = hash_chunk_ref.resolve_to_reader(reader)?;
hash_chunk_ref.seek_reader_to(reader)?;
let fragment = FileNodeListFragment::parse(
&mut reader,
reader,
&mut parse_context,
hash_chunk_ref.cb as usize,
)?;
@@ -117,12 +116,8 @@ impl Parse for OneStoreFile {
let file_node_list_root = &header.fcr_file_node_list_root;
let raw_file_node_list =
if !file_node_list_root.is_fcr_nil() && !file_node_list_root.is_fcr_zero() {
let mut reader = file_node_list_root.resolve_to_reader(reader)?;
FileNodeList::parse(
&mut reader,
&mut parse_context,
file_node_list_root.cb as usize,
)?
file_node_list_root.seek_reader_to(reader)?;
FileNodeList::parse(reader, &mut parse_context, file_node_list_root.cb as usize)?
} else {
FileNodeList::default()
};
@@ -13,6 +13,7 @@ pub(crate) struct Data {
pub(crate) offset_from_parent_vert: Option<f32>,
pub(crate) last_modified: Option<Time>,
pub(crate) ink_data: Option<ExGuid>,
pub(crate) children: Option<Vec<ExGuid>>,
pub(crate) ink_scaling_x: Option<f32>,
pub(crate) ink_scaling_y: Option<f32>,
}
@@ -26,14 +27,16 @@ pub(crate) fn parse(object: &Object) -> Result<Data> {
let offset_from_parent_horiz = simple::parse_f32(PropertyType::OffsetFromParentHoriz, object)?;
let offset_from_parent_vert = simple::parse_f32(PropertyType::OffsetFromParentVert, object)?;
let ink_data = ObjectReference::parse(PropertyType::InkData, object)?;
let children = ObjectReference::parse_vec(PropertyType::ContentChildNodes, object)?;
let ink_scaling_x = simple::parse_f32(PropertyType::InkScalingX, object)?;
let ink_scaling_y = simple::parse_f32(PropertyType::InkScalingX, object)?;
let ink_scaling_y = simple::parse_f32(PropertyType::InkScalingY, object)?;
let data = Data {
offset_from_parent_horiz,
offset_from_parent_vert,
last_modified,
ink_data,
children,
ink_scaling_x,
ink_scaling_y,
};
@@ -11,7 +11,7 @@ use parser_utils::errors::{ErrorKind, Result};
/// See [\[MS-ONE\] 2.2.32].
///
/// [\[MS-ONE\] 2.2.32]: https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-one/a665b5ad-ff40-4c0c-9e42-4b707254dc3f
#[derive(Clone, PartialEq, PartialOrd, Debug)]
#[derive(Clone, PartialEq, Debug)]
pub struct EmbeddedFile {
pub(crate) filename: String,
pub(crate) file_type: FileType,
@@ -46,8 +46,8 @@ impl EmbeddedFile {
}
/// The file's binary data.
pub fn data(&self) -> &[u8] {
self.data.as_ref()
pub fn data(&self) -> Result<Vec<u8>> {
self.data.load()
}
/// The max width of the embedded file's icon in half-inch increments.
@@ -1,5 +1,3 @@
use std::rc::Rc;
use crate::one::property::layout_alignment::LayoutAlignment;
use crate::one::property_set::{image_node, picture_container};
use crate::onenote::iframe::{IFrame, parse_iframe};
@@ -14,7 +12,7 @@ use parser_utils::errors::{ErrorKind, Result};
/// See [\[MS-ONE\] 2.2.24].
///
/// [\[MS-ONE\] 2.2.24]: https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-one/b7bb4d1a-2a57-4819-9eb4-5a2ce8cf210f
#[derive(Clone, PartialEq, PartialOrd, Debug)]
#[derive(Clone, PartialEq, Debug)]
pub struct Image {
pub(crate) data: Option<FileBlob>,
pub(crate) extension: Option<String>,
@@ -54,8 +52,8 @@ impl Image {
/// The image's binary data.
///
/// If `None` this means that the image data hasn't been uploaded yet.
pub fn data(&self) -> Option<Rc<Vec<u8>>> {
self.data.as_ref().map(|data| data.0.clone())
pub fn data(&self) -> Result<Option<Vec<u8>>> {
self.data.as_ref().map(|data| data.load()).transpose()
}
/// The image's file extension.
@@ -9,17 +9,34 @@ use parser_utils::log_warn;
/// An ink object.
#[derive(Clone, Debug)]
pub struct Ink {
pub(crate) ink_strokes: Vec<InkStroke>,
pub(crate) content: InkContent,
pub(crate) bounding_box: Option<InkBoundingBox>,
pub(crate) offset_horizontal: Option<f32>,
pub(crate) offset_vertical: Option<f32>,
}
#[derive(Clone, Debug)]
pub enum InkContent {
InkGroup(Vec<Ink>),
Strokes(Vec<InkStroke>),
}
impl Ink {
/// The ink strokes contained in this ink object.
pub fn ink_strokes(&self) -> &[InkStroke] {
&self.ink_strokes
match &self.content {
InkContent::InkGroup(_ink) => &[],
InkContent::Strokes(strokes) => strokes,
}
}
/// Groups contained within this group
pub fn child_groups(&self) -> &[Ink] {
match &self.content {
InkContent::InkGroup(ink) => ink,
InkContent::Strokes(_strokes) => &[],
}
}
/// The ink object's bounding box.
@@ -163,24 +180,62 @@ impl InkBoundingBox {
width: self.width * factor,
}
}
fn union(&self, other: Option<InkBoundingBox>) -> InkBoundingBox {
let Some(other) = other else {
return *self;
};
let x = self.x.min(other.x);
let y = self.y.min(other.y);
let x2 = (self.x + self.width).max(other.x + other.width);
let y2 = (self.y + self.height).max(other.y + other.height);
InkBoundingBox {
x,
y,
height: y2 - y,
width: x2 - x,
}
}
}
pub(crate) fn parse_ink(ink_container_id: ExGuid, space: ObjectSpaceRef) -> Result<Ink> {
parse_ink_rec(ink_container_id, space, 0)
}
fn parse_ink_rec(ink_container_id: ExGuid, space: ObjectSpaceRef, depth: u32) -> Result<Ink> {
// Cut maximum recursion depth at 16 to guard against cycles (e.g. if an ink node is declared
// to recursively contain itself). An explicit error should be easier to debug than the
// stack overflow that would otherwise occur.
if depth > 16 {
return Err(
parser_error!(MalformedOneStoreData, "Maximum ink nesting depth exceeded").into(),
);
}
let container_object = space
.get_object(ink_container_id)
.ok_or_else(|| ErrorKind::MalformedOneNoteData("ink container is missing".into()))?;
let container = ink_container::parse(&container_object)?;
let ink_data_id = match container.ink_data {
Some(id) => id,
None => {
let Some(ink_data_id) = container.ink_data else {
let Some(children) = container.children else {
return Ok(Ink {
ink_strokes: vec![],
content: InkContent::Strokes(vec![]),
bounding_box: None,
offset_horizontal: container.offset_from_parent_horiz,
offset_vertical: container.offset_from_parent_vert,
offset_horizontal: None,
offset_vertical: None,
});
}
};
let (bbox, content) = parse_ink_group(children, space, depth)?;
return Ok(Ink {
bounding_box: bbox,
offset_horizontal: container.offset_from_parent_horiz,
offset_vertical: container.offset_from_parent_vert,
content,
});
};
let (ink_strokes, bounding_box) = parse_ink_data(
@@ -191,13 +246,36 @@ pub(crate) fn parse_ink(ink_container_id: ExGuid, space: ObjectSpaceRef) -> Resu
)?;
Ok(Ink {
ink_strokes,
content: InkContent::Strokes(ink_strokes),
bounding_box,
offset_horizontal: container.offset_from_parent_horiz,
offset_vertical: container.offset_from_parent_vert,
})
}
fn parse_ink_group(
children: Vec<ExGuid>,
space: ObjectSpaceRef,
recursion_depth: u32,
) -> Result<(Option<InkBoundingBox>, InkContent)> {
let mut ink_contents = vec![];
let children = children
.into_iter()
.map(|group_id| parse_ink_rec(group_id, space.clone(), recursion_depth + 1));
let mut bbox = None;
for child in children {
let child = child?;
if let Some(child_bbox) = &child.bounding_box {
bbox = Some(child_bbox.union(bbox));
}
ink_contents.push(child);
}
Ok((bbox, InkContent::InkGroup(ink_contents)))
}
pub(crate) fn parse_ink_data(
ink_data_id: ExGuid,
space: ObjectSpaceRef,
@@ -1,6 +1,8 @@
use std::rc::Rc;
use crate::onenote::notebook::Notebook;
use crate::onenote::section::{Section, SectionEntry, SectionGroup};
use crate::onestore::{OneStoreType, parse_onestore};
use crate::onestore::{OneStore, OneStoreType, parse_onestore};
use parser_utils::errors::{ErrorKind, Result};
use parser_utils::{fs_driver, log, reader::Reader};
@@ -37,8 +39,8 @@ impl Parser {
/// sections from the folder that the table of contents file is in.
pub fn parse_notebook(&mut self, path: String) -> Result<Notebook> {
log!("Parsing notebook: {:?}", path);
let data = fs_driver().read_file(&path)?;
let store = parse_onestore(&mut Reader::new(&data))?;
let data = fs_driver().open_file(&path)?;
let store = parse_onestore(&mut Reader::try_from(data)?)?;
if store.get_type() != OneStoreType::TableOfContents {
return Err(ErrorKind::NotATocFile { file: path }.into());
@@ -53,7 +55,7 @@ impl Parser {
.map(|p| {
let is_dir = fs_driver().is_directory(&p)?;
if !is_dir {
self.parse_section(p).map(SectionEntry::Section)
self.parse_section(&p).map(SectionEntry::Section)
} else {
self.parse_section_group(p).map(SectionEntry::SectionGroup)
}
@@ -67,17 +69,28 @@ impl Parser {
///
/// The `path` argument must point to a `.one` file that contains a
/// OneNote section.
pub fn parse_section(&mut self, path: String) -> Result<Section> {
pub fn parse_section(&mut self, path: &str) -> Result<Section> {
log!("Parsing section: {:?}", path);
let data = fs_driver().read_file(path.as_str())?;
self.parse_section_from_data(&data, &path)
let file = fs_driver().open_file(path)?;
self.parse_section_from_reader(Reader::try_from(file)?, path)
}
/// Parses low-level OneStore data. Exported for debugging purposes.
pub fn parse_onestore_raw(&mut self, path: &str) -> Result<Rc<dyn OneStore>> {
log!("Parsing OneStore: {:?}", path);
let file = fs_driver().open_file(path)?;
parse_onestore(&mut Reader::try_from(file)?)
}
/// Parse a OneNote section file from a byte array.
/// The [path] is used to provide debugging information and determine
/// the name of the section file.
pub fn parse_section_from_data(&mut self, data: &[u8], path: &str) -> Result<Section> {
let store = parse_onestore(&mut Reader::new(data))?;
self.parse_section_from_reader(Reader::from(data), path)
}
fn parse_section_from_reader(&mut self, mut reader: Reader, path: &str) -> Result<Section> {
let store = parse_onestore(&mut reader)?;
if store.get_type() != OneStoreType::Section {
return Err(ErrorKind::NotASectionFile {
@@ -5,7 +5,7 @@ use crate::one::property::color_ref::ColorRef;
use crate::one::property::layout_alignment::LayoutAlignment;
use crate::one::property::paragraph_alignment::ParagraphAlignment;
use crate::one::property_set::{embedded_ink_container, paragraph_style_object, rich_text_node};
use crate::onenote::ink::{Ink, InkBoundingBox, parse_ink_data};
use crate::onenote::ink::{Ink, InkBoundingBox, InkContent, parse_ink_data};
use crate::onenote::note_tag::{NoteTag, parse_note_tags};
use crate::onenote::text_region::TextRegion;
use crate::onestore::object::Object;
@@ -423,32 +423,45 @@ pub(crate) fn parse_rich_text(content_id: ExGuid, space: ObjectSpaceRef) -> Resu
let embedded_objects: Vec<_> = objects
.into_iter()
.enumerate()
.map(|(i, (object_type, embedded_data))| match object_type {
Some(INK_END_OF_LINE_BLOB) => {
objects_without_ref += 1;
Ok(Some(EmbeddedObject::InkLineBreak))
}
Some(INK_SPACE_BLOB) => {
objects_without_ref += 1;
parse_embedded_ink_space(embedded_data)
.map(|space| Some(EmbeddedObject::InkSpace(space)))
}
None => {
if !data.text_run_data_object.is_empty() {
return parse_embedded_ink_data(
data.text_run_data_object[i - objects_without_ref],
space.clone(),
embedded_data,
)
.map(|container| Some(EmbeddedObject::Ink(container)));
}
.map(|(i, (object_type, embedded_data))| {
let i = i - objects_without_ref;
Ok(None)
let object_ref = data.text_run_data_object.get(i);
let is_valid_ref = object_ref
.map(|object_ref| space.get_object(*object_ref).is_some())
.unwrap_or(true);
// Based on sample .one files, spaces and EOL blobs either:
// - Have an invalid associated object reference (is_valid_ref = false)
// - Have no associated object reference (is_valid_ref = true)
//
// In the first case, the object reference will be skipped automatically.
// In the second, we need to adjust so that the references for subsequent
// objects aren't skipped.
if let Some(object_type) = object_type
&& is_valid_ref
&& (object_type == INK_END_OF_LINE_BLOB || object_type == INK_SPACE_BLOB)
{
objects_without_ref += 1;
}
match object_type {
Some(INK_END_OF_LINE_BLOB) => Ok(Some(EmbeddedObject::InkLineBreak)),
Some(INK_SPACE_BLOB) => parse_embedded_ink_space(embedded_data)
.map(|space| Some(EmbeddedObject::InkSpace(space))),
None => {
if let Some(object_ref) = object_ref {
return parse_embedded_ink_data(*object_ref, space.clone(), embedded_data)
.map(|container| Some(EmbeddedObject::Ink(container)));
}
Ok(None)
}
Some(v) => Err(ErrorKind::MalformedOneNoteFileData(
format!("unknown embedded object type: {:x}", v).into(),
)
.into()),
}
Some(v) => Err(ErrorKind::MalformedOneNoteFileData(
format!("unknown embedded object type: {:x}", v).into(),
)
.into()),
})
.collect::<Result<Vec<_>>>()?
.into_iter()
@@ -513,7 +526,7 @@ fn parse_embedded_ink_data(
let data = EmbeddedInkContainer {
ink: Ink {
ink_strokes: strokes,
content: InkContent::Strokes(strokes),
bounding_box: bb,
offset_horizontal: data.offset_horiz,
offset_vertical: data.offset_vert,
@@ -3,7 +3,7 @@
//!
//! Provides interfaces that are implemented by the different OneStore parsers.
use std::rc::Rc;
use std::{io::Seek, io::SeekFrom, rc::Rc};
use crate::{
fsshttpb_onestore::{self, packaging::OneStorePackaging},
@@ -21,7 +21,7 @@ pub mod mapping_table;
pub mod object;
pub mod object_space;
pub trait OneStore {
pub trait OneStore: std::fmt::Debug {
fn get_type(&self) -> OneStoreType;
fn data_root(&self) -> ObjectSpaceRef;
/// Fetches the object space that is parent to the object identified by the
@@ -39,16 +39,16 @@ pub fn parse_onestore<'a>(reader: &mut Reader<'a>) -> Result<Rc<dyn OneStore>> {
// Try parsing as the standard format first.
// Clone the reader to save the original offset. When retrying parsing with
// a different format, parsing should start from the same location.
let mut reader_1 = reader.clone();
let onestore_local = OneStoreFile::parse(&mut reader_1);
reader.seek(SeekFrom::Start(0))?;
let onestore_local = OneStoreFile::parse(reader);
match onestore_local {
Ok(onestore) => Ok(Rc::new(onestore)),
Err(Error {
kind: ErrorKind::NotLocalOneStore(_),
}) => {
let mut reader_2 = reader.clone();
let packaging = OneStorePackaging::parse(&mut reader_2)?;
reader.seek(SeekFrom::Start(0))?;
let packaging = OneStorePackaging::parse(reader)?;
let store = fsshttpb_onestore::parse_store(&packaging)?;
Ok(Rc::new(store))
}
@@ -22,7 +22,7 @@ impl ObjectFileData for FileBlob {
/// See [\[MS-ONESTORE\] 2.1.5](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/ce60b62f-82e5-401a-bf2c-3255457732ad)
#[derive(Clone)]
pub(crate) struct Object {
pub struct Object {
pub(crate) context_id: ExGuid,
pub(crate) jc_id: JcId,
@@ -51,11 +51,11 @@ impl std::fmt::Debug for Object {
}
impl Object {
pub fn id(&self) -> JcId {
pub(crate) fn id(&self) -> JcId {
self.jc_id
}
pub fn props(&self) -> &ObjectPropSet {
pub(crate) fn props(&self) -> &ObjectPropSet {
&self.props
}
@@ -1,5 +1,5 @@
use parser_utils::Reader;
use parser_utils::errors::{ErrorKind, Result};
use parser_utils::errors::Result;
/// A compact unsigned 64-bit integer.
///
@@ -21,94 +21,63 @@ impl CompactU64 {
}
pub(crate) fn parse(reader: Reader) -> Result<CompactU64> {
let bytes = reader.bytes();
let first_byte = bytes.first().copied().ok_or(ErrorKind::UnexpectedEof(
"Reading CompactU64 (first byte)".into(),
))?;
let first_byte = reader.get_u8()?;
if first_byte == 0 {
reader.advance(1)?;
return Ok(CompactU64(0));
}
if first_byte & 1 != 0 {
return Ok(CompactU64((reader.get_u8()? >> 1) as u64));
return Ok(CompactU64((first_byte >> 1) as u64));
}
if first_byte & 2 != 0 {
return Ok(CompactU64((reader.get_u16()? >> 2) as u64));
let second_byte = reader.get_u8()?;
let value = u16::from_le_bytes([first_byte, second_byte]);
return Ok(CompactU64((value >> 2) as u64));
}
if first_byte & 4 != 0 {
if reader.remaining() < 3 {
return Err(ErrorKind::UnexpectedEof("Reading CompactU64".into()).into());
}
let value = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], 0]);
reader.advance(3)?;
let bytes = reader.read(2)?;
let value = u32::from_le_bytes([first_byte, bytes[0], bytes[1], 0]);
return Ok(CompactU64((value >> 3) as u64));
}
if first_byte & 8 != 0 {
if reader.remaining() < 4 {
return Err(ErrorKind::UnexpectedEof("CompactU64".into()).into());
}
let value = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
reader.advance(4)?;
let bytes = reader.read(3)?;
let value = u32::from_le_bytes([first_byte, bytes[0], bytes[1], bytes[2]]);
return Ok(CompactU64((value >> 4) as u64));
}
if first_byte & 16 != 0 {
if reader.remaining() < 5 {
return Err(ErrorKind::UnexpectedEof("CompactU64".into()).into());
}
let bytes = reader.read(4)?;
let value =
u64::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], 0, 0, 0]);
reader.advance(5)?;
u64::from_le_bytes([first_byte, bytes[0], bytes[1], bytes[2], bytes[3], 0, 0, 0]);
return Ok(CompactU64(value >> 5));
}
if first_byte & 32 != 0 {
if reader.remaining() < 6 {
return Err(ErrorKind::UnexpectedEof("CompactU64".into()).into());
}
let bytes = reader.read(5)?;
let value = u64::from_le_bytes([
first_byte, bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], 0, 0,
first_byte, bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], 0, 0,
]);
reader.advance(6)?;
return Ok(CompactU64(value >> 6));
}
if first_byte & 64 != 0 {
if reader.remaining() < 7 {
return Err(ErrorKind::UnexpectedEof("CompactU64".into()).into());
}
let bytes = reader.read(6)?;
let value = u64::from_le_bytes([
first_byte, bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], 0,
first_byte, bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], 0,
]);
reader.advance(7)?;
return Ok(CompactU64(value >> 7));
}
if first_byte & 128 != 0 {
reader.advance(1)?;
return Ok(CompactU64(reader.get_u64()?));
}
@@ -122,76 +91,42 @@ mod test {
use parser_utils::reader::Reader;
#[test]
fn test_zero() {
assert_eq!(
CompactU64::parse(&mut Reader::new(&[0u8])).unwrap().value(),
0
);
}
#[test]
fn test_7_bit() {
assert_eq!(
CompactU64::parse(&mut Reader::new(&[0u8])).unwrap().value(),
0
);
}
#[test]
fn test_14_bit() {
assert_eq!(
CompactU64::parse(&mut Reader::new(&[0u8])).unwrap().value(),
0
);
}
#[test]
fn test_21_bit() {
assert_eq!(
CompactU64::parse(&mut Reader::new(&[0xd4u8, 0x8b, 0x10]))
.unwrap()
.value(),
135546
);
}
#[test]
fn test_28_bit() {
assert_eq!(
CompactU64::parse(&mut Reader::new(&[0u8])).unwrap().value(),
0
);
}
#[test]
fn test_35_bit() {
assert_eq!(
CompactU64::parse(&mut Reader::new(&[0u8])).unwrap().value(),
0
);
}
#[test]
fn test_42_bit() {
assert_eq!(
CompactU64::parse(&mut Reader::new(&[0u8])).unwrap().value(),
0
);
}
#[test]
fn test_49_bit() {
assert_eq!(
CompactU64::parse(&mut Reader::new(&[0u8])).unwrap().value(),
0
);
}
#[test]
fn test_64_bit() {
assert_eq!(
CompactU64::parse(&mut Reader::new(&[0u8])).unwrap().value(),
0
);
fn should_parse_from_reader() {
for (input, expected) in [
// Zero case
(vec![0u8], 0),
// 7-bit case
(vec![0xF], 7),
// 14-bit case
(vec![0xFE, 0x0], 0x3F),
// 21-bit case
(vec![0xd4, 0x8b, 0x10], 135546),
// 28-bit case
(vec![0xd8, 0x8b, 0x10, 0x10], 0x10108bd),
// 35-bit case
(vec![0x10, 0x8b, 0x10, 0x13, 0x10], 0x1013108b0 >> 1),
// 42-bit case
(vec![0x20, 0x8b, 0x10, 0x13, 0x10, 0x10], 0x101013108b0 >> 2),
// 49-bit case
(
vec![0x40, 0x8b, 0x10, 0x13, 0x10, 0x10, 0x14],
0x14101013108b0 >> 3,
),
// 64-bit case
(
vec![0x80, 0x8b, 0x10, 0x13, 0x10, 0x10, 0x14, 0x10, 0x14],
0x141014101013108b,
),
] {
let test_label = format!("{input:?} should parse to 0x{expected:0x}");
assert_eq!(
CompactU64::parse(&mut Reader::from(&input as &[u8]))
.expect(&test_label)
.value(),
expected,
"{}",
test_label,
);
}
}
}
@@ -1,30 +1,67 @@
use std::fmt::Debug;
use std::rc::Rc;
#[derive(Clone, Default, Eq, PartialEq, PartialOrd)]
pub struct FileBlob(pub Rc<Vec<u8>>);
use parser_utils::Result;
use parser_utils::reader::ReaderDataRef;
#[derive(Clone)]
pub struct FileBlob {
// File blobs can be huge. Lazy-load the data and only keep it as long
// as necessary.
loader: Rc<dyn FileDataLoader>,
size: usize,
}
impl PartialEq for FileBlob {
fn eq(&self, other: &Self) -> bool {
self.size == other.size && Rc::ptr_eq(&self.loader, &other.loader)
}
}
pub trait FileDataLoader {
fn load(&self) -> Result<Vec<u8>>;
}
impl FileDataLoader for Vec<u8> {
fn load(&self) -> Result<Vec<u8>> {
Ok(self.clone())
}
}
impl FileDataLoader for ReaderDataRef {
fn load(&self) -> Result<Vec<u8>> {
self.bytes()
}
}
impl Default for FileBlob {
fn default() -> Self {
Self {
loader: Rc::new(vec![]),
size: 0,
}
}
}
impl Debug for FileBlob {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let len = self.0.len();
write!(f, "FileBlob [ {:?} KiB ]", len / 1024)
write!(f, "FileBlob [ {:?} KiB ]", self.size / 1024)
}
}
impl FileBlob {
pub fn as_ref(&self) -> &[u8] {
&self.0
pub fn new(on_load: Box<dyn FileDataLoader>, size: usize) -> Self {
Self {
loader: on_load.into(),
size,
}
}
}
impl From<Vec<u8>> for FileBlob {
fn from(value: Vec<u8>) -> Self {
Self(Rc::new(value))
pub fn len(&self) -> usize {
self.size
}
}
impl From<&[u8]> for FileBlob {
fn from(value: &[u8]) -> Self {
Self(Rc::new(Vec::from(value)))
pub fn load(&self) -> Result<Vec<u8>> {
self.loader.load()
}
}
@@ -1,6 +1,8 @@
use crate::one::property::PropertyType;
use crate::shared::property::{PropertyId, PropertyValue};
use parser_utils::Reader;
use parser_utils::Utf16ToString;
use parser_utils::debug::DebugOutput;
use parser_utils::errors::Result;
use std::collections::HashMap;
use std::fmt::Debug;
@@ -25,12 +27,41 @@ pub(crate) struct PropertySet {
impl Debug for PropertySet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn format_value(value: &PropertyValue) -> String {
match value {
PropertyValue::Vec(vec) => {
// Vec() property values are used to represent strings. Try creating a string representation for
// debugging purposes:
let s = vec
.as_slice()
// OneNote file strings are usually UTF-16
.utf16_to_string()
.unwrap_or("".to_string());
// Heuristic: If the text contains at least one ASCII letter/space character, it's probably a string.
// This will miss some non-ASCII strings and incorrectly print some non-string vecs.
let is_probably_string = !s.is_empty()
&& s.chars()
.any(|c| c.is_ascii_whitespace() || c.is_ascii_alphanumeric());
if is_probably_string {
format!("{:?} ({:?})", s, vec)
} else {
format!("{:?}", vec)
}
}
// Use the default compact representation of the value.
// This keeps potentially-long property values on a single line when producing
// multi-line debug output, which is usually more readable.
_ => format!("{:?}", value),
}
}
let mut debug_map = f.debug_map();
for (key, (_, value)) in &self.values {
let formatted_key = format!("{:#0x}", key);
// Use the default compact representation of the value
let formatted_value = format!("{:?}", value);
debug_map.entry(&formatted_key, &formatted_value);
let formatted_value = format_value(value);
debug_map.entry(&formatted_key, &DebugOutput::from(formatted_value.as_str()));
}
debug_map.finish()
}
@@ -169,7 +169,7 @@ impl PropertyValue {
fn parse_vec(reader: Reader) -> Result<PropertyValue> {
let size = reader.get_u32()?;
let data = reader.read(size as usize)?.to_vec();
let data = reader.read(size as usize)?;
Ok(PropertyValue::Vec(data))
}
@@ -1,66 +0,0 @@
use itertools::Itertools;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Display;
pub(crate) struct AttributeSet(HashMap<&'static str, String>);
#[allow(dead_code)]
impl AttributeSet {
pub(crate) fn new() -> Self {
Self(HashMap::new())
}
pub(crate) fn set(&mut self, attribute: &'static str, value: String) {
self.0.insert(attribute, value);
}
}
impl Display for AttributeSet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
self.0
.iter()
.sorted_by(|(a, _), (b, _)| Ord::cmp(a, b))
.map(|(attr, value)| attr.to_string() + "=\"" + value + "\"")
.join(" ")
)
}
}
#[derive(Debug, Clone)]
pub(crate) struct StyleSet(HashMap<&'static str, String>);
#[allow(dead_code)]
impl StyleSet {
pub(crate) fn new() -> Self {
Self(HashMap::new())
}
pub(crate) fn set(&mut self, prop: &'static str, value: String) {
self.0.insert(prop, value);
}
pub(crate) fn extend(&mut self, other: Self) {
self.0.extend(other.0)
}
pub(crate) fn len(&self) -> usize {
self.0.len()
}
}
impl Display for StyleSet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
self.0
.iter()
.sorted_by(|(a, _), (b, _)| Ord::cmp(a, b))
.map(|(attr, value)| attr.to_string() + ": " + value + ";")
.join(" ")
)
}
}
@@ -47,7 +47,7 @@ pub fn convert(path: &str, output_dir: &str, base_path: &str) -> Result<()> {
return Ok(());
}
let section = Parser::new().parse_section(path.to_owned())?;
let section = Parser::new().parse_section(path)?;
let section_output_dir = fs_driver().get_output_path(base_path, output_dir, path);
section::Renderer::new().render(&section, section_output_dir.to_owned())?;
@@ -1,4 +1,7 @@
use crate::{page::Renderer, utils::StyleSet};
use crate::{
page::Renderer,
utils::{StyleSet, html_entities},
};
use color_eyre::Result;
use parser::contents::EmbeddedFile;
use parser::property::embedded_file::FileType;
@@ -11,7 +14,7 @@ impl<'a> Renderer<'a> {
.to_unique_safe_filename(&self.output, file.filename())?;
let path = fs_driver().join(&self.output, &filename);
log!("Rendering embedded file: {:?}", path);
fs_driver().write_file(&path, file.data())?;
fs_driver().write_file(&path, &file.data()?)?;
let mut styles = StyleSet::new();
if let Some(offset_x_half_inches) = file.offset_horizontal() {
@@ -35,7 +38,8 @@ impl<'a> Renderer<'a> {
styles.set("line-height", "17px".into());
let style_attr = styles.to_html_attr();
format!("<p {style_attr}><a href=\"{filename}\">{filename}</a></p>")
let escaped_filename = html_entities(&filename);
format!("<p {style_attr}><a href=\"{escaped_filename}\">{escaped_filename}</a></p>")
}
};
@@ -8,7 +8,7 @@ impl<'a> Renderer<'a> {
pub(crate) fn render_image(&mut self, image: &Image) -> Result<String> {
let mut content = String::new();
if let Some(data) = image.data() {
if let Some(data) = image.data()? {
let filename = self.determine_image_filename(image)?;
let path = fs_driver().join(&self.output, &filename);
log!("Rendering image: {:?}", path);
@@ -20,7 +20,7 @@ impl<'a> Renderer<'a> {
attrs.set("src", filename);
if let Some(text) = image.alt_text() {
attrs.set("alt", text.to_string().replace('"', "&quot;"));
attrs.set("alt", text.to_string());
}
if let Some(width) = image.layout_max_width() {
@@ -34,6 +34,11 @@ impl InkBuilder {
}
pub(crate) fn push(&mut self, ink: &Ink, display_bounding_box: Option<&InkBoundingBox>) {
let children = ink.child_groups();
for child in children {
self.push(child, ink.bounding_box().as_ref().or(display_bounding_box));
}
let strokes = ink.ink_strokes();
if strokes.is_empty() {
return;
@@ -37,7 +37,7 @@ impl Display for AttributeSet {
self.0
.iter()
.sorted_by(|(a, _), (b, _)| Ord::cmp(a, b))
.map(|(attr, value)| attr.to_string() + "=\"" + value + "\"")
.map(|(attr, value)| attr.to_string() + "=\"" + &html_entities(value) + "\"")
.join(" ")
)
}
@@ -117,7 +117,7 @@ pub(crate) fn url_encode(url: &str) -> String {
#[cfg(test)]
mod test {
use crate::utils::url_encode;
use crate::utils::{AttributeSet, url_encode};
use super::html_entities;
@@ -139,4 +139,14 @@ mod test {
"http://example.com/%22"
);
}
#[test]
fn should_build_html_attributes() {
let mut attrs = AttributeSet::new();
attrs.set("style", "font-family: \"Multi-word font\";".to_string());
assert_eq!(
format!("{}", attrs),
"style=\"font-family: &quot;Multi-word font&quot;;\""
);
}
}
-2
View File
@@ -45,7 +45,6 @@
"markdown-it": "13.0.2",
"mustache": "4.2.0",
"node-cron": "3.0.3",
"node-os-utils": "1.3.7",
"nodemailer": "6.10.1",
"nodemon": "3.1.11",
"otplib": "12.0.1",
@@ -76,7 +75,6 @@
"@types/markdown-it": "13.0.9",
"@types/mustache": "4.2.6",
"@types/node": "18.19.130",
"@types/node-os-utils": "1.3.4",
"@types/nodemailer": "6.4.21",
"@types/yargs": "17.0.35",
"@types/zxcvbn": "4.4.5",
+12 -12
View File
@@ -6,13 +6,10 @@ describe('metrics', () => {
beforeEach(() => {
clearMetrics();
jest.useFakeTimers({
// Timers need to auto-advance to support node-os-utils.
advanceTimers: true,
});
jest.useFakeTimers();
});
it('should generate a heartbeat message', async () => {
it('should generate a heartbeat message', () => {
const requestId1 = Math.random().toString();
const requestId2 = Math.random().toString();
const requestId3 = Math.random().toString();
@@ -22,18 +19,19 @@ describe('metrics', () => {
onRequestStart(requestId3);
onRequestComplete(requestId2);
jest.advanceTimersByTime(Second);
const regex = /Cpu: (.*?)%; Mem: (.*?) \/ (.*?) MB \((.*?)%\); Req: 3 \/ min; Active req: 2/;
const message = await heartbeatMessage();
const message = heartbeatMessage();
const match = message.match(regex);
expect(match.length).toBe(5);
expect(Number(match[1])).toBeGreaterThan(0);
expect(Number(match[2])).toBeLessThan(Number(match[3]));
expect(Number(match[3])).toBeGreaterThan(0);
});
it('should count the number of requests per minute', async () => {
it('should count the number of requests per minute', () => {
const mockRequest = () => {
const id = uuid.create();
onRequestStart(id);
@@ -44,18 +42,20 @@ describe('metrics', () => {
mockRequest();
jest.advanceTimersByTime(Second);
}
expect(await heartbeatMessage()).toMatch(/Req: 10 \/ min/);
expect(heartbeatMessage()).toMatch(/Req: 10 \/ min/);
jest.advanceTimersByTime(Minute * 15);
expect(await heartbeatMessage()).toMatch(/Req: 0 \/ min/);
expect(heartbeatMessage()).toMatch(/Req: 0 \/ min/);
mockRequest();
expect(await heartbeatMessage()).toMatch(/Req: 1 \/ min/);
jest.advanceTimersByTime(Second);
expect(heartbeatMessage()).toMatch(/Req: 1 \/ min/);
jest.advanceTimersByTime(Minute * 2);
mockRequest();
jest.advanceTimersByTime(Second * 10);
mockRequest();
expect(await heartbeatMessage()).toMatch(/Req: 2 \/ min/);
jest.advanceTimersByTime(Second);
expect(heartbeatMessage()).toMatch(/Req: 2 \/ min/);
});
});
+12 -29
View File
@@ -3,7 +3,7 @@
// Provides metrics about the operating system and server application, and format them in a message
// that can be printed to log.
import { MemUsedInfo, cpu, mem } from 'node-os-utils';
import * as os from 'os';
import { Minute } from './time';
import Logger from '@joplin/utils/Logger';
@@ -53,43 +53,26 @@ export const clearMetrics = () => {
activeRequests_.clear();
};
export const heartbeatMessage = async () => {
const interval = 1000;
const promises: Promise<void>[] = [];
interface Info {
cpu?: number;
memory?: MemUsedInfo;
}
const info: Info = {};
const getCpu = async () => {
info.cpu = await cpu.usage(interval);
};
const getMemory = async () => {
info.memory = await mem.used();
};
promises.push(getCpu());
promises.push(getMemory());
await Promise.all(promises);
export const heartbeatMessage = () => {
const loadAvg = os.loadavg();
const totalMemMb = Math.round(os.totalmem() / (1024 * 1024));
const freeMemMb = Math.round(os.freemem() / (1024 * 1024));
const usedMemMb = totalMemMb - freeMemMb;
const line: string[] = [];
line.push(`Cpu: ${info.cpu}%`);
line.push(`Mem: ${info.memory.usedMemMb} / ${info.memory.totalMemMb} MB (${Math.round((info.memory.usedMemMb / info.memory.totalMemMb) * 100)}%)`);
const cpuCount = os.cpus().length;
const cpuPercent = Math.round((loadAvg[0] / cpuCount) * 100);
line.push(`Cpu: ${cpuPercent}%`);
line.push(`Mem: ${usedMemMb} / ${totalMemMb} MB (${Math.round((usedMemMb / totalMemMb) * 100)}%)`);
line.push(`Req: ${requestsPerMinute()} / min`);
line.push(`Active req: ${activeRequests_.size}`);
return line.join('; ');
};
export const logHeartbeat = async () => {
logger.info(await heartbeatMessage());
export const logHeartbeat = () => {
logger.info(heartbeatMessage());
};
export const onRequestStart = (requestId: string) => {
+3
View File
@@ -261,3 +261,6 @@ llamacpp
bgcolor
bordercolor
togglefullscreen
onestore
macshot
pdate
+2
View File
@@ -38,6 +38,8 @@ describe('git-changelog', () => {
['Update aws-sdk-js-v3 monorepo to v3.215.0', 'aws-sdk-js-v3', 'v3.215.0'],
['Update dependency moment to v2.29.4 (#7087)', 'moment', 'v2.29.4'],
['Update aws (#8106)', 'aws', ''],
['fix(deps): update dependency prosemirror-gapcursor to v1.4.0 (#15069)', 'prosemirror-gapcursor', 'v1.4.0'],
['chore(deps): update dependency webpack-dev-server to v5.2.3 (#15078)', 'webpack-dev-server', 'v5.2.3'],
];
for (const testCase of testCases) {
+3 -3
View File
@@ -145,9 +145,9 @@ export interface RenovateMessage {
export const parseRenovateMessage = (message: string): RenovateMessage => {
const regexes = [
/^Update dependency ([^\s]+) to ([^\s]+)/,
/^Update ([^\s]+) monorepo to ([^\s]+)/,
/^Update ([^\s]+)/,
/^(?:(?:fix|chore)\(deps\): )?[Uu]pdate dependency ([^\s]+) to ([^\s]+)/,
/^(?:(?:fix|chore)\(deps\): )?[Uu]pdate ([^\s]+) monorepo to ([^\s]+)/,
/^(?:(?:fix|chore)\(deps\): )?[Uu]pdate ([^\s]+)/,
];
for (const regex of regexes) {
+3 -3
View File
@@ -8,7 +8,7 @@ msgstr ""
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: \n"
"PO-Revision-Date: 2026-01-09 17:09+0100\n"
"Last-Translator: summoner <summoner@vivaldi.net>\n"
"Last-Translator: summoner <summoner@disroot.org>\n"
"Language-Team: Hungarian <>\n"
"Language: hu_HU\n"
"MIME-Version: 1.0\n"
@@ -1998,7 +1998,7 @@ msgstr "Módosítások elvetése"
#: packages/app-mobile/components/screens/DocumentScanner/DocumentScanner.tsx:166
#: packages/app-mobile/root.tsx:783
msgid "Dismiss"
msgstr "Elvetés"
msgstr "Eltüntetés"
#: packages/app-cli/app/command-geoloc.ts:13
msgid "Displays a geolocation URL for the note."
@@ -2868,7 +2868,7 @@ msgstr "Kényszerített elérési út stílusa"
#: packages/lib/commands/historyForward.ts:6
msgid "Forward"
msgstr "Továbbítás"
msgstr "Előre"
#: packages/app-cli/app/command-import.ts:53
#: packages/app-desktop/gui/ImportScreen.tsx:89
+101 -103
View File
@@ -1,14 +1,15 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR Laurent Cozic
# This file is distributed under the same license as the Joplin-CLI package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
# Previous-Translator: Титан <fignin@ya.ru>"
# Last-Translator: Dmitriy Q <atsip-help@yandex.ru>
#
msgid ""
msgstr ""
"Project-Id-Version: Joplin-CLI 3.2.13\n"
"Report-Msgid-Bugs-To: \n"
"Last-Translator: Arman Saga <asagatbekov@gmail.com>\n"
"POT-Creation-Date: \n"
"PO-Revision-Date: \n"
"Last-Translator: Dmitriy Q <atsip-help@yandex.ru>\n"
"Language-Team: Sergey Segeda <thesermanarm@gmail.com>\n"
"Language: ru_RU\n"
"MIME-Version: 1.0\n"
@@ -16,7 +17,7 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
"X-Generator: Poedit 3.7\n"
"X-Generator: Poedit 3.8\n"
#: packages/app-mobile/components/screens/ConfigScreen/ConfigScreen.tsx:621
msgid "- Camera: to allow taking a picture and attaching it to a note."
@@ -308,7 +309,7 @@ msgstr ""
#: packages/editor/ProseMirror/plugins/imagePlugin.ts:148
msgid "A brief description of the image:"
msgstr ""
msgstr "Краткое описание изображения:"
#: packages/lib/models/settings/builtInMetadata.ts:1993
msgid ""
@@ -336,7 +337,7 @@ msgstr "A5"
#: packages/lib/models/settings/builtInMetadata.ts:1121
msgid "ABC musical notation: Options"
msgstr ""
msgstr "Музыкальная нотация ABC: параметры"
#: packages/app-mobile/components/screens/ConfigScreen/plugins/PluginBox/index.tsx:62
#: packages/app-mobile/components/screens/ConfigScreen/plugins/PluginInfoModal.tsx:240
@@ -432,7 +433,7 @@ msgstr "Добавить текст заметки"
#: packages/editor/ProseMirror/plugins/tablePlugin.ts:31
msgid "Add column"
msgstr ""
msgstr "Добавить столбец"
#: packages/app-mobile/components/buttons/FloatingActionButton.tsx:66
#: packages/app-mobile/components/ComboBox.tsx:103
@@ -449,9 +450,8 @@ msgid "Add recipient:"
msgstr "Добавить получателя:"
#: packages/editor/ProseMirror/plugins/tablePlugin.ts:26
#, fuzzy
msgid "Add row"
msgstr "Добавить новый"
msgstr "Добавить строку"
#: packages/app-mobile/components/TagEditor.tsx:281
msgid "Add tags:"
@@ -591,6 +591,9 @@ msgid ""
"offline or cannot connect to the server.\n"
"Error: %s"
msgstr ""
"Произошла ошибка при отправке ответа. Это может произойти, если приложение "
"находится в оффлайн-режиме или не может подключиться к серверу.\n"
"Ошибка: %s"
#: packages/app-desktop/ElectronAppWrapper.ts:190
msgid "An error occurred: %s"
@@ -807,7 +810,7 @@ msgstr "Бета"
#: packages/app-mobile/components/NoteEditor/commandDeclarations.ts:123
msgid "Block code"
msgstr ""
msgstr "Блок кода"
#: packages/app-desktop/gui/NoteEditor/editorCommandDeclarations.ts:55
#: packages/app-mobile/components/NoteEditor/commandDeclarations.ts:80
@@ -925,9 +928,8 @@ msgid "Cannot change encrypted item"
msgstr "Невозможно изменить зашифрованный элемент"
#: packages/lib/commands/convertNoteToMarkdown.ts:42
#, fuzzy
msgid "Cannot convert read-only item: \"%s\""
msgstr "Невозможно создать новую заметку: %s"
msgstr "Невозможно преобразовать только для чтения элемент: \"%s\""
#: packages/lib/models/Note.ts:622
msgid "Cannot copy note to \"%s\" notebook"
@@ -1086,7 +1088,7 @@ msgstr "Проверка... Пожалуйста, подождите."
#: packages/app-desktop/gui/NoteContentPropertiesDialog.tsx:114
msgid "Chinese/Japanese/Korean characters"
msgstr ""
msgstr "Китайские/японские/корейские иероглифы"
#: packages/app-mobile/components/screens/Note/commands/attachFile.ts:98
msgid "Choose an option"
@@ -1218,9 +1220,8 @@ msgstr "Создать новый блокнот"
#: packages/app-mobile/components/screens/Note/Note.tsx:1758
#: packages/app-mobile/components/screens/NoteRevisionViewer.tsx:225
#, fuzzy
msgid "Collapse title"
msgstr "Крах %s"
msgstr "Свернуть заголовок"
#: packages/app-desktop/gui/Sidebar/listItemComponents/ExpandIcon.tsx:23
msgid "Collapsed"
@@ -1253,7 +1254,7 @@ msgstr "Команда"
#: packages/app-cli/app/command-keymap.ts:30
msgid "COMMAND"
msgstr ""
msgstr "КОММАНДА"
#: packages/app-desktop/plugins/GotoAnything.tsx:783
msgid "Command palette"
@@ -1318,9 +1319,8 @@ msgid "Configuration"
msgstr "Конфигурация"
#: packages/app-cli/app/command-keymap.ts:24
#, fuzzy
msgid "Configured keyboard shortcuts:"
msgstr "Сочетания клавиш"
msgstr "Настроенные сочетания клавиш:"
#: packages/lib/models/settings/builtInMetadata.ts:1296
msgid "Configures the size of scrollbars used in the app."
@@ -1396,9 +1396,8 @@ msgid "Convert it"
msgstr "Преобразовать в заметку"
#: packages/lib/commands/convertNoteToMarkdown.ts:18
#, fuzzy
msgid "Convert to Markdown"
msgstr "Преобразовать в задачу"
msgstr "Преобразовать в Markdown"
#: packages/app-mobile/components/screens/Note/Note.tsx:1350
msgid "Convert to note"
@@ -1504,9 +1503,8 @@ msgid "Could not connect to plugin repository."
msgstr "Не удалось соединиться с репозиторием плагинов."
#: packages/lib/commands/convertNoteToMarkdown.ts:70
#, fuzzy
msgid "Could not convert notes to Markdown: %s"
msgstr "Не удалось экспортировать заметки: %s"
msgstr "Не удалось преобразовать заметки в Markdown: %s"
#: packages/app-desktop/InteropServiceHelper.ts:235
msgid "Could not export notes: %s"
@@ -1562,7 +1560,7 @@ msgstr "Создать новый блокнот"
#: packages/app-mobile/components/FolderPicker.tsx:112
msgid "Create new notebook"
msgstr "Создает новый блокнот."
msgstr "Создать новый блокнот"
#: packages/app-desktop/gui/WindowCommandsAndDialogs/commands/addProfile.ts:9
#: packages/app-mobile/components/ProfileSwitcher/ProfileEditor.tsx:88
@@ -1618,7 +1616,7 @@ msgstr "Создано: %s"
#: packages/app-mobile/components/screens/Notes/NewNoteButton.tsx:70
msgid "Creates a new note with an attachment of type %s"
msgstr "Создать новый блокнот под родительским блокнотом."
msgstr "Создать новый блокнот с вложением типа %s"
#: packages/app-cli/app/command-mknote.js:12
msgid "Creates a new note."
@@ -1777,9 +1775,8 @@ msgid "Delete attachment \"%s\"?"
msgstr "Удалить вложение \"%s\"?"
#: packages/editor/ProseMirror/plugins/tablePlugin.ts:41
#, fuzzy
msgid "Delete column"
msgstr "Удалить строку"
msgstr "Удалить столбец"
#: packages/server/src/services/TaskService.ts:27
msgid "Delete expired sessions"
@@ -1820,18 +1817,18 @@ msgid "Delete profile \"%s\""
msgstr "Удалить профиль \"%s\""
#: packages/app-desktop/gui/ProfileEditor.tsx:147
#, fuzzy
msgid ""
"Delete profile \"%s\"?\n"
"\n"
"All data, including notes, notebooks and tags will be permanently deleted."
msgstr ""
"Все данные, включая заметки, блокноты и теги, будут удалены безвозвратно."
"Удалить профиль \"%s\"?\n"
"\n"
"Все данные, включая заметки, блокноты и теги, будут безвозвратно удалены."
#: packages/editor/ProseMirror/plugins/tablePlugin.ts:36
#, fuzzy
msgid "Delete row"
msgstr "Удалить заметку"
msgstr "Удалить строку"
#: packages/app-mobile/components/ScreenHeader/index.tsx:487
msgid "Delete selected notes"
@@ -1844,6 +1841,10 @@ msgid ""
"All notes associated with this tag will remain, but the tag will be removed "
"from all notes."
msgstr ""
"Удалить тег \"%s\"?\n"
"\n"
"Все заметки, связанные с этим тегом, останутся, но тег будет удалён со всех "
"заметок."
#: packages/app-desktop/gui/WindowCommandsAndDialogs/commands/deleteFolder.ts:38
#: packages/app-mobile/components/side-menu-content.tsx:414
@@ -2027,7 +2028,7 @@ msgstr "Отображает полную информацию о заметке
#: packages/app-cli/app/command-keymap.ts:14
msgid "Displays the configured keyboard shortcuts."
msgstr ""
msgstr "Отображает настроенные сочетания клавиш."
#: packages/app-cli/app/command-cat.ts:14
msgid "Displays the given note."
@@ -2076,7 +2077,7 @@ msgstr ""
#: packages/app-mobile/components/FeedbackBanner.tsx:167
msgid "Do you find the Joplin web app useful?"
msgstr ""
msgstr "Вы находите веб-приложение Joplin полезным?"
#: packages/lib/models/settings/builtInMetadata.ts:2003
msgid "Document scanner: Title template"
@@ -2247,9 +2248,8 @@ msgid "Edit profile configuration..."
msgstr "Редактирование конфигурации профиля..."
#: packages/app-mobile/components/screens/tags.tsx:64
#, fuzzy
msgid "Edit tag"
msgstr "Редактировать заметку."
msgstr "Редактировать тег"
#: packages/app-desktop/gui/MainScreen.tsx:129
#: packages/app-desktop/gui/NoteContentPropertiesDialog.tsx:151
@@ -2359,9 +2359,8 @@ msgid "Enable abbreviation syntax"
msgstr "Включить синтаксис аббревиатур"
#: packages/lib/models/settings/builtInMetadata.ts:1093
#, fuzzy
msgid "Enable ABC musical notation support"
msgstr "Включить поддержку синтаксиса Fountain"
msgstr "Включить поддержку музыкальной нотации ABC"
#: packages/lib/models/settings/builtInMetadata.ts:1095
msgid "Enable audio player"
@@ -2568,7 +2567,7 @@ msgstr "Введите код здесь"
#: packages/app-desktop/gui/SsoLoginScreen/SsoLoginScreen.tsx:43
msgid "Enter the code:"
msgstr "Введите код здесь"
msgstr "Введите код:"
#: packages/app-mobile/components/NoteItem.tsx:130
msgid "Entering selection mode"
@@ -2648,9 +2647,8 @@ msgstr "Редактировать блокнот"
#: packages/app-mobile/components/screens/Note/Note.tsx:1758
#: packages/app-mobile/components/screens/NoteRevisionViewer.tsx:225
#, fuzzy
msgid "Expand title"
msgstr "Развернуть"
msgstr "Развернуть заголовок"
#: packages/app-desktop/gui/Sidebar/listItemComponents/ExpandIcon.tsx:21
msgid "Expanded"
@@ -2760,7 +2758,7 @@ msgstr "Флаги функций"
#: packages/app-mobile/components/FeedbackBanner.tsx:180
msgid "Feedback"
msgstr ""
msgstr "Обратная связь"
#: packages/lib/Synchronizer.ts:207
msgid "Fetched items: %d/%d."
@@ -3141,7 +3139,6 @@ msgid "Import or export your data"
msgstr "Импорт или экспорт ваших данных"
#: packages/app-desktop/gui/WindowCommandsAndDialogs/commands/importFrom.ts:20
#, fuzzy
msgid "Import..."
msgstr "Импортирование..."
@@ -3244,7 +3241,7 @@ msgstr "В: %s"
#: packages/app-cli/app/command-share.ts:170
msgid "Incoming shares:"
msgstr "Поступающие ресурсы"
msgstr "Поступающие ресурсы:"
#: packages/app-mobile/components/screens/ConfigScreen/plugins/PluginBox/PluginChips.tsx:69
msgid "Incompatible"
@@ -3455,9 +3452,8 @@ msgid "Joplin Server"
msgstr "Сервер Joplin"
#: packages/lib/SyncTargetJoplinServerSAML.ts:68
#, fuzzy
msgid "Joplin Server (SAML)"
msgstr "URL сервера Joplin"
msgstr "Joplin Server (SAML)"
#: packages/lib/utils/joplinCloud/index.ts:454
msgid "Joplin Server Business"
@@ -3490,6 +3486,9 @@ msgid ""
"Joplin supports saving the location at which notes are saved or created. Do "
"you want to enable it? This can be changed at any time in settings."
msgstr ""
"Joplin поддерживает сохранение местоположения, в котором сохраняются или "
"создаются заметки. Вы хотите включить его? Это можно изменить в любое время "
"в настройках."
#: packages/app-desktop/gui/ClipperConfigScreen.tsx:132
msgid ""
@@ -3539,7 +3538,7 @@ msgstr "Поддерживаемая связка ключей: %s"
#: packages/app-cli/app/command-keymap.ts:30
msgid "KEYS"
msgstr ""
msgstr "КЛЮЧИ"
#: packages/app-desktop/gui/EncryptionConfigScreen/EncryptionConfigScreen.tsx:74
msgid "Keys that need upgrading"
@@ -3547,7 +3546,7 @@ msgstr "Ключи, которые нуждаются в обновлении"
#: packages/editor/ProseMirror/plugins/imagePlugin.ts:265
msgid "Label"
msgstr ""
msgstr "Метка"
#: packages/lib/models/settings/builtInMetadata.ts:1447
msgid "Landscape"
@@ -3637,9 +3636,9 @@ msgstr "Ссылка"
#: packages/lib/components/shared/ShareNoteDialog/useShareStatusMessage.ts:21
msgid "Link created!"
msgid_plural "Links created!"
msgstr[0] "Текст ссылки"
msgstr[1] "Текст ссылки"
msgstr[2] "Текст ссылки"
msgstr[0] "Ссылка создана!"
msgstr[1] "Ссылки созданы!"
msgstr[2] "Ссылок создано!"
#: packages/app-mobile/components/NoteEditor/EditLinkDialog.tsx:92
msgid "Link description"
@@ -3772,6 +3771,8 @@ msgid ""
"Manage your profiles. You can rename or delete profiles. The active profile "
"cannot be deleted."
msgstr ""
"Управляйте своими профилями. Вы можете переименовывать или удалять профили. "
"Активный профиль нельзя удалить."
#. `generate-ppk`
#: packages/app-cli/app/command-e2ee.ts:19
@@ -3804,14 +3805,12 @@ msgid "Markdown editor"
msgstr "Редактор Markdown"
#: packages/lib/models/settings/builtInMetadata.ts:1519
#, fuzzy
msgid "Markdown editor: Highlight active line"
msgstr "Редактор Markdown"
msgstr "Редактор Markdown: выделять активную строку"
#: packages/lib/models/settings/builtInMetadata.ts:1508
#, fuzzy
msgid "Markdown editor: Render images"
msgstr "Редактор Markdown"
msgstr "Редактор Markdown: отображать изображения"
#: packages/lib/models/settings/builtInMetadata.ts:1498
msgid "Markdown editor: Render markup in editor"
@@ -3894,7 +3893,7 @@ msgstr "Недостающие мастер-ключи"
#: packages/app-mobile/components/voiceTyping/AudioRecordingBanner.tsx:121
msgid "Missing permission to record audio."
msgstr "Отсутствует разрешение для камеры"
msgstr "Отсутствует разрешение для записи аудио."
#: packages/app-cli/app/cli-utils.js:112
msgid "Missing required argument: %s"
@@ -3937,16 +3936,16 @@ msgstr[1] "Переместить %d заметок в блокнот \"%s\"?"
msgstr[2] "Переместить %d заметок в блокнот \"%s\"?"
#: packages/app-desktop/gui/WindowCommandsAndDialogs/commands/deleteFolder.ts:34
#, fuzzy
msgid ""
"Move %d notebooks to the trash?\n"
"\n"
"All notes and sub-notebooks within these notebooks will also be moved to the "
"trash."
msgstr ""
"Переместить блокнот “%s” в корзину?\n"
"Переместить %d блокнотов в корзину?\n"
"\n"
"Все заметки и вложенные блокноты также будут перемещены в корзину."
"Все заметки и подблокноты внутри этих блокнотов также будут перемещены в "
"корзину."
#: packages/app-desktop/gui/ResizableLayout/MoveButtons.tsx:73
msgid "Move down"
@@ -4050,7 +4049,7 @@ msgstr ""
#: packages/app-mobile/components/FolderPicker.tsx:71
msgid "New notebook title"
msgstr "Название блокнота:"
msgstr "Название нового блокнота"
#: packages/app-mobile/setupQuickActions.ts:32
msgid "New photo"
@@ -4168,7 +4167,7 @@ msgstr "Вкладка не выбрана"
#: packages/app-mobile/components/TagEditor.tsx:183
msgid "No tags"
msgstr "Новые метки:"
msgstr "Нет тегов"
#: packages/app-cli/app/command-edit.ts:31
msgid ""
@@ -4183,7 +4182,7 @@ msgstr "Нет доступных обновлений"
#: packages/lib/components/shared/SamlShared.ts:12
msgid "No URL for SAML authentication set."
msgstr ""
msgstr "URL для аутентификации SAML не задан."
#: packages/app-cli/app/command-share.ts:188
#: packages/app-cli/app/command-share.ts:208
@@ -4219,7 +4218,7 @@ msgstr "Не сейчас"
#: packages/app-mobile/components/FeedbackBanner.tsx:188
msgid "Not useful"
msgstr ""
msgstr "Бесполезный"
#: packages/app-desktop/gui/NoteListControls/NoteListControls.tsx:110
#: packages/app-desktop/gui/NoteListWrapper/NoteListWrapper.tsx:71
@@ -4296,9 +4295,8 @@ msgid "Note list style"
msgstr "Стиль списка заметок"
#: packages/app-cli/app/command-unpublish.ts:41
#, fuzzy
msgid "Note not published: %s"
msgstr "Содержимое предоставлено: %s"
msgstr "Заметка не опубликована: %s"
#: packages/app-mobile/components/screens/DocumentScanner/DocumentScanner.tsx:140
msgid "Note preview"
@@ -4530,7 +4528,7 @@ msgstr "Открыть мастер синхронизации..."
#: packages/app-mobile/components/screens/ConfigScreen/ConfigScreen.tsx:635
msgid "Open-source licences"
msgstr ""
msgstr "Лицензия open-source"
#: packages/app-desktop/gui/NoteEditor/utils/contextMenu.ts:87
msgid "Open..."
@@ -4569,6 +4567,8 @@ msgid ""
"Options that should be used whenever rendering ABC code. It must be a JSON5 "
"object. The full list of options is available at: %s"
msgstr ""
"Опции, которые следует использовать при визуализации кода ABC. Это должен "
"быть объект JSON5. Полный список опций доступен по адресу: %s"
#: packages/app-mobile/components/NoteEditor/commandDeclarations.ts:103
msgid "Ordered list"
@@ -4576,7 +4576,7 @@ msgstr "Упорядоченный список"
#: packages/app-mobile/components/SyncWizard/SyncWizard.tsx:130
msgid "Other"
msgstr ""
msgstr "Другое"
#: packages/app-desktop/gui/MenuBar.tsx:459
msgid "Other applications..."
@@ -4937,9 +4937,8 @@ msgid "Profile name"
msgstr "Название профиля"
#: packages/app-desktop/gui/ProfileEditor.tsx:120
#, fuzzy
msgid "Profile name cannot be empty"
msgstr "Подтверждение пароля не может быть пустым"
msgstr "Имя профиля не может быть пустым"
#: packages/app-desktop/gui/ProfileEditor.tsx:116
#: packages/app-desktop/gui/WindowCommandsAndDialogs/commands/addProfile.ts:18
@@ -4979,9 +4978,8 @@ msgid "Publish Note"
msgstr "Публиковать заметку"
#: packages/app-cli/app/command-publish.ts:47
#, fuzzy
msgid "Publish note \"%s\" (in notebook \"%s\")?"
msgstr "Переместить %d заметок в блокнот \"%s\"?"
msgstr "Опубликовать заметку \"%s\" (в блокноте \"%s\")?"
#: packages/app-desktop/gui/WindowCommandsAndDialogs/commands/showShareNoteDialog.ts:6
msgid "Publish note..."
@@ -5002,14 +5000,13 @@ msgid "Publish/unpublish"
msgstr "Опубликовать/Отменить публикацию"
#: packages/app-cli/app/command-publish.ts:60
#, fuzzy
msgid "Published at URL: %s"
msgstr "Публиковать заметку"
msgstr "Опубликовано по адресу URL: %s"
#: packages/app-cli/app/command-publish.ts:27
#: packages/app-cli/app/command-unpublish.ts:24
msgid "Publishes a note to Joplin Server or Joplin Cloud"
msgstr ""
msgstr "Публикует заметку на Joplin Server или Joplin Cloud"
#: packages/app-mobile/components/CameraView/ScannedBarcodes.tsx:79
msgid "QR Code"
@@ -5056,7 +5053,7 @@ msgstr "Продолжительность чтения: %s мин"
#: packages/app-cli/app/command-batch.ts:45
msgid "Reading commands from standard input is only available in CLI mode."
msgstr "Команда \"%s\" доступна только в режиме GUI"
msgstr "Чтение команд из стандартного ввода доступно только в режиме CLI."
#: packages/app-desktop/gui/ShareFolderDialog/ShareFolderDialog.tsx:303
msgid "Recipient has accepted the invitation"
@@ -5075,13 +5072,12 @@ msgid "Recipients:"
msgstr "Получатели:"
#: packages/app-mobile/components/screens/DocumentScanner/NotePreview.tsx:162
#, fuzzy
msgid "Recognise text:"
msgstr "курсивный текст"
msgstr "Распознать текст:"
#: packages/app-desktop/gui/NoteEditor/utils/contextMenu.ts:142
msgid "Recognize handwritten image"
msgstr "Изменение размера больших изображений:"
msgstr "Распознать рукописное изображение"
#: packages/app-mobile/components/screens/ConfigScreen/plugins/PluginBox/RecommendedBadge.tsx:72
msgid "Recommended"
@@ -5135,11 +5131,8 @@ msgid "Remove"
msgstr "Удалить"
#: packages/app-desktop/gui/Sidebar/hooks/useOnRenderItem.tsx:134
#, fuzzy
msgid "Remove %d tags from all notes? This cannot be undone."
msgstr ""
"Удалить модель и перезагрузить?\n"
"Это невозможно отменить."
msgstr "Удалить %d тегов из всех заметок? Это действие нельзя отменить."
#: packages/app-mobile/components/TagEditor.tsx:136
msgid "Remove %s"
@@ -5159,11 +5152,11 @@ msgstr "Удалить этот поиск из боковой панели?"
#: packages/app-cli/app/command-share.ts:112
msgid "Removed %s from share."
msgstr "Удалить %s из общего ресурса"
msgstr "Удалено %s из общего ресурса."
#: packages/app-mobile/components/TagEditor.tsx:247
msgid "Removed tag: %s"
msgstr "Переименовать метку:"
msgstr "Удален тег: %s"
#: packages/app-desktop/gui/ProfileEditor.tsx:68
#: packages/app-desktop/gui/WindowCommandsAndDialogs/commands/renameFolder.ts:8
@@ -5436,9 +5429,8 @@ msgid "Save geo-location with notes"
msgstr "Сохранять информацию о географическом местоположении в заметках"
#: packages/app-mobile/components/screens/Note/Note.tsx:575
#, fuzzy
msgid "Save geolocation?"
msgstr "Сохранять информацию о географическом местоположении в заметках"
msgstr "Сохранить геолокацию?"
#: packages/app-mobile/components/screens/Notes/NewNoteButton.tsx:81
msgid "Scan notebook"
@@ -5549,7 +5541,7 @@ msgstr "Выбор блокнота"
#: packages/app-mobile/components/SyncWizard/SyncWizard.tsx:131
msgid "Select one of the other supported sync targets."
msgstr ""
msgstr "Выберите одну из других поддерживаемых целей синхронизации."
#: packages/app-mobile/components/screens/folder.js:109
msgid "Select parent notebook"
@@ -5557,7 +5549,7 @@ msgstr "Выбрать родительский блокнот"
#: packages/app-desktop/gui/WindowCommandsAndDialogs/commands/importFrom.ts:42
msgid "Select the type of file to be imported:"
msgstr ""
msgstr "Выберите тип файла для импорта:"
#: packages/app-mobile/components/ComboBox.tsx:378
msgid "Selected: %s"
@@ -5769,7 +5761,7 @@ msgstr "Боковая панель"
#: packages/app-desktop/gui/JoplinCloudSignUpCallToAction.tsx:15
msgid "Sign up to Joplin Cloud"
msgstr "Войти в Joplin Cloud."
msgstr "Войти в Joplin Cloud"
#: packages/app-desktop/gui/ResourceScreen.tsx:117
msgid "Size"
@@ -5885,7 +5877,7 @@ msgstr "Источник: "
#: packages/app-cli/app/command-keymap.ts:35
msgid "SPACE"
msgstr ""
msgstr "ПРОСТРАНСТВО"
#: packages/app-desktop/gui/Sidebar/hooks/useOnRenderItem.tsx:456
msgid "Spacer"
@@ -6095,7 +6087,7 @@ msgstr ""
#: packages/app-mobile/components/SyncWizard/SyncWizard.tsx:111
msgid "Sync"
msgstr ""
msgstr "Синхронизация"
#: packages/lib/utils/joplinCloud/index.ts:170
msgid "Sync as many devices as you want"
@@ -6196,18 +6188,16 @@ msgid "Tab moves focus"
msgstr "\"Tab\" cмещает фокус"
#: packages/app-mobile/components/NoteEditor/commandDeclarations.ts:118
#, fuzzy
msgid "Table"
msgstr "Включить"
msgstr "Таблица"
#: packages/lib/models/settings/builtInMetadata.ts:1440
msgid "Tabloid"
msgstr "Таблоид"
#: packages/app-mobile/components/screens/tags.tsx:206
#, fuzzy
msgid "Tag: %s"
msgstr "Использовано: %s"
msgstr "Тег: %s"
#: packages/app-cli/app/command-import.ts:58
#: packages/app-desktop/gui/ImportScreen.tsx:94
@@ -6229,9 +6219,8 @@ msgid "Take photo"
msgstr "Сделать фото"
#: packages/app-mobile/components/FeedbackBanner.tsx:164
#, fuzzy
msgid "Take survey"
msgstr "Нарисовать картинку"
msgstr "Пройти опрос"
#: packages/app-mobile/components/screens/ConfigScreen/NoteExportSection/TaskButton.tsx:73
msgid "Task \"%s\" failed with error: %s"
@@ -6263,6 +6252,8 @@ msgid ""
"Thank you for the feedback!\n"
"Do you have time to complete a short survey?"
msgstr ""
"Спасибо за отзыв!\n"
"У вас есть время заполнить небольшой опрос?"
#: packages/app-desktop/gui/ProfileEditor.tsx:143
#: packages/lib/services/profileConfig/index.ts:106
@@ -6429,16 +6420,21 @@ msgid "The note \"%s\" has been successfully restored to the notebook \"%s\"."
msgstr "Заметка “%s” была успешно восстановлена в блокнот “%s”."
#: packages/lib/commands/convertNoteToMarkdown.ts:64
#, fuzzy
msgid ""
"The note has been converted to Markdown and the original note has been moved "
"to the trash"
msgid_plural ""
"The notes have been converted to Markdown and the original notes have been "
"moved to the trash"
msgstr[0] "Блокнот и его содержимое были успешно перемещены в корзину."
msgstr[1] "Блокнот и его содержимое были успешно перемещены в корзину."
msgstr[2] "Блокнот и его содержимое были успешно перемещены в корзину."
msgstr[0] ""
"Заметка была преобразована в Markdown, а оригинальные заметки перемещены в "
"корзину"
msgstr[1] ""
"Заметки были преобразованы в Markdown, а оригинальные заметки перемещены в "
"корзину"
msgstr[2] ""
"Заметок были преобразованы в Markdown, а оригинальные заметки перемещены в "
"корзину"
#: packages/app-desktop/gui/TrashNotification/TrashNotification.tsx:45
msgid "The note was successfully moved to the trash."
@@ -7016,7 +7012,7 @@ msgstr "Попробуйте прямо сейчас"
#: packages/app-cli/app/command-keymap.ts:30
msgid "TYPE"
msgstr ""
msgstr "ТИП"
#: packages/app-cli/app/command-help.ts:72
msgid ""
@@ -7056,9 +7052,8 @@ msgid "Unable to share log data. Reason: %s"
msgstr "Невозможно поделиться данными журнала. Причина: %s"
#: packages/app-mobile/components/screens/Note/Note.tsx:1125
#, fuzzy
msgid "Unable to share note data. Reason: %s"
msgstr "Невозможно поделиться данными журнала. Причина: %s"
msgstr "Не удается поделиться данными заметки. Причина: %s"
#: packages/app-mobile/components/Checkbox.tsx:51
msgid "Unchecked"
@@ -7323,7 +7318,7 @@ msgstr ""
#: packages/app-mobile/components/FeedbackBanner.tsx:195
msgid "Useful"
msgstr ""
msgstr "Полезный"
#: packages/server/src/services/MustacheService.ts:125
msgid "User deletions"
@@ -7503,6 +7498,9 @@ msgid ""
"higher-quality on-server transcription service. Requires sync with a copy of "
"the desktop app."
msgstr ""
"Когда включено, запросы на транскрипцию изображений в заметке выполняются с "
"использованием более качественного сервиса транскрипции на сервере. "
"Требуется синхронизация с копией настольного приложения."
#: packages/lib/models/settings/builtInMetadata.ts:577
msgid ""
+2 -2
View File
@@ -44,7 +44,7 @@
"yargs": "17.7.2"
},
"devDependencies": {
"@docusaurus/plugin-sitemap": "2.4.3",
"@docusaurus/plugin-sitemap": "3.9.2",
"@joplin/fork-htmlparser2": "^4.1.60",
"@rmp135/sql-ts": "1.18.1",
"@types/fs-extra": "11.0.4",
@@ -61,7 +61,7 @@
"jest": "29.7.0",
"js-yaml": "4.1.1",
"rss": "1.2.2",
"sass": "1.96.0",
"sass": "1.97.2",
"sqlite3": "5.1.6",
"style-to-js": "1.1.21",
"ts-node": "10.9.2",
+2 -1
View File
@@ -215,6 +215,7 @@
"v3.6.7": true,
"android-v3.6.15": true,
"ios-v13.6.4": true,
"v3.6.8": true
"v3.6.8": true,
"android-v3.6.16": true
}
}

Some files were not shown because too many files have changed in this diff Show More