diff --git a/.github/TRANSLATING.md b/.github/TRANSLATING.md index 1fb11de321..bb7f16251a 100644 --- a/.github/TRANSLATING.md +++ b/.github/TRANSLATING.md @@ -86,3 +86,22 @@ Here are some guidelines to help with the translation. Remember, the main goal of the translation is to make the content as accessible and clear to the new audience as it was to the original audience. Always prioritize clarity and accuracy. Thank you for your interest in contributing; we're excited to have you! Reach out on the [`#docs` channel on Discord](https://discord.com/invite/tauri) if you have any questions along the way. + +## Language-specific Guidelines + +This section was written by the translators themselves, feel free to add your own tips here. + +### Basic Procedure of JP Translation(邦訳基本手順) + +1. Use On-line Translation for the inital translation.
オンライン翻訳にて初期翻訳。 +1. Checks on the auto-translation result. Inappropriate translations shall be corrected (such as "Tauri" - which is often translated as the name of the zodiac sign "the Bull").
自動翻訳の内容確認。不適切な訳語は修正(例えば「牡牛座」と訳された "Tauri" など)。 +1. Products names, trade names and proper names such as Tauri, Windows, macOS etc. are shown as they are.
商品名、会社名、固有名詞などは、 + そのまま英語表記とする(必要に応じて括弧書きで「読み」を表示)。 +1. The technical terms shall be checked on the on-line terminology sites (Microsoft Terminology Search, etc.)
技術専門用語類は、オンライン用語検索サイト(マイクロソフト社等)に記載されている一般的なものを採用するが、カタカナ語に関しては適宜和語に置き換える場合もある。 + +### Basic Procedure of KO Translation(번역 기본 절차) + +1. Use On-line Translation for the inital translation.
온라인 번역으로 초기 번역. +1. Checks on the auto-translation result. Inappropriate translations shall be corrected (such as "Tauri" - which is often translated as the name of the zodiac sign "the Bull").
자동 번역 내용 확인. 부적절한 번역어는 수정(예: "황소자리"로 번역된 "Tauri" 등). +1. Products names, trade names and proper names such as Tauri, Windows, macOS etc. are shown as they are.
상품명, 회사명, 고유명사 등은 그대로 영어 표기로 함(필요에 따라 괄호 안에 "읽기" 표시). +1. The technical terms shall be checked on the on-line terminology sites (Microsoft Terminology Search, etc.)
기술 전문 용어류는 온라인 용어 검색 사이트(마이크로소프트사 등)에 기재된 일반적인 것을 채택하지만, 가타카나어에 관해서는 적절히 한국어로 대체하는 경우도 있음. diff --git a/.github/labeler.yml b/.github/labeler.yml index fcaec757b4..d2c3e26b96 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -5,6 +5,8 @@ i18n: - src/content/docs/fr/**/* - src/content/docs/it/**/* - src/content/docs/zh-cn/**/* + - src/content/docs/ja/**/* + - src/content/docs/ko/**/* "i18n: es": - src/content/docs/es/**/* @@ -17,3 +19,9 @@ i18n: "i18n: zh-cn": - src/content/docs/zh-cn/**/* + +"i18n: ja": + - src/content/docs/ja/**/* + +"i18n: ko": + - src/content/docs/ko/**/* diff --git a/.github/workflows/syncSponsorsData.yml b/.github/workflows/syncSponsorsData.yml new file mode 100644 index 0000000000..86d3235ac5 --- /dev/null +++ b/.github/workflows/syncSponsorsData.yml @@ -0,0 +1,55 @@ +name: 'Sync Sponsors Data' + +on: + schedule: + # daily + - cron: '0 0 * * *' + workflow_dispatch: + +jobs: + sync-sponsors-data: + name: Sync Sponsors Data + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: 'pnpm' + + - run: pnpm i + + - name: sync-sponsors + run: pnpm sync:sponsors + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - run: pnpm prettier src/data -w + + # tauri-docs PR + - name: Git config + run: | + git config --global user.name "tauri-bot" + git config --global user.email "tauri-bot@tauri.app" + + - name: Create pull request for updated docs + id: cpr + # soft fork of https://github.com/peter-evans/create-pull-request for security purposes + uses: tauri-apps/create-pull-request@v3.4.1 + if: github.event_name != 'pull_request' && github.event_name != 'push' + with: + token: ${{ secrets.ORG_TAURI_BOT_PAT }} + commit-message: 'chore(docs): Update Sponsors Data' + branch: ci/v2/update-sponsors + title: Update Sponsors Data + labels: 'bot' + + - name: Automerge + run: gh pr merge --squash --auto ${{ steps.cpr.outputs.pull-request-number }} + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.prettierignore b/.prettierignore index d0ebb4e924..4218a9f56e 100644 --- a/.prettierignore +++ b/.prettierignore @@ -7,6 +7,7 @@ # Generated reference docs src/content/docs/reference +src/content/docs/release # Git Modules packages/tauri @@ -25,10 +26,20 @@ pnpm-lock.yaml src/components/overrides/Header.astro # TODO: Prettier breaks these pages +src/content/docs/start/frontend/qwik.mdx +src/content/docs/*/start/frontend/qwik.mdx + +src/content/docs/security/http-headers.mdx +src/content/docs/*/security/http-headers.mdx + +src/content/docs/learn/splashscreen.mdx +src/content/docs/*/learn/splashscreen.mdx + src/content/docs/learn/Security/capabilities-for-windows-and-platforms.mdx +src/content/docs/*/learn/Security/capabilities-for-windows-and-platforms.mdx + src/content/docs/learn/Security/using-plugin-permissions.mdx +src/content/docs/*/learn/Security/using-plugin-permissions.mdx + src/content/docs/learn/Security/writing-plugin-permissions.mdx -src/content/docs/start/frontend/qwik.mdx -src/content/docs/zh-cn/start/frontend/qwik.mdx -src/content/docs/learn/splashscreen.mdx -src/content/docs/security/http-headers.mdx +src/content/docs/*/learn/Security/writing-plugin-permissions.mdx diff --git a/.vscode/settings.json b/.vscode/settings.json index e66e920719..be713d3814 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,5 +3,8 @@ "prettier.documentSelectors": ["**/*.astro"], "[astro]": { "editor.defaultFormatter": "astro-build.astro-vscode" + }, + "[mdx]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" } } diff --git a/astro.config.mjs b/astro.config.mjs index 261cb2ae04..ee24adee8a 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -1,16 +1,18 @@ +// @ts-check import { defineConfig } from 'astro/config'; import starlight from '@astrojs/starlight'; import { rehypeHeadingIds } from '@astrojs/markdown-remark'; import rehypeAutolinkHeadings from 'rehype-autolink-headings'; import locales from './locales.json'; import starlightLinksValidator from 'starlight-links-validator'; +import starlightSidebarTopics from 'starlight-sidebar-topics'; import starlightBlog from 'starlight-blog'; import serviceWorker from 'astrojs-service-worker'; import astroD2 from 'astro-d2'; -import starlightUtils from '@lorenzo_lewis/starlight-utils'; import path from 'path'; import { fileURLToPath } from 'url'; import lunaria from '@lunariajs/starlight'; +import { readFileSync } from 'fs'; const authors = { nothingismagick: { @@ -58,6 +60,11 @@ const authors = { title: 'Tauri Security', picture: '/authors/chip.png', }, + tony: { + name: 'Tony', + title: 'Tauri Development', + picture: '/authors/tony.jpeg', + }, }; const site = 'https://v2.tauri.app'; @@ -69,12 +76,249 @@ export default defineConfig({ integrations: [ starlight({ plugins: [ - starlightUtils({ - multiSidebar: { - switcherStyle: 'horizontalList', - }, - }), starlightBlog({ authors }), + starlightSidebarTopics( + [ + { + label: { + en: 'Guides', + 'zh-CN': '指引', + es: 'Guías', + }, + id: 'guides', + link: '/start/', + icon: 'open-book', + items: [ + { + label: 'Quick Start', + translations: { + 'zh-CN': '快速开始', + es: 'Guía rápida', + }, + collapsed: true, + items: [ + 'start', + 'start/prerequisites', + 'start/create-project', + 'start/project-structure', + // { + // label: 'What is Tauri?', + // // translations: { + // // 'zh-CN': '什么是 Tauri?', + // // es: '¿Qué es Tauri?', + // // }, + // link: '/start/', + // }, + // { + // label: 'Prerequisites', + // // translations: { + // // 'zh-CN': '前置条件', + // // es: 'Requisitos previos', + // // }, + // link: '/start/prerequisites/', + // }, + // { + // label: 'Create a Project', + // // translations: { + // // 'zh-CN': '创建项目', + // // es: 'Crea un proyecto', + // // }, + // link: '/start/create-project/', + // }, + { + label: 'Frontend Configuration', + translations: { + 'zh-CN': '前端配置', + es: 'Configuración del frontend', + }, + collapsed: true, + autogenerate: { directory: 'start/frontend' }, + }, + { + label: 'Upgrade & Migrate', + translations: { + 'zh-CN': '升级和迁移', + es: 'Actualizar y migrar', + }, + collapsed: true, + autogenerate: { directory: 'start/migrate' }, + }, + ], + }, + { + label: 'Core Concepts', + translations: { + 'zh-CN': '核心概念', + es: 'Conceptos básicos', + }, + collapsed: true, + autogenerate: { directory: 'concept' }, + }, + { + label: 'Security', + translations: { + 'zh-CN': '安全', + es: 'Seguridad', + }, + collapsed: true, + autogenerate: { directory: 'security' }, + }, + { + label: 'Develop', + translations: { + 'zh-CN': '开发', + es: 'Desarrollo', + }, + collapsed: true, + items: [ + 'develop', + 'develop/configuration-files', + 'develop/calling-rust', + 'develop/calling-frontend', + 'develop/resources', + 'develop/sidecar', + 'develop/state-management', + 'develop/updating-dependencies', + 'develop/icons', + { + label: 'Debug', + collapsed: true, + autogenerate: { directory: 'develop/Debug' }, + }, + { + label: 'Plugins', + collapsed: true, + autogenerate: { directory: 'develop/Plugins' }, + }, + { + label: 'Tests', + collapsed: true, + autogenerate: { directory: 'develop/Tests' }, + }, + ], + }, + { + label: 'Distribute', + translations: { + 'zh-CN': '分发', + es: 'Distribuir', + }, + collapsed: true, + autogenerate: { directory: 'distribute' }, + }, + { + label: 'Learn', + translations: { + 'zh-CN': '学习', + es: 'Aprende', + }, + collapsed: true, + autogenerate: { directory: 'learn' }, + }, + { + label: 'Plugins', + translations: { + 'zh-CN': '插件', + es: 'Plugins', + }, + collapsed: true, + autogenerate: { directory: 'plugin' }, + }, + { + label: 'About', + translations: { + 'zh-CN': '关于', + es: 'Acerca de', + }, + collapsed: true, + autogenerate: { directory: 'about' }, + }, + ], + }, + { + label: { en: 'References', 'zh-CN': '参考', es: 'Referencias' }, + id: 'references', + link: '/reference/cli', + icon: 'document', + items: [ + { + label: 'Command Line Interface', + translations: { + 'zh-CN': '命令行接口(CLI)', + es: 'Interfaz de línea de comandos', + }, + link: '/reference/cli/', + }, + { + label: 'Security', + translations: { + 'zh-CN': '安全', + es: 'Seguridad', + }, + collapsed: true, + autogenerate: { directory: 'reference/acl' }, + }, + { + label: 'Configuration', + translations: { + 'zh-CN': '配置', + es: 'Configuración', + }, + link: '/reference/config/', + }, + { + label: 'Environment Variables', + translations: { + 'zh-CN': '环境变量', + es: 'Variables de entorno', + }, + link: '/reference/environment-variables/', + }, + { + label: 'Webview Versions', + translations: { + 'zh-CN': 'Webview 版本', + es: 'Versiones de Webview', + }, + link: '/reference/webview-versions/', + }, + { + label: 'Releases', + translations: { + 'zh-CN': '发行版', + es: 'Lanzamientos', + }, + collapsed: true, + autogenerate: { directory: 'release' }, + }, + { + label: 'JavaScript', + collapsed: true, + autogenerate: { directory: 'reference/javascript' }, + }, + { + label: 'Rust (docs.rs)', + link: 'https://docs.rs/tauri/~2/', + }, + ], + }, + { + label: 'Blog', + id: 'blog', + link: '/blog/', + icon: 'pen', + // Empty item to instruct it that is is local files, not an external link + // this is actually filled in through the topics dir for `blog` below + items: [], + }, + ], + { + exclude: ['**/_*/**'], + topics: { + blog: ['/blog', '/blog/*', '/blog/**/*', '**/blog', '**/blog/*', '**/blog/**/*'], + }, + } + ), starlightLinksValidator({ errorOnFallbackPages: false, errorOnRelativeLinks: false, @@ -89,19 +333,18 @@ export default defineConfig({ light: './src/assets/logo_light.svg', replacesTitle: true, }, - social: { - github: 'https://github.com/tauri-apps/tauri', - discord: 'https://discord.com/invite/tauri', - twitter: 'https://twitter.com/TauriApps', - mastodon: 'https://fosstodon.org/@TauriApps', - rss: `${site}/rss/`, - }, + social: [ + { icon: 'github', label: 'GitHub', href: 'https://github.com/tauri-apps/tauri' }, + { icon: 'discord', label: 'Discord', href: 'https://discord.com/invite/tauri' }, + { icon: 'twitter', label: 'Twitter', href: 'https://twitter.com/TauriApps' }, + { icon: 'blueSky', label: 'Bluesky', href: 'https://bsky.app/profile/tauri.app' }, + { icon: 'mastodon', label: 'Mastodon', href: 'https://fosstodon.org/@TauriApps' }, + { icon: 'rss', label: 'RSS', href: `${site}/rss` }, + ], components: { Header: './src/components/overrides/Header.astro', Footer: 'src/components/overrides/Footer.astro', ThemeSelect: 'src/components/overrides/ThemeSelect.astro', - PageFrame: 'src/components/overrides/PageFrame.astro', - TableOfContents: 'src/components/overrides/TableOfContents.astro', }, head: [ { @@ -140,199 +383,6 @@ export default defineConfig({ expressiveCode: { styleOverrides: { borderRadius: '0.5rem' }, }, - sidebar: [ - { - label: 'Guides', - translations: { - 'zh-CN': '指引', - }, - collapsed: true, - items: [ - { - label: 'Quick Start', - translations: { - 'zh-CN': '快速开始', - }, - collapsed: true, - items: [ - { - label: 'What is Tauri?', - translations: { - 'zh-CN': '什么是 Tauri?', - }, - link: '/start/', - }, - { - label: 'Prerequisites', - translations: { - 'zh-CN': '前置条件', - }, - link: '/start/prerequisites/', - }, - { - label: 'Create a Project', - translations: { - 'zh-CN': '创建项目', - }, - link: '/start/create-project/', - }, - { - label: 'Frontend Configuration', - translations: { - 'zh-CN': '前端配置', - }, - collapsed: true, - autogenerate: { directory: 'start/frontend' }, - }, - { - label: 'Upgrade & Migrate', - translations: { - 'zh-CN': '升级和迁移', - }, - collapsed: true, - autogenerate: { directory: 'start/migrate' }, - }, - ], - }, - { - label: 'Core Concepts', - translations: { - 'zh-CN': '核心概念', - }, - collapsed: true, - autogenerate: { directory: 'concept' }, - }, - { - label: 'Security', - translations: { - 'zh-CN': '安全', - }, - collapsed: true, - autogenerate: { directory: 'security' }, - }, - { - label: 'Develop', - translations: { - 'zh-CN': '开发', - }, - collapsed: true, - autogenerate: { directory: 'develop' }, - }, - { - label: 'Distribute', - translations: { - 'zh-CN': '分发', - }, - collapsed: true, - autogenerate: { directory: 'distribute' }, - }, - { - label: 'Learn', - translations: { - 'zh-CN': '学习', - }, - collapsed: true, - autogenerate: { directory: 'learn' }, - }, - { - label: 'Plugins', - translations: { - 'zh-CN': '插件', - }, - collapsed: true, - autogenerate: { directory: 'plugin' }, - }, - { - label: 'About', - translations: { - 'zh-CN': '关于', - }, - collapsed: true, - autogenerate: { directory: 'about' }, - }, - ], - }, - { - label: 'References', - translations: { - 'zh-CN': '参考', - }, - collapsed: true, - items: [ - { - label: 'Security', - translations: { - 'zh-CN': '安全', - }, - collapsed: true, - autogenerate: { directory: 'reference/acl' }, - }, - { - label: 'Command Line Interface', - translations: { - 'zh-CN': '命令行接口(CLI)', - }, - link: '/reference/cli/', - }, - { - label: 'Configuration', - translations: { - 'zh-CN': '配置', - }, - link: '/reference/config/', - }, - { - label: 'Environment Variables', - translations: { - 'zh-CN': '环境变量', - }, - link: '/reference/environment-variables/', - }, - { - label: 'Webview Versions', - translations: { - 'zh-CN': 'Webview 版本', - }, - link: '/reference/webview-versions/', - }, - { - label: 'Releases', - translations: { - 'zh-CN': '发行版', - }, - collapsed: true, - autogenerate: { directory: 'release' }, - }, - { - label: 'JavaScript', - collapsed: true, - autogenerate: { directory: 'reference/javascript' }, - }, - { - label: 'Rust (docs.rs)', - link: 'https://docs.rs/tauri/~2/', - }, - ], - }, - { - label: 'Blog', - translations: { - 'zh-CN': '博客', - }, - collapsed: true, - items: [ - { - label: 'All posts', - link: '/blog/', - }, - { - label: 'Recent posts', - collapsed: false, - autogenerate: { directory: 'blog', sort: 'date', order: 'descending' }, - }, - ], - }, - ], locales, lastUpdated: true, }), @@ -365,10 +415,14 @@ export default defineConfig({ }, }), ], + image: { + domains: ['tauri.app', 'images.opencollective.com', 'avatars.githubusercontent.com'], + }, markdown: { shikiConfig: { langs: ['powershell', 'ts', 'rust', 'bash', 'json', 'toml', 'html', 'js'], }, + rehypePlugins: [ rehypeHeadingIds, [ @@ -400,7 +454,7 @@ export default defineConfig({ '/blog/2023/06/14/tauri-1-4': '/blog/tauri-1-4', '/blog/2023/06/15/tauri-board-elections-and-governance-updates': '/blog/tauri-board-elections-and-governance-updates', - 'about/intro': 'about/philosophy', + '/about/intro': '/about/philosophy', // v1 /guides/debugging -> /guides/debug ...i18nRedirect('/v1/guides/debugging/application', '/guides/debug/application'), ...i18nRedirect('/v1/guides/debugging/vs-code', '/guides/debug/vs-code'), @@ -462,10 +516,13 @@ export default defineConfig({ server: { headers: readHeaders(), }, - // }); // Generates a redirect for each locale. +/** + * @param {string} from + * @param {string} to + */ function i18nRedirect(from, to) { const routes = {}; Object.keys(locales).map((locale) => @@ -481,8 +538,7 @@ function i18nRedirect(from, to) { // Read the HTTP header file in `public/_headers` function readHeaders() { - const header_file = fs - .readFileSync('public/_headers', { encoding: 'utf8' }) + const header_file = readFileSync('public/_headers', { encoding: 'utf8' }) .split('\n') .filter(Boolean); const headers = {}; diff --git a/locales.json b/locales.json index 2fd3c84c6c..a74d969565 100644 --- a/locales.json +++ b/locales.json @@ -13,6 +13,14 @@ }, "zh-cn": { "label": "简体中文", - "lang": "zh-cn" + "lang": "zh-CN" + }, + "ja": { + "label": "日本語", + "lang": "ja" + }, + "ko": { + "label": "한국어", + "lang": "ko" } } diff --git a/lunaria.config.json b/lunaria.config.json index 98a8650313..44c5a5860e 100644 --- a/lunaria.config.json +++ b/lunaria.config.json @@ -3,7 +3,6 @@ "repository": { "name": "tauri-apps/tauri-docs", "branch": "v2", - "rootDir": "src/content/docs", "hosting": "github" }, "files": [ @@ -39,6 +38,14 @@ { "label": "简体中文", "lang": "zh-cn" + }, + { + "label": "日本語", + "lang": "ja" + }, + { + "label": "한국어", + "lang": "ko" } ], "dashboard": { diff --git a/lunaria/components.ts b/lunaria/components.ts index 3e69fafe3c..634fb1701e 100644 --- a/lunaria/components.ts +++ b/lunaria/components.ts @@ -25,7 +25,7 @@ export function TranslationNeedsReview() { diff --git a/src/components/overrides/TableOfContents/TableOfContentsList.astro b/src/components/overrides/TableOfContents/TableOfContentsList.astro deleted file mode 100644 index 655b4b753a..0000000000 --- a/src/components/overrides/TableOfContents/TableOfContentsList.astro +++ /dev/null @@ -1,144 +0,0 @@ ---- -import type { TocItem } from 'node_modules/@astrojs/starlight/utils/generateToC'; - -interface Props { - toc: TocItem[]; - depth?: number; - collapseLevel?: number; - isMobile?: boolean; -} - -const { toc, isMobile = false, depth = 0, collapseLevel = 1 } = Astro.props; ---- - - - - diff --git a/src/components/overrides/TableOfContents/starlight-toc.ts b/src/components/overrides/TableOfContents/starlight-toc.ts deleted file mode 100644 index 2959506a7d..0000000000 --- a/src/components/overrides/TableOfContents/starlight-toc.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { PAGE_TITLE_ID } from 'node_modules/@astrojs/starlight/constants'; - -export class StarlightTOC extends HTMLElement { - private _current = this.querySelector('a[aria-current="true"]'); - private minH = parseInt(this.dataset.minH || '2', 10); - private maxH = parseInt(this.dataset.maxH || '3', 10); - - protected set current(link: HTMLAnchorElement) { - if (link === this._current) return; - if (this._current) this._current.removeAttribute('aria-current'); - link.setAttribute('aria-current', 'true'); - this._current = link; - } - - private onIdle = (cb: IdleRequestCallback) => - (window.requestIdleCallback || ((cb) => setTimeout(cb, 1)))(cb); - - constructor() { - super(); - this.onIdle(() => this.init()); - } - - private init = (): void => { - /** All the links in the table of contents. */ - const links = [...this.querySelectorAll('a')]; - - /** Test if an element is a table-of-contents heading. */ - const isHeading = (el: Element): el is HTMLHeadingElement => { - if (el instanceof HTMLHeadingElement) { - // Special case for page title h1 - if (el.id === PAGE_TITLE_ID) return true; - // Check the heading level is within the user-configured limits for the ToC - const level = el.tagName[1]; - if (level) { - const int = parseInt(level, 10); - if (int >= this.minH && int <= this.maxH) return true; - } - } - return false; - }; - - /** Walk up the DOM to find the nearest heading. */ - const getElementHeading = (el: Element | null): HTMLHeadingElement | null => { - if (!el) return null; - const origin = el; - while (el) { - if (isHeading(el)) return el; - // Assign the previous sibling’s last, most deeply nested child to el. - el = el.previousElementSibling; - while (el?.lastElementChild) { - el = el.lastElementChild; - } - // Look for headings amongst siblings. - const h = getElementHeading(el); - if (h) return h; - } - // Walk back up the parent. - return getElementHeading(origin.parentElement); - }; - - /** Handle intersections and set the current link to the heading for the current intersection. */ - const setCurrent: IntersectionObserverCallback = (entries) => { - for (const { isIntersecting, target } of entries) { - if (!isIntersecting) continue; - const heading = getElementHeading(target); - if (!heading) continue; - const link = links.find((link) => link.hash === '#' + encodeURIComponent(heading.id)); - if (link) { - this.current = link; - break; - } - } - }; - - // Observe elements with an `id` (most likely headings) and their siblings. - // Also observe direct children of `.content` to include elements before - // the first heading. - const toObserve = document.querySelectorAll('main [id], main [id] ~ *, main .content > *'); - - let observer: IntersectionObserver | undefined; - const observe = () => { - if (observer) return; - observer = new IntersectionObserver(setCurrent, { rootMargin: this.getRootMargin() }); - toObserve.forEach((h) => observer!.observe(h)); - }; - observe(); - - let timeout: NodeJS.Timeout; - window.addEventListener('resize', () => { - // Disable intersection observer while window is resizing. - if (observer) observer.disconnect(); - clearTimeout(timeout); - timeout = setTimeout(() => this.onIdle(observe), 200); - }); - }; - - private getRootMargin(): `-${number}px 0% ${number}px` { - const navBarHeight = document.querySelector('header')?.getBoundingClientRect().height || 0; - // `` only exists in mobile ToC, so will fall back to 0 in large viewport component. - const mobileTocHeight = this.querySelector('summary')?.getBoundingClientRect().height || 0; - /** Start intersections at nav height + 2rem padding. */ - const top = navBarHeight + mobileTocHeight + 32; - /** End intersections `53px` later. This is slightly more than the maximum `margin-top` in Markdown content. */ - const bottom = top + 53; - const height = document.documentElement.clientHeight; - return `-${top}px 0% ${bottom - height}px`; - } -} - -customElements.define('tauri-starlight-toc', StarlightTOC); diff --git a/src/components/overrides/ThemeSelect.astro b/src/components/overrides/ThemeSelect.astro index 7a798f77bf..2ee42643a7 100644 --- a/src/components/overrides/ThemeSelect.astro +++ b/src/components/overrides/ThemeSelect.astro @@ -1,5 +1,4 @@ --- -import type { Props } from '@astrojs/starlight/props'; import { Icon } from '@astrojs/starlight/components'; --- diff --git a/src/components/sponsors/GitHub/Sponsors.astro b/src/components/sponsors/GitHub/Sponsors.astro new file mode 100644 index 0000000000..ada58fc673 --- /dev/null +++ b/src/components/sponsors/GitHub/Sponsors.astro @@ -0,0 +1,73 @@ +--- +import { Image } from 'astro:assets'; +import { existsSync, readFileSync } from 'node:fs'; +import { GITHUB_SPONSORS_FILE } from 'packages/fetch-sponsors/config'; +import type { GitHubSponsor } from 'packages/fetch-sponsors/types'; + +let gitHubSponsors = []; +if (existsSync(GITHUB_SPONSORS_FILE)) { + gitHubSponsors = JSON.parse(readFileSync(GITHUB_SPONSORS_FILE, 'utf-8')); +} else { + throw new Error('GitHub sponsors data file not found.'); +} +const gitHubSponsorsLoaded = gitHubSponsors.length > 0; +--- + +{ + gitHubSponsorsLoaded && ( +
+ {gitHubSponsors.map((sponsor: GitHubSponsor) => ( +
+ {sponsor.avatarUrl && ( + + {sponsor.name} + + )} +
+ ))} +
+ ) +} + + diff --git a/src/components/sponsors/OfficialPartners.astro b/src/components/sponsors/OfficialPartners.astro new file mode 100644 index 0000000000..fc5ad2bd0f --- /dev/null +++ b/src/components/sponsors/OfficialPartners.astro @@ -0,0 +1,49 @@ +--- +import { Image } from 'astro:assets'; +import CrabNebulaLight from '@assets/partners/crabnebula/light.svg'; +import CrabNebulaDark from '@assets/partners/crabnebula/dark.svg'; + +type SVG = ((_props: astroHTML.JSX.SVGAttributes) => any) & ImageMetadata; + +interface Partner { + name: string; + image?: ImageMetadata; + // https://docs.astro.build/en/guides/images/#svg-components + svg?: { light: SVG; dark: SVG }; + url: string; + description?: string; +} + +const officialPartners: Partner[] = [ + { + name: 'CrabNebula', + url: 'https://crabnebula.dev/', + svg: { light: CrabNebulaLight, dark: CrabNebulaDark }, + }, +]; +--- + +
+
+ { + officialPartners.map((partner) => ( + + + + )) + } +
+
diff --git a/src/components/sponsors/OpenCollective/Collective.astro b/src/components/sponsors/OpenCollective/Collective.astro new file mode 100644 index 0000000000..6ca3b452e4 --- /dev/null +++ b/src/components/sponsors/OpenCollective/Collective.astro @@ -0,0 +1,116 @@ +--- +import { existsSync, readFileSync } from 'node:fs'; +import { OPEN_COLLECTIVE_FILE } from 'packages/fetch-sponsors/config'; +import { type OpenCollectiveSponsor as Sponsor } from 'packages/fetch-sponsors/types'; + +import OcAvatar from './OcAvatar.astro'; + +let openCollectiveSponsors = []; +if (existsSync(OPEN_COLLECTIVE_FILE)) { + openCollectiveSponsors = JSON.parse(readFileSync(OPEN_COLLECTIVE_FILE, 'utf-8')); +} else { + throw new Error('Open Collective data file not found.'); +} + +const sponsorsByTier = { + platinum: openCollectiveSponsors.filter((sponsor: Sponsor) => sponsor.tier === 'platinum'), + gold: openCollectiveSponsors.filter((sponsor: Sponsor) => sponsor.tier === 'gold'), + silver: openCollectiveSponsors.filter((sponsor: Sponsor) => sponsor.tier === 'silver'), + bronze: openCollectiveSponsors.filter((sponsor: Sponsor) => sponsor.tier === 'bronze'), +}; + +const platinumSponsors = sponsorsByTier.platinum; +const goldSponsors = sponsorsByTier.gold; +const silverSponsors = sponsorsByTier.silver; + +// disabled +// const bronzeSponsors = sponsorsByTier.bronze +// .filter((sponsor: Sponsor) => sponsor.name !== 'Incognito') +// .slice(0, 50); +// const totalBronzeSponsors = sponsorsByTier.bronze.length; + +const sponsorTiers = [ + { title: 'Platinum', name: 'platinum', sponsors: platinumSponsors }, + { title: 'Gold', name: 'gold', sponsors: goldSponsors }, + { title: 'Silver', name: 'silver', sponsors: silverSponsors }, +]; +--- + +<> + { + sponsorTiers.map((tier) => ( +
+ {/*

{tier.title}

*/} + {tier.sponsors.length > 0 && ( +
+ {tier.sponsors.map((sponsor: Sponsor) => ( +
+ +
+ ))} +
+ )} +
+ )) + } + + + + + diff --git a/src/components/sponsors/OpenCollective/OcAvatar.astro b/src/components/sponsors/OpenCollective/OcAvatar.astro new file mode 100644 index 0000000000..7c7d5a0a0c --- /dev/null +++ b/src/components/sponsors/OpenCollective/OcAvatar.astro @@ -0,0 +1,143 @@ +--- +import { Image } from 'astro:assets'; +import { OC_IMAGE_DIMENSION } from 'packages/fetch-sponsors/config'; +import { type OpenCollectiveSponsor as Sponsor } from 'packages/fetch-sponsors/types'; +import fallbackImage from 'src/assets/fallback.jpg'; + +interface Props { + sponsor: Sponsor; + needComma?: boolean; +} + +const { sponsor, needComma } = Astro.props; + +const roundingStyle: Record = { + ORGANIZATION: 'rounded-lg', + INDIVIDUAL: 'rounded-full', +}; + +function getUrl(sponsor: Sponsor): string { + return `${sponsor.socialLinks?.website ?? sponsor.profileUrl}?ref=tauri.app&utm_source=tauri.app`; +} + +const res = await fetch(sponsor.avatarUrl, { method: 'HEAD' }); +if (res && !res.ok) { + sponsor.avatarUrl = fallbackImage.src; +} +--- + +{ + sponsor.tier === 'platinum' && ( + + ) +} + +{ + (sponsor.tier === 'gold' || sponsor.tier === 'silver') && ( +
+ + {sponsor.name} + +
+ ) +} + +{ + sponsor.tier === 'bronze' && ( + <> + + {sponsor.name} + + {needComma && , } + + ) +} + + diff --git a/src/components/sponsors/Partners.astro b/src/components/sponsors/Partners.astro new file mode 100644 index 0000000000..800e1df284 --- /dev/null +++ b/src/components/sponsors/Partners.astro @@ -0,0 +1,51 @@ +--- +import { Image } from 'astro:assets'; +import NetlifyLight from '@assets/partners/netlify/light.svg'; +import NetlifyDark from '@assets/partners/netlify/dark.svg'; +import MeiliSearchLight from '@assets/partners/meilisearch/light.svg'; +import MeiliSearchDark from '@assets/partners/meilisearch/dark.svg'; + +type SVG = ((_props: astroHTML.JSX.SVGAttributes) => any) & ImageMetadata; + +interface Partner { + name: string; + image?: ImageMetadata; + // https://docs.astro.build/en/guides/images/#svg-components + svg?: { light: SVG; dark: SVG }; + url: string; + description?: string; +} + +const partners: Partner[] = [ + { + name: 'Meilisearch', + url: 'https://www.meilisearch.com/', + svg: { light: MeiliSearchLight, dark: MeiliSearchDark }, + }, + { + name: 'Netlify', + url: 'https://netlify.com/', + svg: { light: NetlifyLight, dark: NetlifyDark }, + }, +]; +--- + +
+
+ { + partners.map((partner) => ( + + + + )) + } +
+
diff --git a/src/components/sponsors/SponsorList.astro b/src/components/sponsors/SponsorList.astro new file mode 100644 index 0000000000..c305d2df1c --- /dev/null +++ b/src/components/sponsors/SponsorList.astro @@ -0,0 +1,64 @@ +--- +import OpenCollective from './OpenCollective/Collective.astro'; +import GitHubSponsor from './GitHub/Sponsors.astro'; +import Partners from './Partners.astro'; +import OfficialPartners from './OfficialPartners.astro'; +--- + +
+
+
+

Supported by

+ +
+
+

Open Collective Sponsors

+ +
+
+

GitHub Sponsors

+ +
+
+ +
+

Website powered by

+ +
+
+ + diff --git a/src/content.config.ts b/src/content.config.ts new file mode 100644 index 0000000000..3912141897 --- /dev/null +++ b/src/content.config.ts @@ -0,0 +1,15 @@ +import { defineCollection } from 'astro:content'; +import { i18nSchema, docsSchema } from '@astrojs/starlight/schema'; +import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders'; +import { topicSchema } from 'starlight-sidebar-topics/schema'; +import { blogSchema } from 'starlight-blog/schema'; + +export const collections = { + docs: defineCollection({ + loader: docsLoader(), + schema: docsSchema({ + extend: (context) => blogSchema(context).merge(topicSchema), + }), + }), + i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }), +}; diff --git a/src/content/config.ts b/src/content/config.ts deleted file mode 100644 index da3de68edf..0000000000 --- a/src/content/config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { defineCollection } from 'astro:content'; -import { i18nSchema } from '@astrojs/starlight/schema'; -import { docsSchema } from 'src/schemas/docsSchema'; - -export const collections = { - docs: defineCollection({ - schema: docsSchema, - }), - i18n: defineCollection({ type: 'data', schema: i18nSchema() }), -}; diff --git a/src/content/docs/404.md b/src/content/docs/404.md index ce8f1b4743..23668155c3 100644 --- a/src/content/docs/404.md +++ b/src/content/docs/404.md @@ -1,5 +1,6 @@ --- title: '404' +topic: guides # this sidebar is active when viewing this page template: doc editUrl: false tableOfContents: false diff --git a/src/content/docs/_fragments/cta.mdx b/src/content/docs/_fragments/cta.mdx index b2f7167b07..a92c8f424f 100644 --- a/src/content/docs/_fragments/cta.mdx +++ b/src/content/docs/_fragments/cta.mdx @@ -1,3 +1,7 @@ +--- +title: 'Create Tauri app' +--- + import { Tabs, TabItem } from '@astrojs/starlight/components'; @@ -11,6 +15,11 @@ sh <(curl https://create.tauri.app/sh) irm https://create.tauri.app/ps | iex ``` + +```sh frame=none +sh (curl -sSL https://create.tauri.app/sh | psub) +``` + ```sh frame=none npm create tauri-app@latest diff --git a/src/content/docs/blog/create-tauri-app-version-3-released.md b/src/content/docs/blog/create-tauri-app-version-3-released.md index 2f1339072d..00bc284fd5 100644 --- a/src/content/docs/blog/create-tauri-app-version-3-released.md +++ b/src/content/docs/blog/create-tauri-app-version-3-released.md @@ -4,10 +4,6 @@ date: 2023-03-01 authors: [amrbashir] excerpt: create-tauri-app Version 3 is released with support for alpha versions of Tauri, mobile project support and DX improvements image: ./create-tauri-app-version-3-released/header.jpg -banner: - content: | - You're reading the blog on the prerelease site for Tauri 2.0 - - Go to the Tauri 1.0 site --- ![hero image](./create-tauri-app-version-3-released/header.jpg) diff --git a/src/content/docs/blog/cve-2024-24576.md b/src/content/docs/blog/cve-2024-24576.md index 153e07f55e..21a44dca94 100644 --- a/src/content/docs/blog/cve-2024-24576.md +++ b/src/content/docs/blog/cve-2024-24576.md @@ -3,10 +3,6 @@ title: Rust Security Advisory CVE-2024-24576 date: 2024-04-10 authors: [tweidinger, chip] excerpt: Recent Rust Security Advisory CVE-2024-24576. -banner: - content: | - You're reading the blog on the prerelease site for Tauri 2.0 - - Go to the Tauri 1.0 site --- The Rust Security Response WG announced [`CVE-2024-24576`](https://blog.rust-lang.org/2024/04/09/cve-2024-24576.html), which affects the Rust Standard Library on Windows. diff --git a/src/content/docs/blog/partnership-crabnebula.md b/src/content/docs/blog/partnership-crabnebula.md index adc305bfa3..d5d4a4c763 100644 --- a/src/content/docs/blog/partnership-crabnebula.md +++ b/src/content/docs/blog/partnership-crabnebula.md @@ -3,10 +3,6 @@ title: 'Strengthening Tauri: Our Partnership with CrabNebula' date: 2023-11-13 authors: [nothingismagick] excerpt: "As an open-source project, Tauri's primary mission has always been to provide a secure, efficient framework for multi-platform application development. Understanding the concerns and needs of our community, we are excited to share insights into our partnership with CrabNebula and how it bolsters the stability and future of Tauri." -banner: - content: | - You're reading the blog on the prerelease site for Tauri 2.0 - - Go to the Tauri 1.0 site --- ![Hero Image](./partnership-crabnebula/header.png) diff --git a/src/content/docs/blog/roadmap-to-tauri-2-0.md b/src/content/docs/blog/roadmap-to-tauri-2-0.md index 2d27802941..60e84a399a 100644 --- a/src/content/docs/blog/roadmap-to-tauri-2-0.md +++ b/src/content/docs/blog/roadmap-to-tauri-2-0.md @@ -3,10 +3,6 @@ title: Roadmap to Tauri 2.0 date: 2023-09-07 authors: [lorenzolewis] excerpt: 'Tauri 1.0 was released in June 2022 and introduced an app toolkit for developers to build apps using HTML, CSS, and JavaScript with the security and performance of Rust.' -banner: - content: | - You're reading the blog on the prerelease site for Tauri 2.0 - - Go to the Tauri 1.0 site --- ![Hero Image](./roadmap-to-tauri-2-0/header.png) diff --git a/src/content/docs/blog/tauri-1-0.md b/src/content/docs/blog/tauri-1-0.md index 1dcb71ce94..faf3da7f70 100644 --- a/src/content/docs/blog/tauri-1-0.md +++ b/src/content/docs/blog/tauri-1-0.md @@ -3,10 +3,6 @@ title: Tauri 1.0 Release date: 2022-06-19 authors: [nothingismagick] excerpt: After 9 months of betas and 4 months of release candidates, Tauri version 1.0 is now available! -banner: - content: | - You're reading the blog on the prerelease site for Tauri 2.0 - - Go to the Tauri 1.0 site --- ![Tauri 1.0 Launch Hero Image](./tauri_1_0_images/header.png) @@ -64,17 +60,17 @@ To illustrate this, we compiled some numbers on the ecological impact of your ap
-| App Size | Unit Time (100Mb/s) | Downloads | Transit | Total Time (100Mb/s) | Electricity Use (kWh) | CO2 Produced (Ton) | Trees Needed 🌳 | -| -------- | ------------------- | ---------- | ------- | -------------------- | --------------------- | ------------------ | --------------- | -| 3 MB | 240 milliseconds | 1,000 | 3 GB | 24 minutes | 0.3 | 0.18 | 1 | -| 3 MB | 240 milliseconds | 100,000 | 300 GB | 1.7 days | 30 | 18 | 108 | -| 3 MB | 240 milliseconds | 10,000,000 | 30 TB | 167 days | 3,000 | 1,800 | 10,800 | -| 200 MB | 16 seconds | 1,000 | 200 GB | 4.45 hours | 20 | 12 | 72 | -| 200 MB | 16 seconds | 100,000 | 20 TB | 18.5 days | 2,000 | 1,200 | 7,200 | -| 200 MB | 16 seconds | 10,000,000 | 2 PB | 5 years | 200,000 | 120,000 | 720,000 | -| 600 MB | 48 seconds | 1,000 | 0.6 TB | 13 hours | 60 | 36 | 216 | -| 600 MB | 48 seconds | 100,000 | 60 TB | 54.2 days | 6,000 | 3,600 | 21,600 | -| 600 MB | 48 seconds | 10,000,000 | 6 PB | 14.8 years | 600,000 | 360,000 | 2,160,000 | +| App Size | Unit Time (100Mb/s) | Downloads | Transit | Total Time (100Mb/s) | Electricity Use (kWh) | CO2 Produced (kg) | Trees Needed 🌳 | +| -------- | ------------------- | ---------- | ------- | -------------------- | --------------------- | ----------------- | --------------- | +| 3 MB | 240 milliseconds | 1,000 | 3 GB | 24 minutes | 0.3 | 0.18 | 1 | +| 3 MB | 240 milliseconds | 100,000 | 300 GB | 1.7 days | 30 | 18 | 1 | +| 3 MB | 240 milliseconds | 10,000,000 | 30 TB | 167 days | 3,000 | 1,800 | 11 | +| 200 MB | 16 seconds | 1,000 | 200 GB | 4.45 hours | 20 | 12 | 1 | +| 200 MB | 16 seconds | 100,000 | 20 TB | 18.5 days | 2,000 | 1,200 | 7 | +| 200 MB | 16 seconds | 10,000,000 | 2 PB | 5 years | 200,000 | 120,000 | 720 | +| 600 MB | 48 seconds | 1,000 | 0.6 TB | 13 hours | 60 | 36 | 1 | +| 600 MB | 48 seconds | 100,000 | 60 TB | 54.2 days | 6,000 | 3,600 | 22 | +| 600 MB | 48 seconds | 10,000,000 | 6 PB | 14.8 years | 600,000 | 360,000 | 2,160 |
diff --git a/src/content/docs/blog/tauri-2-0-0-alpha-3.md b/src/content/docs/blog/tauri-2-0-0-alpha-3.md index 59417df90a..70b51749a1 100644 --- a/src/content/docs/blog/tauri-2-0-0-alpha-3.md +++ b/src/content/docs/blog/tauri-2-0-0-alpha-3.md @@ -3,10 +3,6 @@ title: Migration to webkit2gtk-4.1 on Linux port date: 2023-02-03 authors: [wusyong] excerpt: New v2.0 alpha released and new backend for Linux port -banner: - content: | - You're reading the blog on the prerelease site for Tauri 2.0 - - Go to the Tauri 1.0 site --- Hello everybody! We just released [Tauri v2.0.0-alpha3](https://github.com/tauri-apps/tauri/releases/tag/tauri-v2.0.0-alpha.3) recently. While it doesn't bring any major feature, it does bring some huge impacts on Linux port. diff --git a/src/content/docs/blog/tauri-2-0-0-beta.md b/src/content/docs/blog/tauri-2-0-0-beta.md index 0249a3adb6..9c36f7d246 100644 --- a/src/content/docs/blog/tauri-2-0-0-beta.md +++ b/src/content/docs/blog/tauri-2-0-0-beta.md @@ -3,10 +3,6 @@ title: Announcing the Tauri v2 Beta Release date: 2024-02-02 authors: [lucasfernog] excerpt: Tauri v2 is ready to take the next step towards being stable! 2.0.0-beta.0 has been published. -banner: - content: | - You're reading the blog on the prerelease site for Tauri 2.0 - - Go to the Tauri 1.0 site --- ![Hero Image](./tauri_2_0_0_alpha_0/header.png) diff --git a/src/content/docs/blog/tauri-board-elections-2024.md b/src/content/docs/blog/tauri-board-elections-2024.md index 79c25a228f..e842c01898 100644 --- a/src/content/docs/blog/tauri-board-elections-2024.md +++ b/src/content/docs/blog/tauri-board-elections-2024.md @@ -2,11 +2,7 @@ title: Tauri Board Elections 2024 date: 2024-06-28 authors: [jbolda] -excerpt: The Tauri Programme is celebrating it's third anniversary of Tauri becoming a programme within The Commons Conservancy. We are hard at work bringing v2 to a stable release, and now the next round of Tauri Board Director elections is upon us! -banner: - content: | - You're reading the blog on the prerelease site for Tauri 2.0 - - Go to the Tauri 1.0 site +excerpt: The Tauri Programme is celebrating its third anniversary of Tauri becoming a programme within The Commons Conservancy. We are hard at work bringing v2 to a stable release, and now the next round of Tauri Board Director elections is upon us! --- The Tauri Programme is celebrating its third anniversary of Tauri becoming a programme within [The Commons Conservancy](https://commonsconservancy.org/). We are hard at work bringing v2 to a stable release, and now the next round of Tauri Board Director elections is upon us! Want to [get involved in other ways](#interested-in-getting-involved) and help Tauri towards v2? We would love your contributions especially to help evolve the documentation! diff --git a/src/content/docs/blog/tauri-board-elections-2025.md b/src/content/docs/blog/tauri-board-elections-2025.md new file mode 100644 index 0000000000..7018bd00d8 --- /dev/null +++ b/src/content/docs/blog/tauri-board-elections-2025.md @@ -0,0 +1,38 @@ +--- +title: Tauri Board Elections 2025 +date: 2025-06-30 +authors: [beanow] +excerpt: As we continue to be amazed with all the applications you've created with Tauri v2, it's been 4 years that Tauri has become a Programme within The Commons Conservancy! This means we're preparing for a new round of Tauri Board Director elections for the next term. +--- + +As we continue to be amazed by all the applications you've created with Tauri v2, it's been 4 years since Tauri has become a Programme within [The Commons Conservancy](https://commonsconservancy.org/)! This means we're preparing for a new round of Tauri Board Director elections for the next term. + +## Board Elections + +The Tauri Board of Directors is the central decision-making body for the Tauri Programme and is responsible for its overall health and stability. Additional details can be found at the [Tauri Governance page](/about/governance/). + +In order to provide continuity from one year to another, the elections of seats are staggered over the course of 2 years. This means that one year a portion of the seats are elected, and the following year the remaining seats are elected. A Tauri Director seat is an elected position with a term of 2 years. The Board has a minimum of 3 Directors and a maximum of 7. + +This year there are 5 seats open for election. + +### Applying for Candidacy + +There are 3 steps to express interest and apply for candidacy: + +1. Learn about the role of a Tauri Board Director on the [Governance page](/about/governance/#tauri-board--board-directors). +2. Prepare a written introduction about yourself that covers who you are, your history and relevance to Tauri, and what you would like to bring to the Board. (Examples from previous years can be found at https://github.com/tauri-apps/governance-and-guidance). +3. **Apply prior to July 7th, 2025** by emailing [board@tauri.app](mailto:board@tauri.app) or messaging the `@board` role on the [Tauri Discord](https://discord.com/invite/tauri). + +Voting will take place starting on July 7th through July 14th, 2025 where Tauri Working Group Members will cast their votes. We're expecting to announce the results on or before July 19, 2025. If elected, we'll ask you to sign [this pledge](https://dracc.commonsconservancy.org/0016/) if you haven't done so previously. + +If you have any questions or would like more information please reach out by emailing [board@tauri.app](mailto:board@tauri.app), messaging the `@board` role on the [Tauri Discord](https://discord.com/invite/tauri). + +## Interested In Getting Involved? + +If joining the Board isn't for you but still want to help, here are some ways to do so! (Thank you ❤️) + +Reach out on our [Discord](https://discord.com/invite/tauri) by enabling the roles you're interested in like "Contribute to Tauri Code" or "Contribute to Documentation". This reveals the Contributors channels where you can chat with other contributors. While you're there, consider enabling Discord notification roles to stay apprised of news and questions from the team. + +Or on GitHub maybe you can help with these [good first issues](https://github.com/search?q=user%3Atauri-apps+label%3A"good+first+issue"+state%3Aopen&type=Issues&s=created&o=desc)? + +Additionally we're very grateful to all the teams and individuals who [sponsor us on GitHub](https://github.com/sponsors/tauri-apps) or [open collective](https://opencollective.com/tauri)! diff --git a/src/content/docs/blog/tauri-board-elections-and-governance-updates.md b/src/content/docs/blog/tauri-board-elections-and-governance-updates.md index 0b2b3a45e2..985cea2ad8 100644 --- a/src/content/docs/blog/tauri-board-elections-and-governance-updates.md +++ b/src/content/docs/blog/tauri-board-elections-and-governance-updates.md @@ -3,10 +3,6 @@ title: Tauri Board Elections & Governance Update date: 2023-06-15 authors: [beanow, jbolda, lorenzolewis] excerpt: The Tauri Programme is celebrating it's two year anniversary of Tauri becoming a programme within The Commons Conservancy as well as the one year milestone of the Tauri 1.0 release. This also means we're preparing for the next round of Tauri Board Director elections to welcome in the next chapter of Tauri. -banner: - content: | - You're reading the blog on the prerelease site for Tauri 2.0 - - Go to the Tauri 1.0 site --- The Tauri Programme is celebrating it's two year anniversary of Tauri becoming a programme within [The Commons Conservancy](https://commonsconservancy.org/) as well as the one year milestone of the [Tauri 1.0 release](/blog/tauri-1-0/). This also means we're preparing for the next round of Tauri Board Director elections to welcome in the next chapter of Tauri. diff --git a/src/content/docs/blog/tauri-community-growth-and-feedback.md b/src/content/docs/blog/tauri-community-growth-and-feedback.md index 7ac95876a3..da6462d21e 100644 --- a/src/content/docs/blog/tauri-community-growth-and-feedback.md +++ b/src/content/docs/blog/tauri-community-growth-and-feedback.md @@ -4,10 +4,6 @@ date: 2023-02-09 authors: [lorenzolewis, amrbashir] excerpt: Tauri Community Survey results and search improvements image: ./tauri_community_growth_and_feedback/header.jpg -banner: - content: | - You're reading the blog on the prerelease site for Tauri 2.0 - - Go to the Tauri 1.0 site --- ![Community growth and feedback hero image](./tauri_community_growth_and_feedback/header.jpg) diff --git a/src/content/docs/blog/tauri-egui-0-1.md b/src/content/docs/blog/tauri-egui-0-1.md index 568c2d79c1..d6c12aca9a 100644 --- a/src/content/docs/blog/tauri-egui-0-1.md +++ b/src/content/docs/blog/tauri-egui-0-1.md @@ -3,10 +3,6 @@ title: Announcing tauri-egui 0.1.0 date: 2022-09-19 authors: [lucasfernog] excerpt: The Tauri team is happy to announce the tauri-egui 0.1.0 release. -banner: - content: | - You're reading the blog on the prerelease site for Tauri 2.0 - - Go to the Tauri 1.0 site --- The Tauri team is pleased to announce the first release of [tauri-egui](https://github.com/tauri-apps/tauri-egui). diff --git a/src/content/docs/blog/tauri-verso-integration.md b/src/content/docs/blog/tauri-verso-integration.md new file mode 100644 index 0000000000..423491caf8 --- /dev/null +++ b/src/content/docs/blog/tauri-verso-integration.md @@ -0,0 +1,111 @@ +--- +title: Experimental Tauri Verso Integration +date: 2025-03-17 +authors: [tony] +excerpt: The first look of the integration with Verso, a browser based on Servo +--- + +## What is Verso? + +So first off, what is `Verso`? [`Verso`](https://github.com/versotile-org/verso) is a browser based on [`Servo`](https://servo.org/), a web browser rendering engine written in Rust + +## Why using Verso instead of Servo directly? + +I believe there're quite a lot of people having thought about using Servo but got intimidated by the complex APIs and just gave up, which frankly I was one of them, so the goal of building the Verso webview is to make it easy enough to understand and use so that people will actually start to experiment and use it + +Servo itself is made to be relatively easy to embed compared to other browsers, but the APIs are still way too low level and it's quite daunting to use, you can take a look at the minimal example for running Servo with Winit at (note this is not even a fully functional example): https://github.com/servo/servo/blob/8d39d7706aee50971e848a5e31fc6bfd7ef552c1/components/servo/examples/winit_minimal.rs + +And compared to that, Verso's API looks like this, which is much easier and ergonomic to use + +```rust +use std::env::current_exe; +use std::thread::sleep; +use std::time::Duration; +use url::Url; +use verso::VersoBuilder; + +fn main() { + let versoview_path = current_exe().unwrap().parent().unwrap().join("versoview"); + let controller = VersoBuilder::new() + .with_panel(true) + .maximized(true) + .build(versoview_path, Url::parse("https://example.com").unwrap()); + loop { + sleep(Duration::MAX); + } +} +``` + +> https://github.com/versotile-org/verso/blob/2e853d4f3f4cb88274daa211b7a2eb3bd1517115/verso/src/main.rs + +It's not to say Servo's API is bad though, as they need to support a lot more use cases while we just need it for building applications with Tauri + +## `tauri-runtime-verso` + +So let's talk about the integration with Tauri! + +We choose to integrate Verso and Tauri through a new custom runtime [`tauri-runtime-verso`](https://github.com/versotile-org/tauri-runtime-verso) for this time, this is similar to our default runtime `tauri-runtime-wry`. + +With this approach, you can easily swap out the runtime and use Tauri like what you'll normally do: + +```rust +use tauri_runtime_verso::{ + INVOKE_SYSTEM_SCRIPTS, VersoRuntime, set_verso_path, set_verso_resource_directory, +}; + +fn main() { + // You need to set this to the path of the versoview executable + // before creating any of the webview windows + set_verso_path("../verso/target/debug/versoview"); + // Set this to verso/servo's resources directory before creating any of the webview windows + // this is optional but recommended, this directory will include very important things + // like user agent stylesheet + set_verso_resource_directory("../verso/resources"); + tauri::Builder::::new() + // Make sure to do this or some of the commands will not work + .invoke_system(INVOKE_SYSTEM_SCRIPTS.to_owned()) + .run(tauri::generate_context!()) + .unwrap(); +} +``` + +Just note that it's not as feature rich and powerful as the current backends used by Tauri in production yet, but it still has a lot to it, and we have built an example show casing it at https://github.com/versotile-org/tauri-runtime-verso/tree/main/examples/api + + + +#### Features you can see from the video: + +- We have all the functions the `tauri-cli` provides +- We're using a modern framework, in this case [`React`](https://react.dev/) +- We have our official log and opener plugins, they work exactly the same as if you're using Tauri with the other backends +- Windowing functions work, including size, position, maximize, minimize, close, ... +- [`Vite`](https://vitejs.dev/)'s css hot reload works as well +- The `data-tauri-drag-region` attribute works + +## Future works + +Right now, Verso and `tauri-runtime-verso` are still in active development so we'll need to see as we go, but we do have something planned to do next + +### Pre-built Verso executable + +Releasing an easy to use pre-built Verso executable to help people get started with it quicker and easier, as currently you need to compile Verso yourself to get started + +Also if possible, as a long term goal, we would like an evergreen shared Verso, similar to WebView2 on Windows which you would place it on the system and it would update itself automatically, and shared between multiple apps so you don't have to ship the browser inside your app to reduce the bundle size significantly + +### More windowing and webview features support + +We currently only support a small subset of features in Tauri, and we would like to expand this to include more things, and we have currently planned to support window decorations, window titles and transparency + +### Initialization script without temporary files + +Currently Servo can only take an userscript directory to run on document start which is ok but for the Tauri's use case, we would like to do this programmatically without the help of files, as that could result in left over temporary files that we never clean up + +We have a [PR](https://github.com/servo/servo/pull/35388) merged in Servo just a few days ago and we should just need to use in Verso and then the `tarui-runtime-verso` so this is a coming soon! + +### Customization unique to the Verso runtime + +Tauri is largely made with the assumption of the underlying webview libraries, so there're very little ways to use many Verso specific futures right now, for example, setting the verso executable path and resources directory are being done through global variables, which is not really applicable to window specific features (for example setting rounded corners), so we would like to add support for that next + +## Thank you + +At the end we want to thank [NLNet](https://nlnet.nl/) for making this project possible by supporting it financially through grants! diff --git a/src/content/docs/concept/Inter-Process Communication/brownfield.md b/src/content/docs/concept/Inter-Process Communication/brownfield.md index 43ca055259..8917470161 100644 --- a/src/content/docs/concept/Inter-Process Communication/brownfield.md +++ b/src/content/docs/concept/Inter-Process Communication/brownfield.md @@ -1,5 +1,6 @@ --- title: Brownfield Pattern +i18nReady: true --- _**This is the default pattern.**_ @@ -15,13 +16,15 @@ legacy systems. ## Configuration Because the Brownfield pattern is the default pattern, it doesn't require a configuration option to be set. To explicitly set -it, you can use the `tauri > pattern` object in the `tauri.conf.json` configuration file. +it, you can use the `app > security > pattern` object in the `tauri.conf.json` configuration file. ```json { - "tauri": { - "pattern": { - "use": "brownfield" + "app": { + "security": { + "pattern": { + "use": "brownfield" + } } } } diff --git a/src/content/docs/concept/Inter-Process Communication/index.mdx b/src/content/docs/concept/Inter-Process Communication/index.mdx index d8255f5c07..3117111cdf 100644 --- a/src/content/docs/concept/Inter-Process Communication/index.mdx +++ b/src/content/docs/concept/Inter-Process Communication/index.mdx @@ -3,13 +3,14 @@ title: Inter-Process Communication sidebar: label: Overview order: 1 +i18nReady: true --- import { CardGrid, LinkCard } from '@astrojs/starlight/components'; Inter-Process Communication (IPC) allows isolated processes to communicate securely and is key to building more complex applications. -Learn more above the specific IPC patterns in the following guides: +Learn more about the specific IPC patterns in the following guides: + ```toml # src-tauri/Cargo.toml [profile.dev] @@ -27,11 +29,12 @@ lto = true # Enables link-time-optimizations. opt-level = "s" # Prioritizes small binary size. Use `3` if you prefer speed. panic = "abort" # Higher performance by disabling panic handlers. strip = true # Ensures debug symbols are removed. +``` -```` + ```toml # src-tauri/Cargo.toml [profile.dev] @@ -46,7 +49,7 @@ panic = "abort" # Higher performance by disabling panic handlers. strip = true # Ensures debug symbols are removed. trim-paths = "all" # Removes potentially privileged information from your binaries. rustflags = ["-Cdebuginfo=0", "-Zthreads=8"] # Better compile performance. -```` +``` @@ -68,3 +71,43 @@ This is not a complete reference over all available options, merely the ones tha - [rustflags:](https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#profile-rustflags-option) Sets Rust compiler flags on a profile by profile basis. - `-Cdebuginfo=0`: Whether debuginfo symbols should be included in the build. - `-Zthreads=8`: Increases the number of threads used during compilation. + +## Remove Unused Commands + +In Pull Request [`feat: add a new option to remove unused commands`](https://github.com/tauri-apps/tauri/pull/12890), we added in a new option in the tauri config file + +```json title=tauri.conf.json +{ + "build": { + "removeUnusedCommands": true + } +} +``` + +to remove commands that're never allowed in your capability files (ACL), so you don't have to pay for what you don't use + +:::tip +To maximize the benefit of this, only include commands that you use in the ACL instead of using `defaults`s +::: + +:::note +This feature requires `tauri@2.4`, `tauri-build@2.1`, `tauri-plugin@2.1` and `tauri-cli@2.4` +::: + +:::note +This won't be accounting for dynamically added ACLs at runtime so make sure to check it when using this +::: + +
+How does it work under the hood? + +`tauri-cli` will communicate with `tauri-build` and the build script of `tauri`, `tauri-plugin` through an environment variable +and let them generate a list of allowed commands from the ACL, +this will then be used by the `generate_handler` macro to remove unused commands based on that + +An internal detail is this environment variable is currently `REMOVE_UNUSED_COMMANDS`, +and it's set to project's directory, usually the `src-tauri` directory, this is used for the build scripts to find the capability files, +and although it's not encouraged, you can still set this environment variable yourself if you can't or don't want to use `tauri-cli` to get this to work +(**do note that as this is an implementation detail, we don't guarantee the stability of it**) + +
diff --git a/src/content/docs/contribute/index.mdx b/src/content/docs/contribute/index.mdx new file mode 100644 index 0000000000..e7df35601b --- /dev/null +++ b/src/content/docs/contribute/index.mdx @@ -0,0 +1,24 @@ +--- +title: Contribute +topic: guides # this sidebar is active when viewing this page +description: Guide for Tauri contributors +sidebar: + order: 0 + label: Overview + badge: + text: New + variant: tip +--- + +We, the maintainers, are really excited that you are interested in contributing to Tauri. We welcome contributors of any skill level and are happy to provide guidance on PRs. +In case of any doubts you can reach out to us on [our Discord server](https://discord.gg/SpmNs4S). + +### Project repositories + +Main Tauri repositories you can contribute to are: + +- The [core Tauri](https://github.com/tauri-apps/tauri/) repository containing the Tauri runtime, build tools, macros and utils. +- [Plugins workspace](https://github.com/tauri-apps/plugins-workspace) repository with all the official Tauri plugins +- [Tauri Docs](https://github.com/tauri-apps/tauri-docs) repository containing this website + +Each of those Tauri repositories contains a `.github/CONTRIBUTING.md` file. In it you will find instructions on how to set up local development environment and submit a Pull Request. diff --git a/src/content/docs/develop/Debug/crabnebula-devtools.mdx b/src/content/docs/develop/Debug/crabnebula-devtools.mdx index d44f56ce9e..1e6472d1cd 100644 --- a/src/content/docs/develop/Debug/crabnebula-devtools.mdx +++ b/src/content/docs/develop/Debug/crabnebula-devtools.mdx @@ -4,8 +4,12 @@ sidebar: badge: text: New variant: tip +i18nReady: true --- +import { Image } from 'astro:assets'; +import devToolsPrint from '@assets/develop/Debug/crabnebula-devtools.png'; + [CrabNebula](https://crabnebula.dev/) provides a free [DevTools](https://crabnebula.dev/devtools/) application for Tauri as part of its partnership with the Tauri project. This application allows you to instrument your Tauri app by capturing its embedded assets, Tauri configuration file, logs and spans and providing a web frontend to seamlessly visualize data in real time. With the CrabNebula DevTools you can inspect your app's log events (including logs from dependencies), track down the performance of your command calls and overall Tauri API usage, with a special interface for Tauri events and commands, including payload, responses and inner logs and execution spans. @@ -20,19 +24,27 @@ And initialize the plugin as soon as possible in your main function: ```rust fn main() { - #[cfg(debug_assertions)] - let devtools = tauri_plugin_devtools::init(); // initialize the plugin as early as possible + // This should be called as early in the execution of the app as possible + #[cfg(debug_assertions)] // only enable instrumentation in development builds + let devtools = tauri_plugin_devtools::init(); let mut builder = tauri::Builder::default(); #[cfg(debug_assertions)] - builder = builder.plugin(devtools); // then register it with Tauri + { + builder = builder.plugin(devtools); + } - builder.run(tauri::generate_context!()) + builder + .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` +And then run your app as usual, if everything is set up correctly devtools will print the following message: + +DevTools message on terminal + :::note In this case we only initialize the devtools plugin for debug applications, which is recommended. ::: diff --git a/src/content/docs/develop/Debug/index.mdx b/src/content/docs/develop/Debug/index.mdx index 2229b8bf3f..7ec146b159 100644 --- a/src/content/docs/develop/Debug/index.mdx +++ b/src/content/docs/develop/Debug/index.mdx @@ -12,7 +12,7 @@ With all the moving pieces in Tauri, you may run into a problem that requires de ## Development Only Code -One of the most useful tools in your toolkit for debugging is the ability to add debugging statements in your code. However, you generally you don't want these to end up in production, which is where the ability to check whether you're running in development mode or not comes in handy. +One of the most useful tools in your toolkit for debugging is the ability to add debugging statements in your code. However, you generally don't want these to end up in production, which is where the ability to check whether you're running in development mode or not comes in handy. ### In Rust @@ -118,6 +118,7 @@ To create a debug build, run the `tauri build --debug` command. yarn="yarn tauri build --debug" pnpm="pnpm tauri build --debug" deno="deno task tauri build --debug" + bun="bun tauri build --debug" cargo="cargo tauri build --debug" /> diff --git a/src/content/docs/develop/Debug/neovim.mdx b/src/content/docs/develop/Debug/neovim.mdx new file mode 100644 index 0000000000..9af65f9e4a --- /dev/null +++ b/src/content/docs/develop/Debug/neovim.mdx @@ -0,0 +1,127 @@ +--- +title: Debug in Neovim +i18nReady: true +--- + +There are many different plugins that can be used to debug Rust code in Neovim. This guide will show you how to set up `nvim-dap` and some additional plugins to debug Tauri application. + +### Prerequisites + +`nvim-dap` extension requires `codelldb` binary. Download the version for your system from https://github.com/vadimcn/codelldb/releases and unzip it. We will point to it later in the `nvim-dap` configuration. + +### Configuring nvim-dap + +Install [`nvim-dap`](https://github.com/mfussenegger/nvim-dap) and [`nvim-dap-ui`](https://github.com/rcarriga/nvim-dap-ui) plugins. Follow the instructions provided on their github pages or simply use your favourite plugin manager. +Note that `nvim-dap-ui` requires `nvim-nio` plugin. + +Next, setup the plugin in your Neovim configuration: + +```lua title="init.lua" +local dap = require("dap") + +dap.adapters.codelldb = { + type = 'server', + port = "${port}", + executable = { + -- Change this to your path! + command = '/opt/codelldb/adapter/codelldb', + args = {"--port", "${port}"}, + } +} + +dap.configurations.rust= { + { + name = "Launch file", + type = "codelldb", + request = "launch", + program = function() + return vim.fn.input('Path to executable: ', vim.fn.getcwd() .. '/target/debug/', 'file') + end, + cwd = '${workspaceFolder}', + stopOnEntry = false + }, +} +``` + +This setup will ask you to point to the Tauri App binary you want to debug each time you lanuch the debugger. + +Optionally, you can setup `nvim-dap-ui` plugin to toggle debugger view automatically each time debugging session starts and stops: + +```lua title="init.lua" +local dapui = require("dapui") +dapui.setup() + +dap.listeners.before.attach.dapui_config = function() + dapui.open() +end +dap.listeners.before.launch.dapui_config = function() + dapui.open() +end +dap.listeners.before.event_terminated.dapui_config = function() + dapui.close() +end +dap.listeners.before.event_exited.dapui_config = function() + dapui.close() +end + +``` + +Lastly, you can change the default way the breakpoints are displayed in the editor: + +```lua title="init.lua" +vim.fn.sign_define('DapBreakpoint',{ text ='🟥', texthl ='', linehl ='', numhl =''}) +vim.fn.sign_define('DapStopped',{ text ='▶️', texthl ='', linehl ='', numhl =''}) +``` + +### Starting the dev server + +Since we're not using Tauri CLI to launch the app the development server will not start automatically. To control the state of development server from Neovim you can use the [overseer](https://github.com/stevearc/overseer.nvim/tree/master) plugin. + +Best way to control tasks running in background is to use [VS Code style task](https://github.com/stevearc/overseer.nvim/blob/master/doc/guides.md#vs-code-tasks) configuration. To do this create a `.vscode/tasks.json` file in the projects directory. + +You can find example task configuration for project using `trunk` below. + +```json title=".vscode/tasks.json" +{ + "version": "2.0.0", + "tasks": [ + { + "type": "process", + "label": "dev server", + "command": "trunk", + "args": ["serve"], + "isBackground": true, + "presentation": { + "revealProblems": "onProblem" + }, + "problemMatcher": { + "pattern": { + "regexp": "^error:.*", + "file": 1, + "line": 2 + }, + "background": { + "activeOnStart": false, + "beginsPattern": ".*Rebuilding.*", + "endsPattern": ".*server listening at:.*" + } + } + } + ] +} +``` + +### Example key bindings + +Below you can find example key bindings to start and control debugging sessions. + +```lua title="init.lua" +vim.keymap.set('n', '', function() dap.continue() end) +vim.keymap.set('n', '', function() dap.disconnect({ terminateDebuggee = true }) end) +vim.keymap.set('n', '', function() dap.step_over() end) +vim.keymap.set('n', '', function() dap.step_into() end) +vim.keymap.set('n', '', function() dap.step_out() end) +vim.keymap.set('n', 'b', function() dap.toggle_breakpoint() end) +vim.keymap.set('n', 'o', function() overseer.toggle() end) +vim.keymap.set('n', 'R', function() overseer.run_template() end) +``` diff --git a/src/content/docs/develop/Debug/vscode.mdx b/src/content/docs/develop/Debug/vscode.mdx index 016bf42418..400f640f21 100644 --- a/src/content/docs/develop/Debug/vscode.mdx +++ b/src/content/docs/develop/Debug/vscode.mdx @@ -130,7 +130,10 @@ Here is an example of running a dev server (equivalent of `beforeDevCommand`) an { "label": "build:debug", "type": "cargo", - "command": "build" + "command": "build", + "options": { + "cwd": "${workspaceRoot}/src-tauri" + } }, { "label": "ui:dev", diff --git a/src/content/docs/develop/Plugins/develop-mobile.mdx b/src/content/docs/develop/Plugins/develop-mobile.mdx index 928b9161e5..86dd938824 100644 --- a/src/content/docs/develop/Plugins/develop-mobile.mdx +++ b/src/content/docs/develop/Plugins/develop-mobile.mdx @@ -216,6 +216,20 @@ class ExamplePlugin(private val activity: Activity): Plugin(activity) { } ``` +:::note +On Android native commands are scheduled on the main thread. Performing long-running operations will cause the UI to freeze and potentially "Application Not Responding" (ANR) error. + +If you need to wait for some blocking IO, you can launch a corouting like that: + +```kotlin +CoroutineScope(Dispatchers.IO).launch { + val result = myLongRunningOperation() + invoke.resolve(result) +} +``` + +::: + @@ -341,6 +355,129 @@ Use a nullable type and set the default value on the command function instead. Required arguments are defined as `let : Type` ::: +## Calling Rust From Mobile Plugins + +It is often preferable to write plugin code in Rust, for performance and reusability. While Tauri doesn't directly provide a mechanism to call Rust from your plugin code, using JNI on Android and FFI on iOS allows plugins to call shared code, even when the application WebView is suspended. + +### Android + +In your plugin's `Cargo.toml`, add the jni crate as a dependency: + +```toml +[target.'cfg(target_os = "android")'.dependencies] +jni = "0.21" +``` + +Load the application library statically and define native functions in your Kotlin code. In this example, the Kotlin class is `com.example.HelloWorld`, we need to reference the full package name from the Rust side. + +```kotlin +private const val TAG = "MyPlugin" + +init { + try { + // Load the native library (libapp_lib.so) + // This is the shared library built by Cargo with crate-type = ["cdylib"] + System.loadLibrary("app_lib") + Log.d(TAG, "Successfully loaded libapp_lib.so") + } catch (e: UnsatisfiedLinkError) { + Log.e(TAG, "Failed to load libapp_lib.so", e) + throw e + } +} + +external fun helloWorld(name: String): String? +``` + +Then in your plugin's Rust code, define the function JNI will look for. The function format is `Java_package_class_method`, so for our class above this becomes `Java_com_example_HelloWorld_helloWorld` to get called by our `helloWorld` method: + +```rust +#[cfg(target_os = "android")] +#[no_mangle] +pub extern "system" fn Java_com_example_HelloWorld_helloWorld( + mut env: JNIEnv, + _class: JClass, + name: JString, +) -> jstring { + log::debug!("Calling JNI Hello World!"); + let result = format!("Hello, {}!", name); + + match env.new_string(result) { + Ok(jstr) => jstr.into_raw(), + Err(e) => { + log::error!("Failed to create JString: {}", e); + std::ptr::null_mut() + } + } +} +``` + +### iOS + +iOS only uses standard C FFI, so doesn't need any new dependencies. Add the hook in your Swift code, as well as any necessary cleanup. These functions can be named anything valid, but must be annotated with `@_silgen_name(FFI_FUNC)`, where FFI_FUNC is a function name to be called from Rust: + +```swift +@_silgen_name("hello_world_ffi") +private static func helloWorldFFI(_ name: UnsafePointer) -> UnsafeMutablePointer? + +@_silgen_name("free_hello_result_ffi") +private static func freeHelloResult(_ result: UnsafeMutablePointer) + +static func helloWorld(name: String) -> String? { + // Call Rust FFI + let resultPtr = name.withCString({ helloWorldFFI($0) }) + + // Convert C string to Swift String + let result = String(cString: resultPtr) + + // Free the C string + freeHelloResult(resultPtr) + + return result +} + +``` + +Then, implement the Rust side. The `extern` functions here must match the `@_silgen_name` annotations on the Swift side: + +```rust +#[no_mangle] +pub unsafe extern "C" fn hello_world_ffi(c_name: *const c_char) -> *mut c_char { + let name = match CStr::from_ptr(c_name).to_str() { + Ok(s) => s, + Err(e) => { + log::error!("[iOS FFI] Failed to convert C string: {}", e); + return std::ptr::null_mut(); + } + }; + + let result = format!("Hello, {}!", name); + + match CString::new(result) { + Ok(c_str) => c_str.into_raw(), + Err(e) => { + log::error!("[iOS FFI] Failed to create C string: {}", e); + std::ptr::null_mut() + } + } +} + +#[no_mangle] +pub unsafe extern "C" fn free_hello_result_ffi(result: *mut c_char) { + if !result.is_null() { + drop(CString::from_raw(result)); + } +} +``` + +## Android 16KB Memory Pages + +Google is moving to make 16KB memory pages a requirement in all new Android app submissions. Building with an NDK version 28 or higher should automatically generate bundles that meet this requirement, but in the event an older NDK version must be used or generated files aren't 16KB aligned, the following can be added to `.cargo/config.toml` to flag this to `rustc`: + +```toml +[target.aarch64-linux-android] +rustflags = ["-C", "link-arg=-Wl,-z,max-page-size=16384"] +``` + ## Permissions If a plugin requires permissions from the end user, Tauri simplifies the process of checking and requesting permissions. diff --git a/src/content/docs/develop/Tests/WebDriver/Example/index.mdx b/src/content/docs/develop/Tests/WebDriver/Example/index.mdx deleted file mode 100644 index 5b9135f245..0000000000 --- a/src/content/docs/develop/Tests/WebDriver/Example/index.mdx +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: Setup -sidebar: - order: 30 ---- - -{/* TODO: REVISE COPY TO V2 */} - -import { Image } from 'astro:assets'; -import HelloTauriWebdriver from '@assets/develop/Tests/hello-tauri-webdriver.png'; - -This example application solely focuses on adding WebDriver testing to an already existing project. To have a -project to test in the following two sections, we will set up an extremely minimal Tauri application for use in -our testing. We will not use the Tauri CLI, any frontend dependencies or build steps, and not be bundling the -application afterward. This is to showcase exactly a minimal suite to show off adding WebDriver testing to an existing -application. - -If you just want to see the finished example project that utilizes what will be shown in this example guide, then you -can see https://github.com/chippers/hello_tauri. - -## Initializing a Cargo Project - -We want to create a new binary Cargo project to house this example application. We can easily do this from the command -line with `cargo new hello-tauri-webdriver --bin`, which will scaffold a minimal binary Cargo project for us. This -directory will serve as the working directory for the rest of this guide, so make sure the commands you run are inside -this new `hello-tauri-webdriver/` directory. - -## Creating a Minimal Frontend - -We will create a minimal HTML file to act as our example application's front end. We will also be using a few things -from this frontend later during our WebDriver tests. - -First, let's create our Tauri `distDir` that we know we will need once building the Tauri portion of the application. -`mkdir dist` should create a new directory called `dist/` in which we will be placing the following `index.html` file. - -`dist/index.html`: - -```html - - - - - Hello Tauri! - - - -

Hello, Tauri!

- - -``` - -## Adding Tauri to the Cargo Project - -Next, we will add the necessary items to turn our Cargo project into a Tauri project. First, is adding the dependencies -to the Cargo Manifest (`Cargo.toml`) so that Cargo knows to pull in our dependencies while building. - -`Cargo.toml`: - -```toml -[package] -name = "hello-tauri-webdriver" -version = "0.1.0" -edition = "2021" -rust-version = "1.56" - -# Needed to set up some things for Tauri at build time -[build-dependencies] -tauri-build = "1" - -# The actual Tauri dependency, along with `custom-protocol` to serve the pages. -[dependencies] -tauri = { version = "1", features = ["custom-protocol"] } - -# Make --release build a binary that is small (opt-level = "s") and fast (lto = true). -# This is completely optional, but shows that testing the application as close to the -# typical release settings is possible. Note: this will slow down compilation. -[profile.release] -incremental = false -codegen-units = 1 -panic = "abort" -opt-level = "s" -lto = true -``` - -We added a `[build-dependency]` as you may have noticed. To use the build dependency, we must use it from a build -script. We will create one now at `build.rs`. - -`build.rs`: - -```rust -fn main() { - // Only watch the `dist/` directory for recompiling, preventing unnecessary - // changes when we change files in other project subdirectories. - println!("cargo:rerun-if-changed=dist"); - - // Run the Tauri build-time helpers - tauri_build::build() -} -``` - -Our Cargo Project now knows how to pull in and build our Tauri dependencies with all that setup. Let's finish making -this minimal example a Tauri application by setting up Tauri in the actual project code. We will be editing -the `src/main.rs` -file to add this Tauri functionality. - -`src/main.rs`: - -```rust -fn main() { - tauri::Builder::default() - .run(tauri::generate_context!()) - .expect("unable to run Tauri application"); -} -``` - -Pretty simple, right? - -## Tauri Configuration - -We are going to need 2 things to successfully build the application. First, we need an icon file. You can use any PNG -for this next part and copy it into `icon.png`. Typically, this will be provided as part of the scaffolding when you use -the Tauri CLI to create a project. To get the default Tauri icon, we can download the icon used by the Hello Tauri -example repository with the -command `curl -L "https://github.com/chippers/hello_tauri/raw/main/icon.png" --output icon.png`. - -We will need a `tauri.conf.json` to set some important configuration values for Tauri. Again, -this would typically come from the `tauri init` scaffolding command, but we will be creating our own minimal config -here. - -`tauri.conf.json`: - -```json -{ - "build": { - "distDir": "dist" - }, - "tauri": { - "bundle": { - "identifier": "studio.tauri.hello_tauri_webdriver", - "icon": ["icon.png"] - }, - "allowlist": { - "all": false - }, - "windows": [ - { - "width": 800, - "height": 600, - "resizable": true, - "fullscreen": false - } - ] - } -} -``` - -I'll go over some of these. You can see the `dist/` directory we created earlier specified as the `distDir` property. We -set a bundle identifier so that the built application has a unique id and set the `icon.png` as the only -icon. We aren't using any Tauri APIs or features, so we disable them in `allowlist` by setting `"all": false`. -The window values just set a single window to be created with some reasonable default values. - -At this point, we have a basic Hello World application that should display a simple greeting when run. - -## Running the Example Application - -To make sure we did it right, let's build this application! We will run this as a `--release` application because we -will also run our WebDriver tests with a release profile. Run `cargo run --release`, and after some compiling, we should -see the following application pop up. - -
- Hello Tauri Webdriver -
- -_Note: If you are modifying the application and want to use the Devtools, then run it without `--release` and "Inspect -Element" should be available in the right-click menu._ - -We should now be ready to start testing this application with some WebDriver frameworks. This guide will go over both -[WebdriverIO](/develop/tests/webdriver/example/webdriverio/) and [Selenium](/develop/tests/webdriver/example/selenium/) in that order. diff --git a/src/content/docs/develop/Tests/WebDriver/Example/selenium.mdx b/src/content/docs/develop/Tests/WebDriver/Example/selenium.mdx index 6e69a803b4..a93aed4c94 100644 --- a/src/content/docs/develop/Tests/WebDriver/Example/selenium.mdx +++ b/src/content/docs/develop/Tests/WebDriver/Example/selenium.mdx @@ -2,28 +2,26 @@ title: Selenium sidebar: order: 31 +i18nReady: true --- -{/* TODO: REVISE COPY TO V2 */} - import CommandTabs from '@components/CommandTabs.astro'; -:::note[Example Application] +:::note -This [Selenium] guide expects you to have already gone through the [example Application setup] to follow -step-by-step. The general information may still be helpful otherwise. +Make sure to go through the [prerequisites instructions] to be able to follow this guide. ::: This WebDriver testing example will use [Selenium] and a popular Node.js testing suite. You are expected to already have -Node.js installed, along with `npm` or `yarn` although the [finished example project] uses `yarn`. +Node.js installed, along with `npm` or `yarn` although the [finished example project] uses `pnpm`. ## Create a Directory for the Tests Let's create a space to write these tests in our project. We will be using a nested directory for this example project as we will later also go over other frameworks, but typically you will only need to use one. Create -the directory we will use with `mkdir -p webdriver/selenium`. The rest of this guide will assume you are inside the -`webdriver/selenium` directory. +the directory we will use with `mkdir -p e2e-tests`. The rest of this guide will assume you are inside the +`e2e-tests` directory. ## Initializing a Selenium Project @@ -38,13 +36,14 @@ guide on how to set it up from scratch. "name": "selenium", "version": "1.0.0", "private": true, + "type": "module", "scripts": { "test": "mocha" }, "dependencies": { - "chai": "^4.3.4", - "mocha": "^9.0.3", - "selenium-webdriver": "^4.0.0-beta.4" + "chai": "^5.2.1", + "mocha": "^11.7.1", + "selenium-webdriver": "^4.34.0" } } ``` @@ -80,21 +79,24 @@ testing file at `test/test.js` by default, so let's create that file now. `test/test.js`: ```javascript -const os = require('os'); -const path = require('path'); -const { expect } = require('chai'); -const { spawn, spawnSync } = require('child_process'); -const { Builder, By, Capabilities } = require('selenium-webdriver'); +import os from 'os'; +import path from 'path'; +import { expect } from 'chai'; +import { spawn, spawnSync } from 'child_process'; +import { Builder, By, Capabilities } from 'selenium-webdriver'; +import { fileURLToPath } from 'url'; + +const __dirname = fileURLToPath(new URL('.', import.meta.url)); // create the path to the expected application binary const application = path.resolve( __dirname, '..', '..', - '..', + 'src-tauri', 'target', - 'release', - 'hello-tauri-webdriver' + 'debug', + 'tauri-app' ); // keep track of the webdriver instance we create @@ -102,13 +104,18 @@ let driver; // keep track of the tauri-driver process we start let tauriDriver; +let exit = false; before(async function () { // set timeout to 2 minutes to allow the program to build if it needs to this.timeout(120000); - // ensure the program has been built - spawnSync('cargo', ['build', '--release']); + // ensure the app has been built + spawnSync('yarn', ['tauri', 'build', '--debug', '--no-bundle'], { + cwd: path.resolve(__dirname, '../..'), + stdio: 'inherit', + shell: true, + }); // start tauri-driver tauriDriver = spawn( @@ -116,6 +123,16 @@ before(async function () { [], { stdio: [null, process.stdout, process.stderr] } ); + tauriDriver.on('error', (error) => { + console.error('tauri-driver error:', error); + process.exit(1); + }); + tauriDriver.on('exit', (code) => { + if (!exit) { + console.error('tauri-driver exited with code:', code); + process.exit(1); + } + }); const capabilities = new Capabilities(); capabilities.set('tauri:options', { application }); @@ -130,10 +147,7 @@ before(async function () { after(async function () { // stop the webdriver session - await driver.quit(); - - // kill the tauri-driver process - tauriDriver.kill(); + await closeTauriDriver(); }); describe('Hello Tauri', () => { @@ -160,6 +174,34 @@ describe('Hello Tauri', () => { expect(luma).to.be.lessThan(100); }); }); + +async function closeTauriDriver() { + exit = true; + // kill the tauri-driver process + tauriDriver.kill(); + // stop the webdriver session + await driver.quit(); +} + +function onShutdown(fn) { + const cleanup = () => { + try { + fn(); + } finally { + process.exit(); + } + }; + + process.on('exit', cleanup); + process.on('SIGINT', cleanup); + process.on('SIGTERM', cleanup); + process.on('SIGHUP', cleanup); + process.on('SIGBREAK', cleanup); +} + +onShutdown(() => { + closeTauriDriver(); +}); ``` If you are familiar with JS testing frameworks, `describe`, `it`, and `expect` should look familiar. We also have @@ -199,9 +241,9 @@ tests! With [Selenium] and some hooking up to a test suite, we just enabled e2e testing without modifying our Tauri application at all! -[example application setup]: /develop/tests/webdriver/example/ +[prerequisites instructions]: /develop/tests/webdriver/ [selenium]: https://selenium.dev/ -[finished example project]: https://github.com/chippers/hello_tauri +[finished example project]: https://github.com/tauri-apps/webdriver-example [mocha]: https://mochajs.org/ [chai]: https://www.chaijs.com/ [`selenium-webdriver`]: https://www.npmjs.com/package/selenium-webdriver diff --git a/src/content/docs/develop/Tests/WebDriver/Example/webdriverio.mdx b/src/content/docs/develop/Tests/WebDriver/Example/webdriverio.mdx index 94c03289c6..ca14f6b095 100644 --- a/src/content/docs/develop/Tests/WebDriver/Example/webdriverio.mdx +++ b/src/content/docs/develop/Tests/WebDriver/Example/webdriverio.mdx @@ -2,28 +2,26 @@ title: WebdriverIO sidebar: order: 31 +i18nReady: true --- -{/* TODO: REVISE COPY TO V2 */} - import CommandTabs from '@components/CommandTabs.astro'; -:::note[Example Application] +:::note -This [WebdriverIO] guide expects you to have already gone through the [example Application setup] to follow -step-by-step. The general information may still be helpful otherwise. +Make sure to go through the [prerequisites instructions] to be able to follow this guide. ::: This WebDriver testing example will use [WebdriverIO], and its testing suite. It is expected to have Node.js already -installed, along with `npm` or `yarn` although the [finished example project] uses `yarn`. +installed, along with `npm` or `yarn` although the [finished example project] uses `pnpm`. ## Create a Directory for the Tests Let's create a space to write these tests in our project. We will be using a nested directory for this example project as we will later also go over other frameworks, but typically you only need to use one. Create -the directory we will use with `mkdir -p webdriver/webdriverio`. The rest of this guide assumes you are inside the -`webdriver/webdriverio` directory. +the directory we will use with `mkdir e2e-tests`. The rest of this guide assumes you are inside the +`e2e-tests` directory. ## Initializing a WebdriverIO Project @@ -38,16 +36,17 @@ guide on setting it up from scratch. "name": "webdriverio", "version": "1.0.0", "private": true, + "type": "module", "scripts": { "test": "wdio run wdio.conf.js" }, "dependencies": { - "@wdio/cli": "^7.9.1" + "@wdio/cli": "^9.19.0" }, "devDependencies": { - "@wdio/local-runner": "^7.9.1", - "@wdio/mocha-framework": "^7.9.1", - "@wdio/spec-reporter": "^7.9.0" + "@wdio/local-runner": "^9.19.0, + "@wdio/mocha-framework": "^9.19.0", + "@wdio/spec-reporter": "^9.19.0" } } ``` @@ -80,21 +79,27 @@ config file which controls most aspects of our testing suite. `wdio.conf.js`: ```javascript -const os = require('os'); -const path = require('path'); -const { spawn, spawnSync } = require('child_process'); +import os from 'os'; +import path from 'path'; +import { spawn, spawnSync } from 'child_process'; +import { fileURLToPath } from 'url'; + +const __dirname = fileURLToPath(new URL('.', import.meta.url)); // keep track of the `tauri-driver` child process let tauriDriver; +let exit = false; -exports.config = { +export const config = { + host: '127.0.0.1', + port: 4444, specs: ['./develop/tests/specs/**/*.js'], maxInstances: 1, capabilities: [ { maxInstances: 1, 'tauri:options': { - application: '../../target/release/hello-tauri-webdriver', + application: '../src-tauri/target/debug/tauri-app', }, }, ], @@ -106,24 +111,76 @@ exports.config = { }, // ensure the rust project is built since we expect this binary to exist for the webdriver sessions - onPrepare: () => spawnSync('cargo', ['build', '--release']), + onPrepare: () => { + // Remove the extra `--` if you're not using npm! + spawnSync( + 'npm', + ['run', 'tauri', 'build', '--', '--debug', '--no-bundle'], + { + cwd: path.resolve(__dirname, '..'), + stdio: 'inherit', + shell: true, + } + ); + }, // ensure we are running `tauri-driver` before the session starts so that we can proxy the webdriver requests - beforeSession: () => - (tauriDriver = spawn( + beforeSession: () => { + tauriDriver = spawn( path.resolve(os.homedir(), '.cargo', 'bin', 'tauri-driver'), [], { stdio: [null, process.stdout, process.stderr] } - )), + ); + + tauriDriver.on('error', (error) => { + console.error('tauri-driver error:', error); + process.exit(1); + }); + tauriDriver.on('exit', (code) => { + if (!exit) { + console.error('tauri-driver exited with code:', code); + process.exit(1); + } + }); + }, // clean up the `tauri-driver` process we spawned at the start of the session - afterSession: () => tauriDriver.kill(), + // note that afterSession might not run if the session fails to start, so we also run the cleanup on shutdown + afterSession: () => { + closeTauriDriver(); + }, }; + +function closeTauriDriver() { + exit = true; + tauriDriver?.kill(); +} + +function onShutdown(fn) { + const cleanup = () => { + try { + fn(); + } finally { + process.exit(); + } + }; + + process.on('exit', cleanup); + process.on('SIGINT', cleanup); + process.on('SIGTERM', cleanup); + process.on('SIGHUP', cleanup); + process.on('SIGBREAK', cleanup); +} + +// ensure tauri-driver is closed when our test process exits +onShutdown(() => { + closeTauriDriver(); +}); ``` -If you are interested in the properties on the `exports.config` object, I [suggest reading the documentation][webdriver documentation]. +If you are interested in the properties on the `config` object, we [suggest reading the documentation][webdriver documentation]. For non-WDIO specific items, there are comments explaining why we are running commands in `onPrepare`, `beforeSession`, -and `afterSession`. We also have our specs set to `"./develop/tests/specs/**/*.js"`, so let's create a spec now. +and `afterSession`. We also have our specs set to `"./test/specs/**/*.js"`, so let's create a spec now. ## Spec @@ -215,9 +272,9 @@ We see the Spec Reporter tell us that all 3 tests from the `test/specs/example.e Using the [WebdriverIO] test suite, we just easily enabled e2e testing for our Tauri application from just a few lines of configuration and a single command to run it! Even better, we didn't have to modify the application at all. -[example application setup]: /develop/tests/webdriver/example/ +[prerequisites instructions]: /develop/tests/webdriver/ [webdriverio]: https://webdriver.io/ -[finished example project]: https://github.com/chippers/hello_tauri +[finished example project]: https://github.com/tauri-apps/webdriver-example [mocha]: https://mochajs.org/ [webdriver documentation]: https://webdriver.io/docs/configurationfile [webdriverio api docs]: https://webdriver.io/docs/api diff --git a/src/content/docs/develop/Tests/WebDriver/ci.md b/src/content/docs/develop/Tests/WebDriver/ci.md index ea99a9da45..9390f75279 100644 --- a/src/content/docs/develop/Tests/WebDriver/ci.md +++ b/src/content/docs/develop/Tests/WebDriver/ci.md @@ -3,21 +3,23 @@ title: Continuous Integration description: WebDriver Testing sidebar: order: 21 +i18nReady: true --- -Utilizing Linux and some programs to create a fake display, it is possible to run [WebDriver] tests with -[`tauri-driver`] on your CI. The following example uses the [WebdriverIO] example we [previously built together] and +It is possible to run [WebDriver] tests with [`tauri-driver`] on your CI. The following example uses the [WebdriverIO] example we [previously built together] and GitHub Actions. -This means the following assumptions: +The WebDriver tests are executed on Linux by creating a fake display. +Some CI systems such as GitHub Actions also support running WebDriver tests on Windows. -1. The Tauri application is in the repository root and the binary builds when running `cargo build --release`. -2. The [WebDriverIO] test runner is in the `webdriver/webdriverio` directory and runs when `yarn test` is used in that - directory. +## GitHub Actions -The following is a commented GitHub Actions workflow file at `.github/workflows/webdriver.yml` +The following GitHub Actions assumes: -```yaml +1. The Tauri application is in the `src-tauri` folder. +2. The [WebDriverIO] test runner is in the `e2e-tests` directory and runs when `yarn test` is used in that directory. + +```yaml title=".github/workflows/webdriver.yml" # run this action when the repository is pushed to on: [push] @@ -30,8 +32,14 @@ jobs: # the display name of the test job name: WebDriverIO Test Runner - # we want to run on the latest linux environment - runs-on: ubuntu-22.04 + # run on the matrix platform + runs-on: ${{ matrix.platform }} + strategy: + # do not fail other matrix runs if one fails + fail-fast: false + # set all platforms our test should run on + matrix: + platform: [ubuntu-latest, windows-latest] # the steps our job runs **in order** steps: @@ -41,55 +49,72 @@ jobs: # install system dependencies that Tauri needs to compile on Linux. # note the extra dependencies for `tauri-driver` to run which are: `webkit2gtk-driver` and `xvfb` - name: Tauri dependencies + if: matrix.platform == 'ubuntu-latest' + run: | + sudo apt-get update && + sudo apt-get install -y \ + libwebkit2gtk-4.1-dev \ + libayatana-appindicator3-dev \ + webkit2gtk-driver \ + xvfb + + # install a matching Microsoft Edge Driver version using msedgedriver-tool + - name: install msdgedriver (Windows) + if: matrix.platform == 'windows-latest' run: | - sudo apt update && sudo apt install -y \ - libwebkit2gtk-4.1-dev \ - build-essential \ - curl \ - wget \ - file \ - libxdo-dev \ - libssl-dev \ - libayatana-appindicator3-dev \ - librsvg2-dev \ - webkit2gtk-driver \ - xvfb + cargo install --git https://github.com/chippers/msedgedriver-tool + & "$HOME/.cargo/bin/msedgedriver-tool.exe" + $PWD.Path >> $env:GITHUB_PATH + # install latest stable Rust release - name: Setup rust-toolchain stable - id: rust-toolchain uses: dtolnay/rust-toolchain@stable - # we run our rust tests before the webdriver tests to avoid testing a broken application + # setup caching for the Rust target folder + - name: Setup Rust cache + uses: Swatinem/rust-cache@v2 + with: + workspaces: src-tauri + + # we run our Rust tests before the webdriver tests to avoid testing a broken application - name: Cargo test run: cargo test - # build a release build of our application to be used during our WebdriverIO tests - - name: Cargo build - run: cargo build --release - # install the latest stable node version at the time of writing - - name: Node 20 + - name: Node 24 uses: actions/setup-node@v4 with: - node-version: 20 + node-version: 24 cache: 'yarn' - # install our Node.js dependencies with Yarn + # install the application Node.js dependencies with Yarn + - name: Yarn install + run: yarn install --frozen-lockfile + + # install the e2e-tests Node.js dependencies with Yarn - name: Yarn install run: yarn install --frozen-lockfile - working-directory: webdriver/webdriverio + working-directory: e2e-tests # install the latest version of `tauri-driver`. # note: the tauri-driver version is independent of any other Tauri versions - name: Install tauri-driver run: cargo install tauri-driver --locked - # run the WebdriverIO test suite. + # run the WebdriverIO test suite on Linux. # we run it through `xvfb-run` (the dependency we installed earlier) to have a fake # display server which allows our application to run headless without any changes to the code - - name: WebdriverIO + - name: WebdriverIO (Linux) + if: matrix.platform == 'ubuntu-latest' run: xvfb-run yarn test - working-directory: webdriver/webdriverio + working-directory: e2e-tests + + # run the WebdriverIO test suite on Windows. + # in this case we can run the tests directly. + - name: WebdriverIO (Windows) + if: matrix.platform == 'windows-latest' + run: yarn test + working-directory: e2e-tests ``` [previously built together]: /develop/tests/webdriver/example/webdriverio/ diff --git a/src/content/docs/develop/Tests/WebDriver/index.mdx b/src/content/docs/develop/Tests/WebDriver/index.mdx index f736654a85..31cc83a05b 100644 --- a/src/content/docs/develop/Tests/WebDriver/index.mdx +++ b/src/content/docs/develop/Tests/WebDriver/index.mdx @@ -4,6 +4,7 @@ description: WebDriver Testing sidebar: order: 10 label: Overview +i18nReady: true --- [WebDriver] is a standardized interface to interact with web documents primarily intended for automated testing. @@ -24,7 +25,7 @@ Because we currently utilize the platform's native [WebDriver] server, there are ### Linux -We use `WebKitWebDriver` on Linux platforms. Check if this binary exists already (command `which WebKitWebDriver`) as +We use `WebKitWebDriver` on Linux platforms. Check if this binary exists already by running the `which WebKitWebDriver` command as some distributions bundle it with the regular WebKit package. Other platforms may have a separate package for them, such as `webkit2gtk-driver` on Debian-based distributions. @@ -34,6 +35,13 @@ Make sure to grab the version of [Microsoft Edge Driver] that matches your Windo being built and tested on. This should almost always be the latest stable version on up-to-date Windows installs. If the two versions do not match, you may experience your WebDriver testing suite hanging while trying to connect. +You can use the [msedgedriver-tool](https://github.com/chippers/msedgedriver-tool) to download the appropriate Microsoft Edge Driver: + +```powershell +cargo install --git https://github.com/chippers/msedgedriver-tool +& "$HOME/.cargo/bin/msedgedriver-tool.exe" +``` + The download contains a binary called `msedgedriver.exe`. [`tauri-driver`] looks for that binary in the `$PATH` so make sure it's either available on the path or use the `--native-driver` option on [`tauri-driver`]. You may want to download this automatically as part of the CI setup process to ensure the Edge, and Edge Driver versions stay in sync on Windows CI machines. A guide on how to do this may be added at a later date. @@ -44,12 +52,11 @@ Below are step-by-step guides to show how to create a minimal example applicatio is tested with WebDriver. If you prefer to see the result of the guide and look over a finished minimal codebase that utilizes it, you -can look at https://github.com/chippers/hello_tauri. +can look at https://github.com/tauri-apps/webdriver-example. import { LinkCard, CardGrid } from '@astrojs/starlight/components'; - { }); // we can use the spying tools provided by vitest to track the mocked function - const spy = vi.spyOn(window, "__TAURI_INTERNALS__.invoke"); + const spy = vi.spyOn(window.__TAURI_INTERNALS__, "invoke"); expect(invoke("add", { a: 12, b: 15 })).resolves.toBe(27); expect(spy).toHaveBeenCalled(); @@ -124,6 +128,33 @@ mockIPC(async (cmd, args) => { }); ``` +### Mocking Events + + + +There is partial support of the [Event System] to simulate events emitted by your Rust code via the `shouldMockEvents` option: + +```javascript +import { mockIPC, clearMocks } from '@tauri-apps/api/mocks'; +import { emit, listen } from '@tauri-apps/api/event'; +import { afterEach, expect, test, vi } from 'vitest'; + +test('mocked event', () => { + mockIPC(() => {}, { shouldMockEvents: true }); // enable event mocking + + const eventHandler = vi.fn(); + listen('test-event', eventHandler); + + emit('test-event', { foo: 'bar' }); + expect(eventHandler).toHaveBeenCalledWith({ + event: 'test-event', + payload: { foo: 'bar' }, + }); +}); +``` + +`emitTo` and `emit_filter` are **not** supported yet. + ## Windows Sometimes you have window-specific code (a splash screen window, for example), so you need to simulate different windows. @@ -168,3 +199,4 @@ test('invoke', async () => { [`mockwindows()`]: /reference/javascript/api/namespacemocks/#mockwindows [`clearmocks()`]: /reference/javascript/api/namespacemocks/#clearmocks [vitest]: https://vitest.dev +[Event System]: /develop/calling-frontend/#event-system diff --git a/src/content/docs/develop/_sections/frontend-listen.mdx b/src/content/docs/develop/_sections/frontend-listen.mdx index c26d0a7bc4..7184d97899 100644 --- a/src/content/docs/develop/_sections/frontend-listen.mdx +++ b/src/content/docs/develop/_sections/frontend-listen.mdx @@ -1,7 +1,5 @@ --- title: Calling the Frontend from Rust -sidebar: - order: 1 --- The `@tauri-apps/api` NPM package offers APIs to listen to both global and webview-specific events. @@ -66,8 +64,8 @@ appWebview.once('ready', () => {}); ``` :::note -Events emitted in the frontend also triggers listeners registed by these APIs. -For more information see the [Calling Rust from the Frontend] documentation. +Events emitted in the frontend also trigger listeners registered by these APIs. +For more information, see the [Calling Rust from the Frontend] documentation. ::: #### Listening to Events on Rust diff --git a/src/content/docs/develop/calling-frontend.mdx b/src/content/docs/develop/calling-frontend.mdx index 7c94f29253..4e70a34628 100644 --- a/src/content/docs/develop/calling-frontend.mdx +++ b/src/content/docs/develop/calling-frontend.mdx @@ -1,7 +1,6 @@ --- title: Calling the Frontend from Rust -sidebar: - order: 1 +i18nReady: true --- import { Content as FrontendListen } from './_sections/frontend-listen.mdx'; @@ -162,20 +161,17 @@ use tauri::{AppHandle, ipc::Channel}; use serde::Serialize; #[derive(Clone, Serialize)] -#[serde(rename_all = "camelCase", tag = "event", content = "data")] +#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "event", content = "data")] enum DownloadEvent<'a> { - #[serde(rename_all = "camelCase")] Started { url: &'a str, download_id: usize, content_length: usize, }, - #[serde(rename_all = "camelCase")] Progress { download_id: usize, chunk_length: usize, }, - #[serde(rename_all = "camelCase")] Finished { download_id: usize, }, diff --git a/src/content/docs/develop/calling-rust.mdx b/src/content/docs/develop/calling-rust.mdx index fadbd832e4..b480899f00 100644 --- a/src/content/docs/develop/calling-rust.mdx +++ b/src/content/docs/develop/calling-rust.mdx @@ -1,7 +1,6 @@ --- title: Calling Rust from the Frontend -sidebar: - order: 1 +i18nReady: true --- import { Content as FrontendListen } from './_sections/frontend-listen.mdx'; @@ -37,7 +36,7 @@ Command names must be unique. Commands defined in the `lib.rs` file cannot be marked as `pub` due to a limitation in the glue code generation. You will see an error like this if you mark it as a public function: -```` +``` error[E0255]: the name `__cmd__command_name` is defined multiple times --> src/lib.rs:28:8 | @@ -48,6 +47,7 @@ error[E0255]: the name `__cmd__command_name` is defined multiple times | = note: `__cmd__command_name` must be defined only once in the macro namespace of this module ``` + ::: You will have to provide a list of your commands to the builder function like so: @@ -60,7 +60,7 @@ pub fn run() { .run(tauri::generate_context!()) .expect("error while running tauri application"); } -```` +``` Now, you can invoke the command from your JavaScript code: @@ -237,7 +237,7 @@ invoke('login', { user: 'tauri', password: '0j4rijw8=' }) As mentioned above, everything returned from commands must implement [`serde::Serialize`], including errors. This can be problematic if you're working with error types from Rust's std library or external crates as most error types do not implement it. -In simple scenarios you can use `map_err` to convert these errors to `String`s: +In simple scenarios you can use `map_err` to convert these errors to `String`: ```rust #[tauri::command] @@ -451,12 +451,35 @@ Commands can access an `AppHandle` instance: ```rust title="src-tauri/src/lib.rs" #[tauri::command] async fn my_custom_command(app_handle: tauri::AppHandle) { - let app_dir = app_handle.path_resolver().app_dir(); + let app_dir = app_handle.path().app_dir(); use tauri::GlobalShortcutManager; app_handle.global_shortcut_manager().register("CTRL + U", move || {}); } ``` +:::tip + +`AppHandle` and `WebviewWindow` both take a generic parameter `R: Runtime`, +when the `wry` feature is enabled in `tauri` (which is enabled by default), +we default the generic to the `Wry` runtime so you can use it directly, +but if you want to use a different runtime, for example the [mock runtime], +you need to write your functions like this + +```rust title="src-tauri/src/lib.rs" ins="" ins="" +use tauri::{AppHandle, GlobalShortcutManager, Runtime, WebviewWindow}; + +#[tauri::command] +async fn my_custom_command(app_handle: AppHandle, webview_window: WebviewWindow) { + let app_dir = app_handle.path().app_dir(); + app_handle + .global_shortcut_manager() + .register("CTRL + U", move || {}); + println!("WebviewWindow: {}", webview_window.label()); +} +``` + +::: + ### Accessing Managed State Tauri can manage state using the `manage` function on `tauri::Builder`. @@ -642,7 +665,7 @@ Global events are delivered to **all** listeners To trigger an event to a listener registered by a specific webview you can use the [event.emitTo] or the [WebviewWindow#emitTo] functions: ```js -import { emit } from '@tauri-apps/api/event'; +import { emitTo } from '@tauri-apps/api/event'; import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'; // emitTo(webviewLabel, eventName, payload) @@ -700,3 +723,4 @@ To learn how to listen to events and emit events from your Rust code, see the [R [Rust Event System documentation]: /develop/calling-frontend/#event-system [channels documentation]: /develop/calling-frontend/#channels [Calling Rust from the Frontend]: /develop/calling-rust/ +[mock runtime]: https://docs.rs/tauri/2.0.0/tauri/test/struct.MockRuntime.html diff --git a/src/content/docs/develop/configuration-files.mdx b/src/content/docs/develop/configuration-files.mdx index 25b19c8b22..3c43d432e5 100644 --- a/src/content/docs/develop/configuration-files.mdx +++ b/src/content/docs/develop/configuration-files.mdx @@ -1,7 +1,6 @@ --- title: Configuration Files -sidebar: - order: 1 +i18nReady: true --- import CommandTabs from '@components/CommandTabs.astro'; @@ -77,7 +76,7 @@ pubkey = "updater pub key" endpoints = ["https://my.app.updater/{{target}}/{{current_version}}"] ``` -Note that JSON5 and TOML supports comments, and TOML can use kebab-case for config names which are more idiomatic. +Note that JSON5 and TOML supports comments, and TOML can use kebab-case for config names which are more idiomatic. Field names are case-sensitive in all 3 formats. ### Platform-specific Configuration @@ -139,7 +138,8 @@ The resolved configuration for Linux would be the following object: "subcommands": { "update": {} } - } + }, + "deep-link": {} } } ``` @@ -163,20 +163,17 @@ For instance to distribute a completely isolated _beta_ application you can use } ``` +And to distribute this separate _beta_ app you provide this configuration file when building it: + -And to distribute this separate _beta_ app you provide this configuration file when building it: - -``` - -``` - ## `Cargo.toml` Cargo's manifest file is used to declare Rust crates your app depends on, metadata about your app, and other Rust-related features. If you do not intend to do backend development using Rust for your app then you may not be modifying it much, but it's important to know that it exists and what it does. @@ -204,14 +201,14 @@ serde = { version = "1.0", features = ["derive"] } tauri = { version = "2.0.0", features = [ ] } ``` -The most important parts to take note of are the `tauri-build` and `tauri` dependencies. Generally, they must both be on the latest minor versions as the Tauri CLI, but this is not strictly required. If you encounter issues while trying to run your app you should check that any Tauri versions (`tauri` and `tauri-cli`) are on the latest versions for their respective minor releases. +The most important parts to take note of are the `tauri-build` and `tauri` dependencies. Generally, they must both be on the same latest minor versions as the Tauri CLI, but this is not strictly required. If you encounter issues while trying to run your app you should check that any Tauri versions (`tauri` and `tauri-cli`) are on the latest versions for their respective minor releases. Cargo version numbers use [Semantic Versioning]. Running `cargo update` in the `src-tauri` folder will pull the latest available Semver-compatible versions of all dependencies. For example, if you specify `2.0.0` as the version for `tauri-build`, Cargo will detect and download version `2.0.0.0` because it is the latest Semver-compatible version available. Tauri will update the major version number whenever a breaking change is introduced, meaning you should always be capable of safely upgrading to the latest minor and patch versions without fear of your code breaking. If you want to use a specific crate version you can use exact versions instead by prepending `=` to the version number of the dependency: ``` -tauri-build = { version = "=2.0.0.0" } +tauri-build = { version = "=2.0.0" } ``` An additional thing to take note of is the `features=[]` portion of the `tauri` dependency. Running `tauri dev` and `tauri build` will automatically manage which features need to be enabled in your project based on the your Tauri configuration. For more information about `tauri` feature flags see the [documentation][tauri Cargo features]. diff --git a/src/content/docs/develop/icons.mdx b/src/content/docs/develop/icons.mdx new file mode 100644 index 0000000000..14ed8760b0 --- /dev/null +++ b/src/content/docs/develop/icons.mdx @@ -0,0 +1,119 @@ +--- +title: App Icons +sidebar: + order: 1 +--- + +{/* TODO: More platform specific explanations like macOS requiring padding in the icon (waiting for https://github.com/tauri-apps/tauri/pull/11037) */} + +import CommandTabs from '@components/CommandTabs.astro'; + +Tauri ships with a default iconset based on its logo. This is NOT what you want when you ship your application. To remedy this common situation, Tauri provides the `icon` command that will take an input file (`"./app-icon.png"` by default) and create all the icons needed for the various platforms. + +:::note[Note on filetypes] + +- `icon.icns` = macOS +- `icon.ico` = Windows +- `*.png` = Linux +- `Square*Logo.png` & `StoreLogo.png` = Currently unused but intended for AppX/MS Store targets. + +Some icon types may be used on platforms other than those listed above (especially `png`). Therefore we recommend including all icons even if you intend to only build for a subset of platforms. + +::: + +## Command Usage + + + +```console +> pnpm tauri icon --help + +Generate various icons for all major platforms + +Usage: pnpm run tauri icon [OPTIONS] [INPUT] + +Arguments: + [INPUT] Path to the source icon (squared PNG or SVG file with transparency) [default: ./app-icon.png] + +Options: + -o, --output Output directory. Default: 'icons' directory next to the tauri.conf.json file + -v, --verbose... Enables verbose logging + -p, --png Custom PNG icon sizes to generate. When set, the default icons are not generated + --ios-color The background color of the iOS icon - string as defined in the W3C's CSS Color Module Level 4 [default: #fff] + -h, --help Print help + -V, --version Print version +``` + +The **desktop** icons will be placed in your `src-tauri/icons` folder by default, where they will be included in your built app automatically. If you want to source your icons from a different location, you can edit this part of the `tauri.conf.json` file: + +```json +{ + "bundle": { + "icon": [ + "icons/32x32.png", + "icons/128x128.png", + "icons/128x128@2x.png", + "icons/icon.icns", + "icons/icon.ico" + ] + } +} +``` + +The **mobile** icons will be placed into the Xcode and Android Studio projects directly! + +## Creating icons manually + +If you prefer to build these icons yourself, for example if you want to have a simpler design for small sizes or because you don't want to depend on the CLI's internal image resizing, you must make sure your icons meet some requirements: + +- `icon.icns`: The required layer sizes and names for the [`icns`] file are described [in the Tauri repo] +- `icon.ico`: The [`ico`] file must include layers for 16, 24, 32, 48, 64 and 256 pixels. For an optimal display of the ICO image _in development_, the 32px layer should be the first layer. +- `png`: The requirements for the png icons are: width == height, RGBA (RGB + Transparency), and 32bit per pixel (8bit per channel). Commonly expected sizes on desktop are 32, 128, 256, and 512 pixels. We recommend to at least match the output of `tauri icon`: `32x32.png`, `128x128.png`, `128x128@2x.png`, and `icon.png`. + +### Android + +On Android you will need png icons with the same requirements but in different sizes. They will also need to be placed directly in the Android Studio project: + +- `src-tauri/gen/android/app/src/main/res/` + - `mipmap-hdpi/` + - `ic_launcher.png` & `ic_launcher_round.png`: 49x49px + - `ic_launcher_foreground.png`: 162x162px + - `mipmap-mdpi/` + - `ic_launcher.png` & `ic_launcher_round.png`: 48x48px + - `ic_launcher_foreground.png`: 108x108px + - `mipmap-xhdpi/` + - `ic_launcher.png` & `ic_launcher_round.png`: 96x96px + - `ic_launcher_foreground.png`: 216x216px + - `mipmap-xxhdpi/` + - `ic_launcher.png` & `ic_launcher_round.png`: 144x144px + - `ic_launcher_foreground.png`: 324x324px + - `mipmap-xxxhdpi/` + - `ic_launcher.png` & `ic_launcher_round.png`: 192x192px + - `ic_launcher_foreground.png`: 432x432px + +If `tauri icon` cannot be used, we recommend checking out Android Studio's [Image Asset Studio] instead. + +### iOS + +On iOS you will need png icons with the same requirements but **without transparency** and in different sizes. They will also need to be placed directly in the Xcode project into `src-tauri/gen/apple/Assets.xcassets/AppIcon.appiconset/`. The following icons are expected: + +- 20px in 1x, 2x, 3x, with an extra icon +- 29px in 1x, 2x, 3x, with an extra icon +- 40px in 1x, 2x, 3x, with an extra icon +- 60px in 2x, 3x +- 76px in 1x, 2x +- 83.5px in 2x +- 512px in 2x saved as `AppIcon-512@2x.png` + +The file names are in the format of `AppIcon-{size}x{size}@{scaling}{extra}.png`. For the 20px icons this means you need icons in sizes 20x20, 40x40 and 60x60 named as `AppIcon-20x20@1x.png`, `AppIcon-20x20@2x.png`, `AppIcon-20x20@3x.png` and `2x` saved additionally as `AppIcon-20x20@2x-1.png` ("extra icon"). + +[in the tauri repo]: https://github.com/tauri-apps/tauri/blob/1.x/tooling/cli/src/helpers/icns.json +[`icns`]: https://en.wikipedia.org/wiki/Apple_Icon_Image_format +[`ico`]: https://en.wikipedia.org/wiki/ICO_(file_format) +[image asset studio]: https://developer.android.com/studio/write/create-app-icons diff --git a/src/content/docs/develop/index.mdx b/src/content/docs/develop/index.mdx index bbce535bbd..1715f9b1c9 100644 --- a/src/content/docs/develop/index.mdx +++ b/src/content/docs/develop/index.mdx @@ -2,8 +2,8 @@ title: Develop description: Core concepts for developing with Tauri. sidebar: - order: 0 label: Overview +i18nReady: true --- import CommandTabs from '@components/CommandTabs.astro'; @@ -63,6 +63,7 @@ To develop your application for desktop, run the `tauri dev` command. yarn="yarn tauri dev" pnpm="pnpm tauri dev" deno="deno task tauri dev" + bun="bun tauri dev" cargo="cargo tauri dev" /> @@ -86,6 +87,7 @@ Developing for mobile is similar to how desktop development works, but you must yarn="yarn tauri [android|ios] dev" pnpm="pnpm tauri [android|ios] dev" deno="deno task tauri [android|ios] dev" + bun="bun tauri [android|ios] dev" cargo="cargo tauri [android|ios] dev" /> @@ -147,6 +149,7 @@ To define the run target upfront you can provide the device or simulator name as yarn="yarn tauri ios dev 'iPhone 15'" pnpm="pnpm tauri ios dev 'iPhone 15'" deno="deno task tauri ios dev 'iPhone 15'" + bun="bun tauri ios dev 'iPhone 15'" cargo="cargo tauri ios dev 'iPhone 15'" /> @@ -161,6 +164,7 @@ To open the mobile IDE instead of running on a connected device or simulator, us yarn="yarn tauri [android|ios] dev --open" pnpm="pnpm tauri [android|ios] dev --open" deno="deno task tauri [android|ios] dev --open" + bun="bun tauri [android|ios] dev --open" cargo="cargo tauri [android|ios] dev --open" /> @@ -174,6 +178,7 @@ See your framework's setup guide for more information. yarn="yarn tauri [android|ios] dev --open --host" pnpm="pnpm tauri [android|ios] dev --open --host" deno="deno task tauri [android|ios] dev --open --host" + bun="bun tauri [android|ios] dev --open --host" cargo="cargo tauri [android|ios] dev --open --host" /> ::: @@ -194,7 +199,7 @@ It is recommended to use the `tauri [android|ios] dev --open` command and keep t If you are running on a physical device you must enable **Web Inspector** in **Settings > Safari > Advanced**. After following all steps you should see a **Develop** menu in Safari, where you will find the connected devices and applications to inspect. - Select on your device or simulator and click on **localhost** to open the Safari Developer Tools window. + Select your device or simulator and click on **localhost** to open the Safari Developer Tools window. - Android @@ -209,9 +214,9 @@ It is recommended to use the `tauri [android|ios] dev --open` command and keep t Each Android distribution has its own way to enable the Developer Mode, please check your manufacturer's documentation for more information. ::: - The Web Inspector for Android is powered by Google Chrome's DevTools and can be accessed by navigating to `chrome://inspect` in the Chrome browser. + The Web Inspector for Android is powered by Google Chrome's DevTools and can be accessed by navigating to `chrome://inspect` in the Chrome browser on your computer. Your device or emulator should appear in the remote devices list if your Android application is running, and you can open the developer tools - by clicking **inspect** on your device. + by clicking **inspect** on the entry matching your device. #### Troubleshooting diff --git a/src/content/docs/develop/resources.mdx b/src/content/docs/develop/resources.mdx index d5d5dfbe1f..794ca030db 100644 --- a/src/content/docs/develop/resources.mdx +++ b/src/content/docs/develop/resources.mdx @@ -1,32 +1,81 @@ --- title: Embedding Additional Files -sidebar: - order: 1 +i18nReady: true --- +import { Tabs, TabItem } from '@astrojs/starlight/components'; + You may need to include additional files in your application bundle that aren't part of your frontend (your `frontendDist`) directly or which are too big to be inlined into the binary. We call these files `resources`. -To bundle the files of your choice, you can add the `resources` property to the `bundle` object in your `tauri.conf.json` file. +## Configuration -See more about `tauri.conf.json` configuration [here][tauri.bundle]. +To bundle the files of your choice, add the `resources` property to the `bundle` object in your `tauri.conf.json` file. -`resources` expects a list of strings targeting files or directories either with absolute or relative paths. It supports glob patterns in case you need to include multiple files from a directory. +To include a list of files: -Here is a sample to illustrate the configuration. This is not a complete `tauri.conf.json` file: + + ```json title=tauri.conf.json { "bundle": { "resources": [ + "./path/to/some-file.txt", + "/absolute/path/to/textfile.txt", + "../relative/path/to/jsonfile.json", + "some-folder/", + "resources/**/*.md" + ] + } +} +``` + + + + +```json title=tauri.conf.json5 +{ + "bundle": { + "resources": [ + // Will be placed to `$RESOURCE/path/to/some-file.txt` + "./path/to/some-file.txt", + + // The root in an abosolute path will be replaced by `_root_`, + // so `textfile.txt` will be placed to `$RESOURCE/_root_/absolute/path/to/textfile.txt` "/absolute/path/to/textfile.txt", - "relative/path/to/jsonfile.json", - "resources/**/*" + + // `..` in a relative path will be replaced by `_up_`, + // so `jsonfile.json` will be placed to `$RESOURCE/_up_/relative/path/to/textfile.txt`, + "../relative/path/to/jsonfile.json", + + // If the path is a directory, the entire directory will be copied to the `$RESOURCE` directory, + // preserving the original structures, for example: + // - `some-folder/file.txt` -> `$RESOURCE/some-folder/file.txt` + // - `some-folder/another-folder/config.json` -> `$RESOURCE/some-folder/another-folder/config.json` + // This is the same as `some-folder/**/*` + "some-folder/", + + // You can also include multiple files at once through glob patterns. + // All the `.md` files inside `resources` will be placed to `$RESOURCE/resources/`, + // preserving their original directory structures, for example: + // - `resources/index.md` -> `$RESOURCE/resources/index.md` + // - `resources/docs/setup.md` -> `$RESOURCE/resources/docs/setup.md` + "resources/**/*.md" ] } } ``` -Alternatively the `resources` config also accepts a map object if you want to change where the files will be copied to. Here is a sample that shows how to include files from different sources into the same `resources` folder: + + + +The bundled files will be in `$RESOURCES/` with the original directory structure preserved, +for example: `./path/to/some-file.txt` -> `$RESOURCE/path/to/some-file.txt` + +To fine control where the files will get copied to, use a map instead: + + + ```json title=tauri.conf.json { @@ -34,19 +83,50 @@ Alternatively the `resources` config also accepts a map object if you want to ch "resources": { "/absolute/path/to/textfile.txt": "resources/textfile.txt", "relative/path/to/jsonfile.json": "resources/jsonfile.json", - "resources/**/*": "resources/" + "resources/": "", + "docs/**/*md": "website-docs/" } } } ``` -:::note + + -In Tauri's [permission system](/reference/acl/capability/), absolute paths and paths containing parent components (`../`) can only be allowed via `"$RESOURCE/**"`. Relative paths like `"path/to/file.txt"` can be allowed explicitly via `"$RESOURCE/path/to/file.txt"`. +```json title=tauri.conf.json5 +{ + "bundle": { + "resources": { + // `textfile.txt` will be placed to `$RESOURCE/resources/textfile.txt` + "/absolute/path/to/textfile.txt": "resources/textfile.txt", -::: + // `jsonfile.json` will be placed to `$RESOURCE/resources/jsonfile.json` + "relative/path/to/jsonfile.json": "resources/jsonfile.json", -## Source path syntax + // Copy the entire directory to `$RESOURCE`, preserving the original structures, + // the target is "" which means it will be placed directly in the resource directory `$RESOURCE`, for example: + // - `resources/file.txt` -> `$RESOURCE/file.txt` + // - `resources/some-folder/config.json` -> `$RESOURCE/some-folder/config.json` + "resources/": "", + + // When using glob patterns, the behavior is different from the list one, + // all the matching files will be placed to the target directory without preserving the original file structures + // for example: + // - `docs/index.md` -> `$RESOURCE/website-docs/index.md` + // - `docs/plugins/setup.md` -> `$RESOURCE/website-docs/setup.md` + "docs/**/*md": "website-docs/" + } + } +} +``` + + + + +To learn about where `$RESOURCE` resolves to on each platforms, see the documentation of [`resource_dir`] + +
+Source path syntax In the following explanations "target resource directory" is either the value after the colon in the object notation, or a reconstruction of the original file paths in the array notation. @@ -57,19 +137,111 @@ In the following explanations "target resource directory" is either the value af - `"dir/**/*"`: copies all files in the `dir` directory _recursively_ (all files in `dir/` and all files in all sub-directories) into the target resource directory. - `"dir/**/**`: throws an error because `**` only matches directories and therefore no files can be found. -## Accessing files in Rust +
+ +## Resolve resource file paths -In this example we want to bundle additional i18n json files that look like this: +To resolve the path for a resource file, instead of manually calculating the path, use the following APIs -```json title=de.json + + + +On the Rust side, you need an instance of the [`PathResolver`] which you can get from [`App`] and [`AppHandle`], +then call [`PathResolver::resolve`]: + +```rust +tauri::Builder::default() + .setup(|app| { + let resource_path = app.path().resolve("lang/de.json", BaseDirectory::Resource)?; + Ok(()) + }) +``` + +To use it in a command: + +```rust +#[tauri::command] +fn hello(handle: tauri::AppHandle) { + let resource_path = handle.path().resolve("lang/de.json", BaseDirectory::Resource)?; +} +``` + + + + +To resolve the path in JavaScript, use [`resolveResource`]: + +```javascript +import { resolveResource } from '@tauri-apps/api/path'; +const resourcePath = await resolveResource('lang/de.json'); +``` + + + + +### Path syntax + +The path in the API calls can be either a normal relative path like `folder/json_file.json` that resolves to `$RESOURCE/folder/json_file.json`, +or a paths like `../relative/folder/toml_file.toml` that resolves to `$RESOURCE/_up_/relative/folder/toml_file.toml`, +these APIs use the same rules as you write `tauri.conf.json > bundle > resources`, for example: + +```json title=tauri.conf.json +{ + "bundle": { + "resources": ["folder/json_file.json", "../relative/folder/toml_file.toml"] + } +} +``` + +```rust +let json_path = app.path().resolve("folder/json_file.json", BaseDirectory::Resource)?; +let toml_path = app.path().resolve("../relative/folder/toml_file.toml", BaseDirectory::Resource)?; +``` + +### Android + +Currently the resources are stored in the APK as assets so the return value of those APIs are not normal file system paths, +we use a special URI prefix `asset://localhost/` here that can be used with the [`fs` plugin], +with that, you can read the files through [`FsExt::fs`] like this: + +```rust +let resource_path = app.path().resolve("lang/de.json", BaseDirectory::Resource).unwrap(); +let json = app.fs().read_to_string(&resource_path); +``` + +If you want or must have the resource files to be on a real file system, copy the contents out manually through the [`fs` plugin] + +## Reading resource files + +In this example we want to bundle additional i18n json files like this: + +``` +. +├── src-tauri/ +│ ├── tauri.conf.json +│ ├── lang/ +│ │ ├── de.json +│ │ └── en.json +│ └── ... +└── ... +``` + +```json title=tauri.conf.json +{ + "bundle": { + "resources": ["lang/*"] + } +} +``` + +```json title=lang/de.json { "hello": "Guten Tag!", "bye": "Auf Wiedersehen!" } ``` -In this case, we store these files in a `lang` directory next to the `tauri.conf.json`. -For this we add `"lang/*"` to `resources` as shown above. +### Rust On the Rust side, you need an instance of the [`PathResolver`] which you can get from [`App`] and [`AppHandle`]: @@ -80,8 +252,11 @@ tauri::Builder::default() // `tauri.conf.json > bundle > resources` let resource_path = app.path().resolve("lang/de.json", BaseDirectory::Resource)?; - let file = std::fs::File::open(&resource_path).unwrap(); - let lang_de: serde_json::Value = serde_json::from_reader(file).unwrap(); + let json = std::fs::read_to_string(&resource_path).unwrap(); + // Or when dealing with Android, use the file system plugin instead + // let json = app.fs().read_to_string(&resource_path); + + let lang_de: serde_json::Value = serde_json::from_str(json).unwrap(); // This will print 'Guten Tag!' to the terminal println!("{}", lang_de.get("hello").unwrap()); @@ -95,33 +270,30 @@ tauri::Builder::default() fn hello(handle: tauri::AppHandle) -> String { let resource_path = handle.path().resolve("lang/de.json", BaseDirectory::Resource)?; - let file = std::fs::File::open(&resource_path).unwrap(); - let lang_de: serde_json::Value = serde_json::from_reader(file).unwrap(); + let json = std::fs::read_to_string(&resource_path).unwrap(); + // Or when dealing with Android, use the file system plugin instead + // let json = handle.fs().read_to_string(&resource_path); + + let lang_de: serde_json::Value = serde_json::from_str(json).unwrap(); lang_de.get("hello").unwrap() } ``` -## Accessing files in JavaScript +### JavaScript -This is based on the example above. +For the JavaScript side, you can either use a command like the one above and call it through `await invoke('hello')` or access the files using the [`fs` plugin]. -Note that you must configure the access control list to enable any [`plugin-fs`] APIs you will need as well as permissions to access the `$RESOURCE` folder: +When using the [`fs` plugin], in addition to the [basic setup], you'll also need to configure the access control list to enable any plugin APIs you need as well as the permissions to access the `$RESOURCE` folder: -```json title=src-tauri/capabilities/default.json ins={14-15} +```json title=src-tauri/capabilities/default.json ins={8-9} { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "main-capability", "description": "Capability for the main window", "windows": ["main"], "permissions": [ - "path:default", - "event:default", - "window:default", - "app:default", - "resources:default", - "menu:default", - "tray:default", + "core:default", "fs:allow-read-text-file", "fs:allow-resource-read-recursive" ] @@ -142,10 +314,78 @@ const langDe = JSON.parse(await readTextFile(resourcePath)); console.log(langDe.hello); // This will print 'Guten Tag!' to the devtools console ``` -[tauri.bundle]: /reference/config/#bundleconfig -[`pathresolver`]: https://docs.rs/tauri/latest/tauri/struct.PathResolver.html +## Permissions + +Since we replace `../` to `_up_` in relative paths and the root to `_root_` in abosolute paths when using a list, +those files will be in sub folders inside the resource directory, +to allow those paths in Tauri's [permission system](/security/capabilities/), +use `$RESOURCE/**/*` to allow recursive access to those files + +### Examples + +With a file bundled like this: + +```json title=tauri.conf.json +{ + "bundle": { + "resources": ["../relative/path/to/jsonfile.json"] + } +} +``` + +To use it with the [`fs` plugin]: + +```json title=src-tauri/capabilities/default.json ins={8-15} +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + "core:default", + "fs:allow-stat", + "fs:allow-read-text-file", + "fs:allow-resource-read-recursive", + { + "identifier": "fs:scope", + "allow": ["$RESOURCE/**/*"], + "deny": ["$RESOURCE/secret.txt"] + } + ] +} +``` + +To use it with the [`opener` plugin]: + +```json title=src-tauri/capabilities/default.json ins={8-15} +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + "core:default", + { + "identifier": "opener:allow-open-path", + "allow": [ + { + "path": "$RESOURCE/**/*" + } + ] + } + ] +} +``` + +[`resource_dir`]: https://docs.rs/tauri/latest/tauri/path/struct.PathResolver.html#method.resource_dir +[`pathresolver`]: https://docs.rs/tauri/latest/tauri/path/struct.PathResolver.html +[`PathResolver::resolve`]: https://docs.rs/tauri/latest/tauri/path/struct.PathResolver.html#method.resolve +[`resolveResource`]: https://tauri.app/reference/javascript/api/namespacepath/#resolveresource [`app`]: https://docs.rs/tauri/latest/tauri/struct.App.html [`apphandle`]: https://docs.rs/tauri/latest/tauri/struct.AppHandle.html -[`plugin-fs`]: /reference/javascript/fs/ +[`fs` plugin]: /plugin/file-system/ +[`FsExt::fs`]: https://docs.rs/tauri-plugin-fs/latest/tauri_plugin_fs/trait.FsExt.html#tymethod.fs +[basic setup]: /plugin/file-system/#setup [Scope Permissions]: /plugin/file-system/#scopes [scopes]: /plugin/file-system/#scopes +[`opener` plugin]: /plugin/opener/ diff --git a/src/content/docs/develop/sidecar.mdx b/src/content/docs/develop/sidecar.mdx index 4ecaa79371..1b6dae053a 100644 --- a/src/content/docs/develop/sidecar.mdx +++ b/src/content/docs/develop/sidecar.mdx @@ -1,7 +1,5 @@ --- title: Embedding External Binaries -sidebar: - order: 1 i18nReady: true --- @@ -131,6 +129,31 @@ You can place this code inside a Tauri command to easily pass the AppHandle or y ## Running it from JavaScript +When running the sidecar, Tauri requires you to give the sidecar permission to run the `execute` or `spawn` method on the child process. To grant this permission, go to the file `/src-tauri/capabilities/default.json` and add the section below to the permissions array. Don't forget to name your sidecar according to the relative path mentioned earlier. + +```json title="src-tauri/capabilities/default.json" ins={4-12} +{ + "permissions": [ + "core:default", + { + "identifier": "shell:allow-execute", + "allow": [ + { + "name": "binaries/app", + "sidecar": true + } + ] + } + ] +} +``` + +:::note + +The `shell:allow-execute` identifier is used because the sidecar's child process will be started using the `command.execute()` method. To run it with `command.spawn()`, you need to change the identifier to `shell:allow-spawn` or add another entry to the array with the same structure as the one above, but with the identifier set to `shell:allow-spawn`. + +::: + In the JavaScript code, import the `Command` class from the `@tauri-apps/plugin-shell` module and use the `sidecar` static method. ```javascript @@ -147,24 +170,18 @@ The string provided to `Command.sidecar` must match one of the strings defined i You can pass arguments to Sidecar commands just like you would for running normal [Command][std::process::Command]. -Arguments can be either **static** (e.g. `-o` or `serve`) or **dynamic** (e.g. `` or `localhost:`). You define the arguments in the exact order in which you'd call them. Static arguments are defined as-is, while dynamic arguments can be defined using a regular expression. +Arguments can be either **static** (e.g. `-o` or `serve`) or **dynamic** (e.g. `` or `localhost:`). A value of `true` will allow any arguments to be passed to the command. `false` will disable all arguments. If neither `true` or `false` is set, you define the arguments in the exact order in which you'd call them. Static arguments are defined as-is, while dynamic arguments can be defined using a regular expression. First, define the arguments that need to be passed to the sidecar command in `src-tauri/capabilities/default.json`: -```json title="src-tauri/capabilities/default.json" ins={14-31} +```json title="src-tauri/capabilities/default.json" ins={8-24} { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", "description": "Capability for the main window", "windows": ["main"], "permissions": [ - "core:path:default", - "core:event:default", - "core:window:default", - "core:app:default", - "core:resources:default", - "core:menu:default", - "core:tray:default", + "core:default", { "identifier": "shell:allow-execute", "allow": [ @@ -181,8 +198,7 @@ First, define the arguments that need to be passed to the sidecar command in `sr "sidecar": true } ] - }, - "shell:allow-open" + } ] } ``` @@ -212,7 +228,7 @@ In JavaScript: ```javascript import { Command } from '@tauri-apps/plugin-shell'; -// notice that the args array matches EXACTLY what is specified on `tauri.conf.json`. +// notice that the args array matches EXACTLY what is specified in `capabilities/default.json`. const command = Command.sidecar('binaries/my-sidecar', [ 'arg1', '-a', diff --git a/src/content/docs/develop/state-management.mdx b/src/content/docs/develop/state-management.mdx index dd0a4dc5fb..715be48dfe 100644 --- a/src/content/docs/develop/state-management.mdx +++ b/src/content/docs/develop/state-management.mdx @@ -1,7 +1,6 @@ --- title: State Management -sidebar: - order: 1 +i18nReady: true --- In a Tauri application, you often need to keep track of the current state of your application or manage the lifecycle of things associated with it. Tauri provides an easy way to manage the state of your application using the [`Manager`] API, and read it when commands are called. @@ -89,6 +88,8 @@ It's a good idea to read the linked documentation fully to understand the trade- It's common to see [`Arc`] used in Rust to share ownership of a value across multiple threads (usually paired with a [`Mutex`] in the form of `Arc>`). However, you don't need to use [`Arc`] for things stored in [`State`] because Tauri will do this for you. +In case `State`'s lifetime requirements prevent you from moving your state into a new thread you can instead move an `AppHandle` into the thread and then retrieve your state as shown below in the "[Access state with the Manager trait](#access-state-with-the-manager-trait)" section. `AppHandle`s are deliberately cheap to clone for use-cases like this. + ## Accessing State ### Access state in commands @@ -106,7 +107,7 @@ For more information on commands, see [Calling Rust from the Frontend](/develop/ #### Async commands -If you are using `async` commands and want to use Tokio's async [`Mutex`], you can set it up the same way and access the state like this: +If you are using `async` commands and want to use Tokio's async [`Mutex`](https://docs.rs/tokio/latest/tokio/sync/struct.Mutex.html), you can set it up the same way and access the state like this: ```rust #[tauri::command] @@ -124,7 +125,8 @@ Note that the return type must be [`Result`] if you use asynchronous commands. Sometimes you may need to access the state outside of commands, such as in a different thread or in an event handler like `on_window_event`. In such cases, you can use the `state()` method of types that implement the [`Manager`] trait (such as the `AppHandle`) to get the state: ```rust -use tauri::{Builder, GlobalWindowEvent, Manager}; +use std::sync::Mutex; +use tauri::{Builder, Window, WindowEvent, Manager}; #[derive(Default)] struct AppState { @@ -132,9 +134,9 @@ struct AppState { } // In an event handler: -fn on_window_event(event: GlobalWindowEvent) { +fn on_window_event(window: &Window, _event: &WindowEvent) { // Get a handle to the app so we can get the global state. - let app_handle = event.window().app_handle(); + let app_handle = window.app_handle(); let state = app_handle.state::>(); // Lock the mutex to mutably access the state. diff --git a/src/content/docs/develop/updating-dependencies.mdx b/src/content/docs/develop/updating-dependencies.mdx index 3a2dc6e942..f1283001ac 100644 --- a/src/content/docs/develop/updating-dependencies.mdx +++ b/src/content/docs/develop/updating-dependencies.mdx @@ -1,7 +1,5 @@ --- title: Updating Dependencies -sidebar: - order: 1 i18nReady: true --- @@ -52,6 +50,12 @@ cargo update Alternatively, you can run the `cargo upgrade` command provided by [cargo-edit] which does all of this automatically. +## Sync npm Packages and Cargo Crates versions + +Since the JavaScript APIs rely on Rust code in the backend, adding a new feature requires upgrading both sides to ensure compatibility. Please make sure you have the same minor version of the npm package `@tauri-apps/api` and cargo crate `tauri` synced + +And for the plugins, we might introduce this type of changes in patch releases, so we bump the npm package and cargo crate versions together, and you need to keep the exact versions synced, for example, you need the same version (e.g. `2.2.1`) of the npm package `@tauri-apps/plugin-fs` and cargo crate `tauri-plugin-fs` + [`cargo outdated`]: https://github.com/kbknapp/cargo-outdated [tauri]: https://crates.io/crates/tauri/versions [tauri-build]: https://crates.io/crates/tauri-build/versions diff --git a/src/content/docs/distribute/Pipelines/crabnebula-cloud.mdx b/src/content/docs/distribute/Pipelines/crabnebula-cloud.mdx index ed8d8283f4..2622c26396 100644 --- a/src/content/docs/distribute/Pipelines/crabnebula-cloud.mdx +++ b/src/content/docs/distribute/Pipelines/crabnebula-cloud.mdx @@ -1,5 +1,6 @@ --- title: CrabNebula Cloud +i18nReady: true --- ## Distributing with CrabNebula Cloud diff --git a/src/content/docs/distribute/Pipelines/github.mdx b/src/content/docs/distribute/Pipelines/github.mdx index bbab520913..0dcf8a8ae9 100644 --- a/src/content/docs/distribute/Pipelines/github.mdx +++ b/src/content/docs/distribute/Pipelines/github.mdx @@ -1,5 +1,6 @@ --- title: GitHub +i18nReady: true --- This guide will show you how to use [tauri-action](https://github.com/tauri-apps/tauri-action) in [GitHub Actions](https://docs.github.com/en/actions) to easily build and upload your app, and how to make Tauri's updater query the newly created GitHub release for updates. @@ -50,7 +51,7 @@ For a full list of possible trigger configurations, check out the official [GitH Below is an example workflow that has been set up to run every time you push to the `release` branch. -This workflow will build and release your app for Linux x64, Windows x64, macOS x64 and macOS Arm64 (M1 and above). +This workflow will build and release your app for Windows x64, Linux x64, Linux Arm64, macOS x64 and macOS Arm64 (M1 and above). The steps this workflow takes are: @@ -84,6 +85,8 @@ jobs: args: '--target x86_64-apple-darwin' - platform: 'ubuntu-22.04' args: '' + - platform: 'ubuntu-22.04-arm' # Only available in public repos. + args: '' - platform: 'windows-latest' args: '' @@ -140,6 +143,10 @@ Carefully read through the [Usage limits, billing, and administration](https://d ## Arm Runner Compilation +:::note[August 2025 Update] +Github has [released](https://github.blog/changelog/2025-08-07-arm64-hosted-runners-for-public-repositories-are-now-generally-available/#get-started) publicly available `ubuntu-22.04-arm` and `ubuntu-24.04-arm` runners. You can use these to build your app for Arm64 in public repos with the workflow example above. +::: + This workflow uses [`pguyot/arm-runner-action`](https://github.com/pguyot/arm-runner-action) to compile directly on an emulated Arm runner. This bridges the gap for missing cross-architecture build support in the AppImage tooling. :::danger @@ -165,7 +172,7 @@ jobs: include: - arch: aarch64 cpu: cortex-a72 - base_image: https://dietpi.com/downloads/images/DietPi_RPi-ARMv8-Bookworm.img.xz + base_image: https://dietpi.com/downloads/images/DietPi_RPi5-ARMv8-Bookworm.img.xz deb: arm64 rpm: aarch64 appimage: aarch64 diff --git a/src/content/docs/distribute/Sign/android.mdx b/src/content/docs/distribute/Sign/android.mdx index daa2aa3165..0ab0a66998 100644 --- a/src/content/docs/distribute/Sign/android.mdx +++ b/src/content/docs/distribute/Sign/android.mdx @@ -3,10 +3,12 @@ title: Android Code Signing sidebar: label: Android order: 15 +i18nReady: true --- -import { Tabs, TabItem } from '@astrojs/starlight/components'; -import { Code } from '@astrojs/starlight/components'; +import { Image } from 'astro:assets'; +import { Code, Tabs, TabItem } from '@astrojs/starlight/components'; +import BuildGradleFiletree from '@assets/distribute/sign/build-gradle-kts-filetree.png'; To publish on the Play Store, you need to sign your app with a digital certificate. @@ -110,6 +112,22 @@ In this example the keystore was exported to base64 with `base64 -i /path/to/key Configure gradle to use your upload key when building your app in release mode by editing the `[project]/src-tauri/gen/android/app/build.gradle.kts` file. +:::tip + +There are multiple different `build.gradle.kts` files in a typical Android project. If there is no `buildTypes` block you're looking at the wrong file. The one you need is in the `app/` directory relative to the keystore file from the prior step. + +
+ + Click here for a screenshot showing its location in a typical file tree. + + build.gradle.kts location in file tree +
+ +::: + 1. Add the needed import at the beginning of the file: ```kotlin diff --git a/src/content/docs/distribute/Sign/ios.mdx b/src/content/docs/distribute/Sign/ios.mdx index 5ab0f05d7f..6f5acbd73e 100644 --- a/src/content/docs/distribute/Sign/ios.mdx +++ b/src/content/docs/distribute/Sign/ios.mdx @@ -3,6 +3,7 @@ title: iOS Code Signing sidebar: label: iOS order: 14 +i18nReady: true --- Code signing on iOS is required to distribute your application through the official [Apple App Store] or possibly alternative marketplaces in the European Union and in general to install and execute on end user devices. diff --git a/src/content/docs/distribute/Sign/linux.mdx b/src/content/docs/distribute/Sign/linux.mdx index 7a1aba2408..ac4b786bba 100644 --- a/src/content/docs/distribute/Sign/linux.mdx +++ b/src/content/docs/distribute/Sign/linux.mdx @@ -3,6 +3,7 @@ title: Linux Code Signing sidebar: label: Linux order: 13 +i18nReady: true --- This guide provides information on code signing for Linux packages. @@ -47,12 +48,35 @@ Note that you need to change the $APPNAME and $VERSION values with the correct o **The signature is not verified** AppImage does not validate the signature, so you can't rely on it to check whether the file has been tampered with or not. -To validate the signature, you must provide an external tool for your users. -This requires you to publish your public key on an authenticated channel (e.g. your website served via TLS), -so the end user can download and verify. +The user must manually verify the signature using the AppImage validate tool. +This requires you to publish your key ID on an authenticated channel (e.g. your website served via TLS), +so the end user can view and verify. See [the official AppImage documentation] for additional information. ::: [the official appimage documentation]: https://docs.appimage.org/packaging-guide/optional/signatures.html + +### Validate the signature + +The AppImage validate tool can be downloaded from [here](https://github.com/AppImageCommunity/AppImageUpdate/releases/tag/continuous). +Select one of the `validate-$PLATFORM.AppImage` files. + +Run the following command to validate the signature: + +```shell +chmod +x validate-$PLATFORM.AppImage +./validate-$PLATFORM.AppImage $TAURI_OUTPUT.AppImage +``` + +If the signature is valid, the output will be: + +``` +Validation result: validation successful +Signatures found with key fingerprints: $KEY_ID +==================== +Validator report: +Signature checked for key with fingerprint $KEY_ID: +Validation successful +``` diff --git a/src/content/docs/distribute/Sign/macos.mdx b/src/content/docs/distribute/Sign/macos.mdx index 960299e6ff..c944598006 100644 --- a/src/content/docs/distribute/Sign/macos.mdx +++ b/src/content/docs/distribute/Sign/macos.mdx @@ -3,13 +3,16 @@ title: macOS Code Signing sidebar: label: macOS order: 11 +i18nReady: true --- +import { Tabs, TabItem } from '@astrojs/starlight/components'; + Code signing is required on macOS to allow your application to be listed in the [Apple App Store] and to prevent a warning that your application is broken and can not be started, when downloaded from the browser. ## Prerequisites -Code signing on macOS requires an [Apple Developer] account which is either paid (99$ per year) or on the free plan. You also need an Apple device where you perform the code signing. This is required by the signing process and due to Apple's Terms and Conditions. +Code signing on macOS requires an [Apple Developer] account which is either paid (99$ per year) or on the free plan (only for testing and development purposes). You also need an Apple device where you perform the code signing. This is required by the signing process and due to Apple's Terms and Conditions. :::note Note when using a free Apple Developer account, you will not be able to notarize your application and it will still show up as not verified when opening the app. @@ -51,7 +54,7 @@ With the certificate installed in your Mac computer keychain, you can configure The name of the certificate's keychain entry represents the `signing identity`, which can also be found by executing: -``` +```sh security find-identity -v -p codesigning ``` @@ -78,7 +81,7 @@ and configure the `APPLE_CERTIFICATE` and `APPLE_CERTIFICATE_PASSWORD` environme 3. Select the path to save the certificate's `.p12` file and define a password for the exported certificate. 4. Convert the `.p12` file to base64 running the following script on the terminal: -``` +```sh openssl base64 -in /path/to/certificate.p12 -out certificate-base64.txt ``` @@ -98,6 +101,8 @@ Required secrets: - `APPLE_CERTIFICATE_PASSWORD` - The password for your exported `.p12` file - `KEYCHAIN_PASSWORD` - The password for your keychain +Check out the official GitHub guide to learn [how to set up secrets](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository). + ```yaml name: 'build' @@ -131,6 +136,7 @@ jobs: security create-keychain -p "$KEYCHAIN_PASSWORD" build.keychain security default-keychain -s build.keychain security unlock-keychain -p "$KEYCHAIN_PASSWORD" build.keychain + security set-keychain-settings -t 3600 -u build.keychain security import certificate.p12 -k build.keychain -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" build.keychain security find-identity -v -p codesigning build.keychain @@ -154,27 +160,53 @@ jobs: ## Notarization -To notarize your application, you must provide credentials for Tauri to authenticate with Apple: +To notarize your application, you must provide credentials for Tauri to authenticate with Apple. This can be done via the App Store Connect API, or via your Apple ID. -- APPLE_API_ISSUER, APPLE_API_KEY and APPLE_API_KEY_PATH: authenticate using an App Store Connect API key + + + 1. Open the [App Store Connect's Users and Access page], select the Integrations tab, click on the Add button and select a name and the Developer access. + 2. Set the `APPLE_API_ISSUER` environment variable to the value presented above the keys table. + 3. Set the `APPLE_API_KEY` environment variable to the value on the Key ID column on that table. + 4. Download the private key, which can only be done once and is only visible after a page reload (the button is shown on the table row for the newly created key). + 5. Set the `APPLE_API_KEY_PATH` environment variable to the file path of the downloaded private key. + - Open the [App Store Connect's Users and Access page], select the Integrations tab, click on the Add button and select a name and the Developer access. - The APPLE_API_ISSUER (Issuer ID) is presented above the keys table, and the APPLE_API_KEY is the value on the Key ID column on that table. - You also need to download the private key, which can only be done once and is only visible after a page reload (the button is shown on the table row for the newly created key). - The private key file path must be set via the APPLE_API_KEY_PATH environment variable. - -- APPLE_ID, APPLE_PASSWORD and APPLE_TEAM_ID: authenticate using your Apple ID - - Alternatively, to authenticate with your Apple ID, set the APPLE_ID to your Apple account email and the APPLE_PASSWORD to an app-specific password for the Apple account. + + 1. Set the `APPLE_ID` environment variable to your Apple account email. + 2. Set the `APPLE_PASSWORD` environment variable to an [app-specific password] for your Apple account. + 3. Set the `APPLE_TEAM_ID` environment variable to your Apple Team ID. You can find your Team ID in [your account's membership page][membership]. + + :::note Notarization is required when using a _Developer ID Application_ certificate. ::: [Certificates]: https://developer.apple.com/account/resources/certificates/list +[membership]: https://developer.apple.com/account#MembershipDetailsCard [Apple Developer]: https://developer.apple.com [Apple App Store]: https://www.apple.com/app-store/ [App Store Connect's Users and Access page]: https://appstoreconnect.apple.com/access/users [`tauri.conf.json > bundle > macOS > signingIdentity`]: /reference/config/#signingidentity [creating a certificate signing request]: https://developer.apple.com/help/account/create-certificates/create-a-certificate-signing-request [Certificates, IDs & Profiles page]: https://developer.apple.com/account/resources/certificates/list +[app-specific password]: https://support.apple.com/en-ca/HT204397 + +## Ad-Hoc Signing + +If you do not wish to provide an Apple-authenticated identity, but still wish to sign your application, you can configure an _ad-hoc_ signature. + +This is useful on ARM (Apple Silicon) devices, where code-signing is required for all apps from the Internet. + +:::caution +Ad-hoc code signing does not prevent MacOS from requiring users to +[whitelist the installation in their Privacy & Security settings](https://support.apple.com/guide/mac-help/open-a-mac-app-from-an-unknown-developer-mh40616/mac). +::: + +To configure an ad-hoc signature, provide the pseudo-identity `-` to Tauri, e.g. + +```json +"signingIdentity": "-" +``` + +For details on configuring Tauri's signing identity, see [above](#configuring-tauri). diff --git a/src/content/docs/distribute/Sign/windows.mdx b/src/content/docs/distribute/Sign/windows.mdx index 4f8354b911..e9ce370e44 100644 --- a/src/content/docs/distribute/Sign/windows.mdx +++ b/src/content/docs/distribute/Sign/windows.mdx @@ -3,6 +3,7 @@ title: Windows Code Signing sidebar: label: Windows order: 12 +i18nReady: true --- import { Steps } from '@astrojs/starlight/components'; @@ -46,9 +47,7 @@ There are a few things we have to do to get Windows prepared for code signing. T 1. #### Convert your `.cer` to `.pfx` - - You will need the following: - - certificate file (mine is `cert.cer`) - private key file (mine is `private-key.key`) @@ -59,7 +58,6 @@ There are a few things we have to do to get Windows prepared for code signing. T - You should be prompted to enter an export password **DON'T FORGET IT!** 2. #### Import your `.pfx` file into the keystore. - - We now need to import our `.pfx` file. - Assign your export password to a variable using `$WINDOWS_PFX_PASSWORD = 'MYPASSWORD'` @@ -67,7 +65,6 @@ There are a few things we have to do to get Windows prepared for code signing. T - Now Import the certificate using `Import-PfxCertificate -FilePath certificate.pfx -CertStoreLocation Cert:\CurrentUser\My -Password (ConvertTo-SecureString -String $WINDOWS_PFX_PASSWORD -Force -AsPlainText)` 3. #### Prepare Variables - - Start ➡️ `certmgr.msc` to open Personal Certificate Management, then open Personal/Certificates. - Find the certificate we just imported and double-click on it, then click on the Details tab. @@ -128,7 +125,6 @@ The secrets we used are as follows #### Workflow Modifications 1. We need to add a step in the workflow to import the certificate into the Windows environment. This workflow accomplishes the following - 1. Assign GitHub secrets to environment variables 2. Create a new `certificate` directory 3. Import `WINDOWS_CERTIFICATE` into tempCert.txt @@ -255,7 +251,7 @@ To configure Tauri to use your Azure Key Vault configuration for signing change [relic] must authenticate with Azure in order to load the certificate. In the Azure portal landing page, go to the "Microsoft Entra ID" service and head to the "Manage > App registrations" page. Click "New registration" to create a new app. After creating the app, you are redirected to the application details page where you can see the "Application (client) ID" and "Directory (tenant) ID" values. -Set these IDs to the `AZURE_VAULT_ID` and `AZURE_TENANT_ID` environment variables respectively. +Set these IDs to the `AZURE_CLIENT_ID` and `AZURE_TENANT_ID` environment variables respectively. In the "Manage > Certificates & secrets" page click the "New client secret" button and set the text in the "Value" column as the `AZURE_CLIENT_SECRET` environment variable. @@ -306,30 +302,26 @@ You need to install [trusted-signing-cli](https://github.com/Levminer/trusted-si 1. #### Install trusted-signing-cli - - `cargo install trusted-signing-cli` 2. #### Configure environment variables - - trusted-signing-cli needs the following environment variables to be set, don't forget to add these as Github Actions [secrets](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions): - - `AZURE_CLIENT_ID`: The client ID of your [App Registration](https://melatonin.dev/blog/code-signing-on-windows-with-azure-trusted-signing/#step-4-create-app-registration-user-credentials) - `AZURE_CLIENT_SECRET`: The client secret of [App Registration](https://melatonin.dev/blog/code-signing-on-windows-with-azure-trusted-signing/#step-4-create-app-registration-user-credentials) - `AZURE_TENANT_ID`: The tenant ID of your Azure directory, you can also get this from your [App Registration](https://melatonin.dev/blog/code-signing-on-windows-with-azure-trusted-signing/#step-4-create-app-registration-user-credentials) 3. ### Modify your `tauri.conf.json` file - - You can modify your `tauri.conf.json` or you can create a specific config file for Windows. Replace the URL and the certificate name with your own values. - - -e: The endpoint of your Azure Code Signing account - -a: The name of your Azure Code Signing Account - -c: The name of your Certificate profile inside your Azure Code Signing Account + - -d: The description of the signed content (optional). When signing a .msi installer, this description will appear as the installer's name in the UAC prompt or will be a random string of characters if unset. ```json title=tauri.conf.json { "bundle": { "windows": { - "signCommand": "trusted-signing-cli -e https://wus2.codesigning.azure.net -a MyAccount -c MyProfile %1" + "signCommand": "trusted-signing-cli -e https://wus2.codesigning.azure.net -a MyAccount -c MyProfile -d MyApp %1" } } } diff --git a/src/content/docs/distribute/app-store.mdx b/src/content/docs/distribute/app-store.mdx index a992797685..da386821b8 100644 --- a/src/content/docs/distribute/app-store.mdx +++ b/src/content/docs/distribute/app-store.mdx @@ -2,6 +2,7 @@ title: App Store sidebar: order: 1 +i18nReady: true --- import CommandTabs from '@components/CommandTabs.astro'; @@ -27,6 +28,7 @@ After running `tauri ios init` to setup the Xcode project, you can use the `taur yarn="yarn tauri icon /path/to/app-icon.png --ios-color #fff" pnpm="pnpm tauri icon /path/to/app-icon.png --ios-color #fff" deno="deno task tauri icon /path/to/app-icon.png --ios-color #fff" + bun="bun tauri icon /path/to/app-icon.png --ios-color #fff" cargo="cargo tauri icon /path/to/app-icon.png --ios-color #fff" /> @@ -45,6 +47,20 @@ The value provided in the _Bundle ID_ field **must** match the identifier define The Tauri CLI can package your app for macOS and iOS. Running on a macOS machine is a requirement. +Tauri derives the [`CFBundleVersion`](https://developer.apple.com/documentation/bundleresources/information-property-list/cfbundleversion) from the value defined in [`tauri.conf.json > version`]. +You can set a custom bundle version in the [`tauri.conf.json > bundle > iOS > bundleVersion`] or [`tauri.conf.json > bundle > macOS > bundleVersion`] configuration +if you need a different bundle version scheme e.g. sequential codes: + +```json title="tauri.conf.json" ins={4} +{ + "bundle": { + "iOS": { + "bundleVersion": "100" + } + } +} +``` + :::caution Code signing is required. See the documentation for [macOS][macOS code signing] and [iOS][iOS code signing]. ::: @@ -57,6 +73,7 @@ To open the iOS project in Xcode for building you must run the following command yarn="yarn tauri ios build --open" pnpm="pnpm tauri ios build --open" deno="deno task tauri ios build --open" + bun="bun tauri ios build --open" cargo="cargo tauri ios build --open" /> @@ -100,6 +117,8 @@ yarn tauri bundle --bundles app --target universal-apple-darwin --config src-tau pnpm tauri bundle --bundles app --target universal-apple-darwin --config src-tauri/tauri.appstore.conf.json" deno="deno task tauri build --no-bundle deno task tauri bundle --bundles app --target universal-apple-darwin --config src-tauri/tauri.appstore.conf.json" + bun="bun tauri build --no-bundle +bun tauri bundle --bundles app --target universal-apple-darwin --config src-tauri/tauri.appstore.conf.json" cargo="cargo tauri build --no-bundle cargo tauri bundle --bundles app --target universal-apple-darwin --config src-tauri/tauri.appstore.conf.json" /> @@ -281,6 +300,7 @@ To build your iOS app, run the `tauri ios build` command: yarn="yarn tauri ios build --export-method app-store-connect" pnpm="pnpm tauri ios build --export-method app-store-connect" deno="deno task tauri ios build --export-method app-store-connect" + bun="bun tauri ios build --export-method app-store-connect" cargo="cargo tauri ios build --export-method app-store-connect" /> diff --git a/src/content/docs/distribute/appimage.mdx b/src/content/docs/distribute/appimage.mdx index 31a5488cef..fe5971b1e3 100644 --- a/src/content/docs/distribute/appimage.mdx +++ b/src/content/docs/distribute/appimage.mdx @@ -2,15 +2,28 @@ title: AppImage sidebar: order: 1 +i18nReady: true --- `AppImage` is a distribution format that does not rely on the system installed packages and instead bundles all dependencies and files needed by the application. For this reason, the output file is larger but easier to distribute since it is supported on many Linux distributions and can be executed without installation. The user just needs to make the file executable (`chmod a+x MyProject.AppImage`) and can then run it (`./MyProject.AppImage`). AppImages are convenient, simplifying the distribution process if you cannot make a package targeting the distribution's package manager. Still, you should carefully use it as the file size grows from the 2-6 MB range to 70+ MB. +:::note + +GUI apps on macOS and Linux do not inherit the `$PATH` from your shell dotfiles (`.bashrc`, `.bash_profile`, `.zshrc`, etc). Check out Tauri's [fix-path-env-rs](https://github.com/tauri-apps/fix-path-env-rs) crate to fix this issue. + +::: + +## Limitations + +Core libraries such as glibc frequently break compatibility with older systems. For this reason, you must build your Tauri application using the oldest base system you intend to support. A relatively old system such as Ubuntu 18.04 is more suited than Ubuntu 22.04, as the binary compiled on Ubuntu 22.04 will have a higher requirement of the glibc version, so when running on an older system, you will face a runtime error like `/usr/lib/libc.so.6: version 'GLIBC_2.33' not found`. We recommend using a Docker container or GitHub Actions to build your Tauri application for Linux. + +See the issues [tauri-apps/tauri#1355](https://github.com/tauri-apps/tauri/issues/1355) and [rust-lang/rust#57497](https://github.com/rust-lang/rust/issues/57497), in addition to the [AppImage guide](https://docs.appimage.org/reference/best-practices.html#binaries-compiled-on-old-enough-base-system) for more information. + ## Multimedia support via GStreamer -If your app plays audio/video you need to enable `tauri.conf.json > bundle > appimage > bundleMediaFramework`. This will increase the size of the AppImage bundle to include additional gstreamer files needed for media playback. This flag is currently only fully supported on Ubuntu build systems. Make sure that your build system has all the plugins your app may need at runtime. +If your app plays audio/video you need to enable `tauri.conf.json > bundle > linux > appimage > bundleMediaFramework`. This will increase the size of the AppImage bundle to include additional gstreamer files needed for media playback. This flag is currently only fully supported on Ubuntu build systems. Make sure that your build system has all the plugins your app may need at runtime. :::caution @@ -47,6 +60,10 @@ Note that the destination paths must currently begin with `/usr/`. ## AppImages for ARM-based devices +:::note[August 2025 Update] +Github has [released](https://github.blog/changelog/2025-08-07-arm64-hosted-runners-for-public-repositories-are-now-generally-available/#get-started) publicly available `ubuntu-22.04-arm` and `ubuntu-24.04-arm` runners. You can use these to build your app with no changes, a typical build should take ~10 minutes. +::: + `linuxdeploy`, the AppImage tooling Tauri uses, currently [does not support cross-compiling] ARM AppImages. This means ARM AppImages can only be built on ARM devices or emulators. Check out our [GitHub Action guide](/distribute/pipelines/github/#arm-runner-compilation) for an example workflow that leverages QEMU to build the app. Note that this is extremely slow and only recommended in public repositories where Build Minutes are free. In private repositories GitHub's ARM runners should be more cost-efficient and much easier to set up. diff --git a/src/content/docs/distribute/aur.mdx b/src/content/docs/distribute/aur.mdx index 0fe4c658eb..e553dc1794 100644 --- a/src/content/docs/distribute/aur.mdx +++ b/src/content/docs/distribute/aur.mdx @@ -2,6 +2,7 @@ title: AUR sidebar: order: 1 +i18nReady: true --- # Publishing To The Arch User Repository @@ -25,12 +26,12 @@ pkgrel=1 pkgdesc="Description of your app" arch=('x86_64' 'aarch64') url="https://github.com//" -license=('mit') -depends=('cairo' 'desktop-file-utils' 'gdk-pixbuf2' 'glib2' 'gtk3' 'hicolor-icon-theme' 'libsoup' 'pango' 'webkit2gtk') +license=('MIT') +depends=('cairo' 'desktop-file-utils' 'gdk-pixbuf2' 'glib2' 'gtk3' 'hicolor-icon-theme' 'libsoup' 'pango' 'webkit2gtk-4.1') options=('!strip' '!emptydirs') install=${pkgname}.install -source_x86_64=("https://github.com///releases/download/v$pkgver/appname_"$pkgver"_amd64.deb") -source_aarch64=("https://github.com///releases/download/v$pkgver/appname_"$pkgver"_arm64.deb") +source_x86_64=("${url}/releases/download/v${pkgver}/appname_${pkgver}_amd64.deb") +source_aarch64=("${url}/releases/download/v${pkgver}/appname_"${pkgver}_arm64.deb") ``` - At the top of the file, define your package name and assign it the variable `pkgname`. @@ -38,25 +39,25 @@ source_aarch64=("https://github.com///releases/download/v$pkgver/ - The `pkgdesc` variable on your aur repo's page and tells vistors what your app does. - The `arch` variable controls what architectures can install your package. - The `url` variable, while not required, helps to make your package appear more professional. -- The `install` variable defines a file that runs the installation commands. +- The `install` variable specifies the name of .install script which will be run when the package is installed, removed or upgraded. - The `depends` variable includes a list of items that are required to make your app run. For any Tauri app you must include all of the dependencies shown above. - The `source` variable is required and defines the location where your upstream package is. You can make a `source` architecture specific by adding the architecture to the end of the variable name. -### Generating `SRCINFO` +### Generating `.SRCINFO` -In order to push your repo to the aur you must generate an `srcinfo` file. This can be done with this command. +In order to push your repo to the aur you must generate an `.SRCINFO` file. This can be done with this command. ```sh -makepkg --printsrcinfo >> .SRCINFO +makepkg --printsrcinfo > .SRCINFO ``` ### Testing -Testing the app is extremely simple. All you have to do is run makepkg -f within the same directory as the pkgbuild file and see if it works +Testing the app is extremely simple. All you have to do is run `makepkg` within the same directory as the `PKGBUILD` file and see if it works ### Publishing -Finally, after the testing phase is over, you can publish the application to the arch user repository with these commands. +Finally, after the testing phase is over, you can publish the application to AUR (Arch User Repository) with these commands. ```sh git add . @@ -66,7 +67,7 @@ git commit -m "Initial Commit" git push ``` -If all goes well, your repository should now appear on the aur website. +If all goes well, your repository should now appear on the AUR website. ## Examples @@ -81,18 +82,17 @@ pkgrel=1 pkgdesc="Description of your app" arch=('x86_64' 'aarch64') url="https://github.com//" -license=('mit') -depends=('cairo' 'desktop-file-utils' 'gdk-pixbuf2' 'glib2' 'gtk3' 'hicolor-icon-theme' 'libsoup' 'pango' 'webkit2gtk') -options=('!strip' '!emptydirs') +license=('MIT') +depends=('cairo' 'desktop-file-utils' 'gdk-pixbuf2' 'glib2' 'gtk3' 'hicolor-icon-theme' 'libsoup' 'pango' 'webkit2gtk-4.1') +options=('!strip' '!debug') install=${pkgname}.install -source_x86_64=("https://github.com///releases/download/v$pkgver/appname_"$pkgver"_amd64.deb") -source_aarch64=("https://github.com///releases/download/v$pkgver/appname_"$pkgver"_arm64.deb") +source_x86_64=("${url}/releases/download/v${pkgver}/appname_${pkgver}_amd64.deb") +source_aarch64=("${url}/releases/download/v${pkgver}/appname_${pkgver}_arm64.deb") sha256sums_x86_64=('ca85f11732765bed78f93f55397b4b4cbb76685088553dad612c5062e3ec651f') sha256sums_aarch64=('ed2dc3169d34d91188fb55d39867713856dd02a2360ffe0661cb2e19bd701c3c') package() { - # Extract package data - tar -xz -f data.tar.gz -C "${pkgdir}" + tar -xvf data.tar.gz -C "${pkgdir}" } ``` @@ -119,39 +119,39 @@ post_remove() { ```ini title="PKGBUILD" # Maintainer: pkgname=-git -pkgver=1.1.0 +pkgver= pkgrel=1 pkgdesc="Description of your app" -arch=('any') +arch=('x86_64' 'aarch64') url="https://github.com//" -license=('mit') -depends=('cairo' 'desktop-file-utils' 'gdk-pixbuf2' 'glib2' 'gtk3' 'hicolor-icon-theme' 'libsoup' 'pango' 'webkit2gtk') -makedepends=('git' 'file' 'openssl' 'appmenu-gtk-module' 'libappindicator-gtk3' 'librsvg' 'base-devel' 'curl' 'wget' 'rustup' 'npm' 'nodejs' 'dpkg') +license=('MIT') +depends=('cairo' 'desktop-file-utils' 'gdk-pixbuf2' 'glib2' 'gtk3' 'hicolor-icon-theme' 'libsoup' 'pango' 'webkit2gtk-4.1') +makedepends=('git' 'openssl' 'appmenu-gtk-module' 'libappindicator-gtk3' 'librsvg' 'cargo' 'pnpm' 'nodejs') provides=('') conflicts=('' '') -options=('!strip' '!emptydirs') -source=('git+https://github.com//') +source=("git+${url}.git") sha256sums=('SKIP') -prepare() { + +pkgver() { cd - npm install - npm run tauri build + ( set -o pipefail + git describe --long --abbrev=7 2>/dev/null | sed 's/\([^-]*-g\)/r\1/;s/-/./g' || + printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short=7 HEAD)" + ) } -package() { - cd "$srcdir"//src-tauri/target/*unknown-linux*/release/bundle/deb - dpkg-deb -x *.deb here - cd here - install -Dm755 usr/bin/myapp "$pkgdir"/usr/bin/myapp +prepare() { + cd + pnpm install +} - # Install desktop file - install -Dm644 usr/share/applications/myapp.desktop "$pkgdir"/usr/share/applications/myapp.desktop +build() { + cd + pnpm tauri build -b deb +} - # Install icons - install -Dm644 usr/share/icons/hicolor/128x128/apps/myapp.png "$pkgdir"/usr/share/icons/hicolor/128x128/apps/myapp.png - install -Dm644 usr/share/icons/hicolor/256x256@2/apps/myapp.png "$pkgdir"/usr/share/icons/hicolor/256x256@2/apps/myapp.png - install -Dm644 usr/share/icons/hicolor/32x32/apps/myapp.png "$pkgdir"/usr/share/icons/hicolor/32x32/apps/myapp.png - # Extract package data +package() { + cp -a /src-tauri/target/release/bundle/deb/_${pkgver}_*/data/* "${pkgdir}" } ``` diff --git a/src/content/docs/distribute/crabnebula-cloud.mdx b/src/content/docs/distribute/crabnebula-cloud.mdx index 1d36a807ea..dc0a89f415 100644 --- a/src/content/docs/distribute/crabnebula-cloud.mdx +++ b/src/content/docs/distribute/crabnebula-cloud.mdx @@ -3,6 +3,7 @@ title: Distributing with CrabNebula Cloud sidebar: label: CrabNebula Cloud order: 1 +i18nReady: true --- [CrabNebula] is an official Tauri partner providing services and tooling for Tauri applications. diff --git a/src/content/docs/distribute/debian.mdx b/src/content/docs/distribute/debian.mdx index d19b7f93aa..143169df0f 100644 --- a/src/content/docs/distribute/debian.mdx +++ b/src/content/docs/distribute/debian.mdx @@ -2,15 +2,27 @@ title: Debian sidebar: order: 1 +i18nReady: true --- -{/* Is this about building .deb files, creating PPAs, or adding something to the debian/ubuntu repos? */} - -## Debian +import ShowSolution from '@components/ShowSolution.astro'; +import { Steps } from '@astrojs/starlight/components'; The stock Debian package generated by the Tauri bundler has everything you need to ship your application to Debian-based Linux distributions, defining your application's icons, generating a Desktop file, and specifying the dependencies `libwebkit2gtk-4.1-0` and `libgtk-3-0`, along with `libappindicator3-1` if your app uses the system tray. -### Custom Files +:::note + +GUI apps on macOS and Linux do not inherit the `$PATH` from your shell dotfiles (`.bashrc`, `.bash_profile`, `.zshrc`, etc). Check out Tauri's [fix-path-env-rs](https://github.com/tauri-apps/fix-path-env-rs) crate to fix this issue. + +::: + +## Limitations + +Core libraries such as glibc frequently break compatibility with older systems. For this reason, you must build your Tauri application using the oldest base system you intend to support. A relatively old system such as Ubuntu 18.04 is more suited than Ubuntu 22.04, as the binary compiled on Ubuntu 22.04 will have a higher requirement of the glibc version, so when running on an older system, you will face a runtime error like `/usr/lib/libc.so.6: version 'GLIBC_2.33' not found`. We recommend using a Docker container or GitHub Actions to build your Tauri application for Linux. + +See the issues [tauri-apps/tauri#1355](https://github.com/tauri-apps/tauri/issues/1355) and [rust-lang/rust#57497](https://github.com/rust-lang/rust/issues/57497), in addition to the [AppImage guide](https://docs.appimage.org/reference/best-practices.html#binaries-compiled-on-old-enough-base-system) for more information. + +## Custom Files Tauri exposes a few configurations for the Debian package in case you need more control. @@ -32,3 +44,141 @@ To include custom files in the Debian package, you can provide a list of files o } } ``` + +## Cross-Compiling for ARM-based Devices + +This guide covers manual compilation. Check out our [GitHub Action guide](/distribute/pipelines/github/#arm-runner-compilation) for an example workflow that leverages QEMU to build the app. This will be much slower but will also be able to build AppImages. + +Manual compilation is suitable when you don't need to compile your application frequently and prefer a one-time setup. The following steps expect you to use a Linux distribution based on Debian/Ubuntu. + + + +1. #### Install Rust targets for your desired architecture + - For ARMv7 (32-bit): `rustup target add armv7-unknown-linux-gnueabihf` + - For ARMv8 (ARM64, 64-bit): `rustup target add aarch64-unknown-linux-gnu` + +2. #### Install the corresponding linker for your chosen architecture + - For ARMv7: `sudo apt install gcc-arm-linux-gnueabihf` + - For ARMv8 (ARM64): `sudo apt install gcc-aarch64-linux-gnu` + +3. #### Open or create the file `/.cargo/config.toml` and add the following configurations accordingly + + ```toml + [target.armv7-unknown-linux-gnueabihf] + linker = "arm-linux-gnueabihf-gcc" + + [target.aarch64-unknown-linux-gnu] + linker = "aarch64-linux-gnu-gcc" + ``` + +4. #### Enable the respective architecture in the package manager + - For ARMv7: `sudo dpkg --add-architecture armhf` + - For ARMv8 (ARM64): `sudo dpkg --add-architecture arm64` + +5. #### Adjusting Package Sources + + On Debian, this step should not be necessary, but on other distributions, you might need to edit /etc/apt/sources.list to include the ARM architecture variant. For example on Ubuntu 22.04 add these lines to the bottom of the file (Remember to replace jammy with the codename of your Ubuntu version): + + ``` + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy main restricted + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates main restricted + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy universe + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates universe + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy multiverse + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates multiverse + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-backports main restricted universe multiverse + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security main restricted + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security universe + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security multiverse + ``` + + Then, to prevent issues with the main packages, you have to add the correct main architecture to all other lines the file contained beforehand. For standard 64-bit systems you need to add [arch=amd64], the full file on Ubuntu 22.04 then looks similar to this: + + + + ``` + # See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to + # newer versions of the distribution. + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy main restricted + # deb-src http://archive.ubuntu.com/ubuntu/ jammy main restricted + + ## Major bug fix updates produced after the final release of the + ## distribution. + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted + # deb-src http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted + + ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu + ## team. Also, please note that software in universe WILL NOT receive any + ## review or updates from the Ubuntu security team. + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy universe + # deb-src http://archive.ubuntu.com/ubuntu/ jammy universe + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy-updates universe + # deb-src http://archive.ubuntu.com/ubuntu/ jammy-updates universe + + ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu + ## team, and may not be under a free licence. Please satisfy yourself as to + ## your rights to use the software. Also, please note that software in + ## multiverse WILL NOT receive any review or updates from the Ubuntu + ## security team. + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy multiverse + # deb-src http://archive.ubuntu.com/ubuntu/ jammy multiverse + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy-updates multiverse + + ## N.B. software from this repository may not have been tested as + ## extensively as that contained in the main release, although it includes + ## newer versions of some applications which may provide useful features. + ## Also, please note that software in backports WILL NOT receive any review + ## or updates from the Ubuntu security team. + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy-backports main restricted universe multiverse + # deb-src http://archive.ubuntu.com/ubuntu/ jammy-backports main restricted universe multiverse + + deb [arch=amd64] http://security.ubuntu.com/ubuntu/ jammy-security main restricted + # deb-src http://security.ubuntu.com/ubuntu/ jammy-security main restricted + deb [arch=amd64] http://security.ubuntu.com/ubuntu/ jammy-security universe + # deb-src http://security.ubuntu.com/ubuntu/ jammy-security universe + deb [arch=amd64] http://security.ubuntu.com/ubuntu/ jammy-security multiverse + # deb-src http://security.ubuntu.com/ubuntu/ jammy-security multiverse + + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy main restricted + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates main restricted + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy universe + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates universe + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy multiverse + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates multiverse + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-backports main restricted universe multiverse + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security main restricted + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security universe + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security multiverse + ``` + + + +6. #### Update the package information: `sudo apt-get update && sudo apt-get upgrade -y` + +7. #### Install the required webkitgtk library for your chosen architecture + - For ARMv7: `sudo apt install libwebkit2gtk-4.1-dev:armhf` + - For ARMv8 (ARM64): `sudo apt install libwebkit2gtk-4.1-dev:arm64` + +8. #### Install OpenSSL or use a vendored version + + This is not always required so you may want to proceed first and check if you see errors like `Failed to find OpenSSL development headers`. + - Either install the development headers system-wide: + - For ARMv7: `sudo apt install libssl-dev:armhf` + - For ARMv8 (ARM64): `sudo apt install libssl-dev:arm64` + - Or enable the vendor feature for the OpenSSL Rust crate which will affect all other Rust dependencies using the same minor version. You can do so by adding this to the dependencies section in your `Cargo.toml` file: + + ```toml + openssl-sys = {version = "0.9", features = ["vendored"]} + ``` + +9. #### Set the `PKG_CONFIG_SYSROOT_DIR` to the appropriate directory based on your chosen architecture + - For ARMv7: `export PKG_CONFIG_SYSROOT_DIR=/usr/arm-linux-gnueabihf/` + - For ARMv8 (ARM64): `export PKG_CONFIG_SYSROOT_DIR=/usr/aarch64-linux-gnu/` + +10. #### Build the app for your desired ARM version + - For ARMv7: cargo tauri build --target armv7-unknown-linux-gnueabihf + - For ARMv8 (ARM64): cargo tauri build --target aarch64-unknown-linux-gnu + + Choose the appropriate set of instructions based on whether you want to cross-compile your Tauri application for ARMv7 or ARMv8 (ARM64). Please note that the specific steps may vary depending on your Linux distribution and setup. + + diff --git a/src/content/docs/distribute/dmg.mdx b/src/content/docs/distribute/dmg.mdx index e243d016d2..2a81f73b37 100644 --- a/src/content/docs/distribute/dmg.mdx +++ b/src/content/docs/distribute/dmg.mdx @@ -2,6 +2,7 @@ title: DMG sidebar: order: 1 +i18nReady: true --- import CommandTabs from '@components/CommandTabs.astro'; @@ -25,6 +26,7 @@ To create an Apple Disk Image for your app you can use the Tauri CLI and run the yarn="yarn tauri build --bundles dmg" pnpm="pnpm tauri build --bundles dmg" deno="deno task tauri build --bundles dmg" + bun="bun tauri build --bundles dmg" cargo="cargo tauri build --bundles dmg" /> @@ -39,6 +41,12 @@ To create an Apple Disk Image for your app you can use the Tauri CLI and run the alt="Standard DMG window" /> +:::note + +GUI apps on macOS and Linux do not inherit the `$PATH` from your shell dotfiles (`.bashrc`, `.bash_profile`, `.zshrc`, etc). Check out Tauri's [fix-path-env-rs](https://github.com/tauri-apps/fix-path-env-rs) crate to fix this issue. + +::: + ## Window background You can set a custom background image to the DMG installation window with the [`tauri.conf.json > bundle > macOS > dmg > background`] configuration option: diff --git a/src/content/docs/distribute/flatpak.mdx b/src/content/docs/distribute/flatpak.mdx index 9af745d108..350a06f623 100644 --- a/src/content/docs/distribute/flatpak.mdx +++ b/src/content/docs/distribute/flatpak.mdx @@ -2,6 +2,8 @@ title: Flathub sidebar: order: 1 +i18nReady: true +draft: true --- import { Tabs, TabItem, Card } from '@astrojs/starlight/components'; @@ -57,56 +59,97 @@ dev-util/flatpak-builder flatpak install flathub org.gnome.Platform//46 org.gnome.Sdk//46 ``` -**3. [Build the .deb of your tauri-app](https://deploy-preview-2279--tauri-v2.netlify.app/reference/config/#bundleconfig)** +**3. [Build the .deb of your tauri-app](https://v2.tauri.app/reference/config/#bundleconfig)** -**4. Create the manifest** +**4. [Create an AppStream MetaInfo file](https://www.freedesktop.org/software/appstream/metainfocreator/#/guiapp)** + +**5. Create the flatpak manifest** ```yaml -id: org.your.id +# flatpak-builder.yaml +id: runtime: org.gnome.Platform runtime-version: '46' sdk: org.gnome.Sdk -command: tauri-app +command: finish-args: - --socket=wayland # Permission needed to show the window - --socket=fallback-x11 # Permission needed to show the window - --device=dri # OpenGL, not necessary for all projects - --share=ipc + - --talk-name=org.kde.StatusNotifierWatcher # Optional: needed only if your app uses the tray icon + - --filesystem=xdg-run/tray-icon:create # Optional: needed only if your app uses the tray icon - see an alternative way below + # - --env=WEBKIT_DISABLE_COMPOSITING_MODE=1 # Optional: may solve some issues with black webviews on Wayland modules: - name: binary buildsystem: simple + sources: + # A reference to the previously generated flatpak metainfo file + - type: file + path: flatpak.metainfo.xml + # If you use GitHub releases, you can target an existing remote file - type: file url: https://github.com/your_username/your_repository/releases/download/v1.0.1/yourapp_1.0.1_amd64.deb sha256: 08305b5521e2cf0622e084f2b8f7f31f8a989fc7f407a7050fa3649facd61469 # This is required if you are using a remote source - only-arches: [x86_64] #This source is only used on x86_64 Computers - # This path points to the binary file which was created in the .deb bundle. - # Tauri also creates a folder which corresponds to the content of the unpacked .deb. + only-arches: [x86_64] # This source is only used on x86_64 Computers + # You can also use a local file for testing + # - type: file + # path: yourapp_1.0.1_amd64.deb build-commands: - - ar -x *.deb - - tar -xf data.tar.gz - - 'install -Dm755 usr/bin/tauri-app /app/bin/tauri-app' - - install -Dm644 usr/share/applications/yourapp.desktop /app/share/applications/org.your.id.desktop - - install -Dm644 usr/share/icons/hicolor/128x128/apps/yourapp.png /app/share/icons/hicolor/128x128/apps/org.your.id.png - - install -Dm644 usr/share/icons/hicolor/32x32/apps/yourapp.png /app/share/icons/hicolor/32x32/apps/org.your.id.png - - install -Dm644 usr/share/icons/hicolor/256x256@2/apps/yourapp.png /app/share/icons/hicolor/256x256@2/apps/org.your.id.png - - install -Dm644 org.your.id.metainfo.xml /app/share/metainfo/org.your.id.rosary.metainfo.xml + - set -e + + # Extract the deb package + - mkdir deb-extract + - ar -x *.deb --output deb-extract + - tar -C deb-extract -xf deb-extract/data.tar.gz + + # Copy binary + - 'install -Dm755 deb-extract/usr/bin/ /app/bin/' + + # If you bundle files with additional resources, you should copy them: + - mkdir -p /app/lib/ + - cp -r deb-extract/usr/lib//. /app/lib/ + - find /app/lib/ -type f -exec chmod 644 {} \; + + # Copy desktop file + ensure the right icon is set + - sed -i 's/^Icon=.*/Icon=/' deb-extract/usr/share/applications/.desktop + - install -Dm644 deb-extract/usr/share/applications/.desktop /app/share/applications/.desktop + + # Copy icons + - install -Dm644 deb-extract/usr/share/icons/hicolor/128x128/apps/.png /app/share/icons/hicolor/128x128/apps/.png + - install -Dm644 deb-extract/usr/share/icons/hicolor/32x32/apps/.png /app/share/icons/hicolor/32x32/apps/.png + - install -Dm644 deb-extract/usr/share/icons/hicolor/256x256@2/apps/.png /app/share/icons/hicolor/256x256@2/apps/.png + - install -Dm644 flatpak.metainfo.xml /app/share/metainfo/.metainfo.xml ``` The Gnome 46 runtime includes all dependencies of the standard Tauri app with their correct versions. +:::note[Using tray-icon without changing the Flatpak manifest] +If you prefer not opening access from your app to $XDG_RUNTIME_DIR (where tray-icon is saved on linux), you can change the path tauri saves the tray image: + +```rust +TrayIconBuilder::new() + .icon(app.default_window_icon().unwrap().clone()) + .temp_dir_path(app.path().app_cache_dir().unwrap()) // will save to the cache folder ($XDG_CACHE_HOME) where the app already has permission + .build() + .unwrap(); +``` + +::: + **5. Install, and Test the app** ```shell # Install the flatpak -flatpak -y --user install +flatpak-builder --force-clean --user --disable-cache --repo flatpak-repo flatpak flatpak-builder.yaml # Run it -flatpak run +flatpak run # or via your desktop environment # Update it flatpak -y --user update diff --git a/src/content/docs/distribute/google-play.mdx b/src/content/docs/distribute/google-play.mdx index 48a8e6ee5a..3a2a06c3d2 100644 --- a/src/content/docs/distribute/google-play.mdx +++ b/src/content/docs/distribute/google-play.mdx @@ -2,6 +2,7 @@ title: Google Play sidebar: order: 1 +i18nReady: true --- import CommandTabs from '@components/CommandTabs.astro'; @@ -32,6 +33,7 @@ After running `tauri android init` to setup the Android Studio project, you can yarn="yarn tauri icon /path/to/app-icon.png" pnpm="pnpm tauri icon /path/to/app-icon.png" deno="deno task tauri icon /path/to/app-icon.png" + bun="bun tauri icon /path/to/app-icon.png" cargo="cargo tauri icon /path/to/app-icon.png" /> @@ -48,6 +50,7 @@ You can build an Android App Bundle (AAB) to upload to Google Play by running th yarn="yarn tauri android build --aab" pnpm="pnpm tauri android build --aab" deno="deno task tauri android build --aab" + bun="bun tauri android build --aab" cargo="cargo tauri android build --aab" /> @@ -76,6 +79,7 @@ To compile APKs for your app you can use the `--apk` argument: yarn="yarn tauri android build --apk" pnpm="pnpm tauri android build --apk" deno="deno task tauri android build --apk" + bun="bun tauri android build --apk" cargo="cargo tauri android build --apk" /> @@ -89,6 +93,7 @@ To only compile for a subset of targets, you can use the `--target` argument: yarn="yarn tauri android build --aab --target aarch64 --target armv7" pnpm="pnpm tauri android build --aab --target aarch64 --target armv7" deno="deno task tauri android build --aab --target aarch64 --target armv7" + bun="bun tauri android build --aab --target aarch64 --target armv7" cargo="cargo tauri android build --aab --target aarch64 --target armv7" /> @@ -105,6 +110,7 @@ This is only useful for testing or distribution outside Google Play, as it reduc yarn="yarn tauri android build --apk --split-per-abi" pnpm="pnpm tauri android build --apk --split-per-abi" deno="deno task tauri android build --apk --split-per-abi" + bun="bun tauri android build --apk --split-per-abi" cargo="cargo tauri android build --apk --split-per-abi" /> diff --git a/src/content/docs/distribute/index.mdx b/src/content/docs/distribute/index.mdx index 9d15c3bcf8..b258e2744d 100644 --- a/src/content/docs/distribute/index.mdx +++ b/src/content/docs/distribute/index.mdx @@ -3,6 +3,7 @@ title: Distribute sidebar: order: 0 label: Overview +i18nReady: true --- import { CardGrid, LinkCard, LinkButton } from '@astrojs/starlight/components'; @@ -19,6 +20,7 @@ Tauri builds your application directly from its CLI via the `build`, `android bu yarn="yarn tauri build" pnpm="pnpm tauri build" deno="deno task tauri build" + bun="bun tauri build" cargo="cargo tauri build" /> @@ -56,6 +58,11 @@ pnpm tauri bundle --bundles app --config src-tauri/tauri.appstore.conf.json" deno task tauri bundle --bundles app,dmg # bundle for App Store distribution deno task tauri bundle --bundles app --config src-tauri/tauri.appstore.conf.json" + bun="bun tauri build --no-bundle +# bundle for distribution outside the macOS App Store +bun tauri bundle --bundles app,dmg +# bundle for App Store distribution +bun tauri bundle --bundles app --config src-tauri/tauri.appstore.conf.json" cargo="cargo tauri build --no-bundle # bundle for distribution outside the macOS App Store cargo tauri bundle --bundles app,dmg @@ -107,6 +114,7 @@ Signing is required on most platforms. See the documentation for each platform f href="/distribute/sign/ios/" description="Code signing for iOS" /> +
## Distributing @@ -123,16 +131,21 @@ For Linux you can distribute your app using the Debian package, Snap, AppImage, href="/distribute/appimage/" description="Distribute as an AppImage" /> + - + /> */} +:::note + +GUI apps on macOS and Linux do not inherit the `$PATH` from your shell dotfiles (`.bashrc`, `.bash_profile`, `.zshrc`, etc). Check out Tauri's [fix-path-env-rs](https://github.com/tauri-apps/fix-path-env-rs) crate to fix this issue. + +::: + ## File structure The macOS app bundle is a directory with the following structure: diff --git a/src/content/docs/distribute/microsoft-store.mdx b/src/content/docs/distribute/microsoft-store.mdx index 056b4dac3b..cc73c3acb8 100644 --- a/src/content/docs/distribute/microsoft-store.mdx +++ b/src/content/docs/distribute/microsoft-store.mdx @@ -2,6 +2,7 @@ title: Microsoft Store sidebar: order: 1 +i18nReady: true --- import CommandTabs from '@components/CommandTabs.astro'; @@ -26,6 +27,7 @@ Use the `tauri icon` command to generate app icons from a single PNG or SVG sour yarn="yarn tauri icon /path/to/app-icon.png" pnpm="pnpm tauri icon /path/to/app-icon.png" deno="deno task tauri icon /path/to/app-icon.png" + bun="bun tauri icon /path/to/app-icon.png" cargo="cargo tauri icon /path/to/app-icon.png" /> @@ -71,6 +73,8 @@ yarn tauri bundle --config src-tauri/tauri.microsoftstore.conf.json" pnpm tauri bundle --config src-tauri/tauri.microsoftstore.conf.json" deno="deno task tauri build --no-bundle deno task tauri bundle --config src-tauri/tauri.microsoftstore.conf.json" + bun="bun tauri build --no-bundle +bun tauri bundle --config src-tauri/tauri.microsoftstore.conf.json" cargo="cargo tauri build --no-bundle cargo tauri bundle --config src-tauri/tauri.microsoftstore.conf.json" /> diff --git a/src/content/docs/distribute/rpm.mdx b/src/content/docs/distribute/rpm.mdx index 0945592b9e..47ec8a9161 100644 --- a/src/content/docs/distribute/rpm.mdx +++ b/src/content/docs/distribute/rpm.mdx @@ -2,11 +2,12 @@ title: RPM sidebar: order: 1 +i18nReady: true --- +import ShowSolution from '@components/ShowSolution.astro'; import CommandTabs from '@components/CommandTabs.astro'; - -# Packaging for RPM +import { Steps } from '@astrojs/starlight/components'; :::note Some sections in this guide are optional. This includes configuring scripts and certain other steps. Feel free to adapt the instructions based on your specific needs and requirements. @@ -14,6 +15,18 @@ Some sections in this guide are optional. This includes configuring scripts and This guide covers how to distribute and manage RPM packages, including retrieving package information, configuring scripts, setting dependencies, and signing packages. +:::note + +GUI apps on macOS and Linux do not inherit the `$PATH` from your shell dotfiles (`.bashrc`, `.bash_profile`, `.zshrc`, etc). Check out Tauri's [fix-path-env-rs](https://github.com/tauri-apps/fix-path-env-rs) crate to fix this issue. + +::: + +## Limitations + +Core libraries such as glibc frequently break compatibility with older systems. For this reason, you must build your Tauri application using the oldest base system you intend to support. A relatively old system such as Ubuntu 18.04 is more suited than Ubuntu 22.04, as the binary compiled on Ubuntu 22.04 will have a higher requirement of the glibc version, so when running on an older system, you will face a runtime error like `/usr/lib/libc.so.6: version 'GLIBC_2.33' not found`. We recommend using a Docker container or GitHub Actions to build your Tauri application for Linux. + +See the issues [tauri-apps/tauri#1355](https://github.com/tauri-apps/tauri/issues/1355) and [rust-lang/rust#57497](https://github.com/rust-lang/rust/issues/57497), in addition to the [AppImage guide](https://docs.appimage.org/reference/best-practices.html#binaries-compiled-on-old-enough-base-system) for more information. + ## Configuring the RPM package Tauri allows you to configure the RPM package by adding scripts, setting dependencies, adding a license, including custom files, and more. @@ -120,8 +133,7 @@ echo "-------------" - **obsoletes**: Lists the RPM dependencies that your application obsoletes. :::note -If this package is installed, packages listed as “obsoletes” will be automatically removed -if present. +If this package is installed, packages listed as "obsoletes" will be automatically removed if present. ::: - **desktopTemplate**: Adds a custom desktop file to the package. @@ -187,6 +199,7 @@ To build the RPM package, you can use the following command: yarn="yarn tauri build" pnpm="pnpm tauri build" deno="deno task tauri build" + bun="bun tauri build" cargo="cargo tauri build" /> @@ -227,6 +240,7 @@ Now you can build the package with the following command: yarn="yarn tauri build" pnpm="pnpm tauri build" deno="deno task tauri build" + bun="bun tauri build" cargo="cargo tauri build" /> @@ -342,3 +356,141 @@ Or for an already installed package: ```bash rpm -Uvvh package_name.rpm ``` + +## Cross-Compiling for ARM-based Devices + +This guide covers manual compilation. Check out our [GitHub Action guide](/distribute/pipelines/github/#arm-runner-compilation) for an example workflow that leverages QEMU to build the app. This will be much slower but will also be able to build AppImages. + +Manual compilation is suitable when you don't need to compile your application frequently and prefer a one-time setup. The following steps expect you to use a Linux distribution based on Debian/Ubuntu. + + + +1. #### Install Rust targets for your desired architecture + - For ARMv7 (32-bit): `rustup target add armv7-unknown-linux-gnueabihf` + - For ARMv8 (ARM64, 64-bit): `rustup target add aarch64-unknown-linux-gnu` + +2. #### Install the corresponding linker for your chosen architecture + - For ARMv7: `sudo apt install gcc-arm-linux-gnueabihf` + - For ARMv8 (ARM64): `sudo apt install gcc-aarch64-linux-gnu` + +3. #### Open or create the file `/.cargo/config.toml` and add the following configurations accordingly + + ```toml + [target.armv7-unknown-linux-gnueabihf] + linker = "arm-linux-gnueabihf-gcc" + + [target.aarch64-unknown-linux-gnu] + linker = "aarch64-linux-gnu-gcc" + ``` + +4. #### Enable the respective architecture in the package manager + - For ARMv7: `sudo dpkg --add-architecture armhf` + - For ARMv8 (ARM64): `sudo dpkg --add-architecture arm64` + +5. #### Adjusting Package Sources + + On Debian, this step should not be necessary, but on other distributions, you might need to edit /etc/apt/sources.list to include the ARM architecture variant. For example on Ubuntu 22.04 add these lines to the bottom of the file (Remember to replace jammy with the codename of your Ubuntu version): + + ``` + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy main restricted + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates main restricted + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy universe + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates universe + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy multiverse + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates multiverse + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-backports main restricted universe multiverse + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security main restricted + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security universe + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security multiverse + ``` + + Then, to prevent issues with the main packages, you have to add the correct main architecture to all other lines the file contained beforehand. For standard 64-bit systems you need to add [arch=amd64], the full file on Ubuntu 22.04 then looks similar to this: + + + + ``` + # See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to + # newer versions of the distribution. + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy main restricted + # deb-src http://archive.ubuntu.com/ubuntu/ jammy main restricted + + ## Major bug fix updates produced after the final release of the + ## distribution. + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted + # deb-src http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted + + ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu + ## team. Also, please note that software in universe WILL NOT receive any + ## review or updates from the Ubuntu security team. + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy universe + # deb-src http://archive.ubuntu.com/ubuntu/ jammy universe + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy-updates universe + # deb-src http://archive.ubuntu.com/ubuntu/ jammy-updates universe + + ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu + ## team, and may not be under a free licence. Please satisfy yourself as to + ## your rights to use the software. Also, please note that software in + ## multiverse WILL NOT receive any review or updates from the Ubuntu + ## security team. + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy multiverse + # deb-src http://archive.ubuntu.com/ubuntu/ jammy multiverse + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy-updates multiverse + + ## N.B. software from this repository may not have been tested as + ## extensively as that contained in the main release, although it includes + ## newer versions of some applications which may provide useful features. + ## Also, please note that software in backports WILL NOT receive any review + ## or updates from the Ubuntu security team. + deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy-backports main restricted universe multiverse + # deb-src http://archive.ubuntu.com/ubuntu/ jammy-backports main restricted universe multiverse + + deb [arch=amd64] http://security.ubuntu.com/ubuntu/ jammy-security main restricted + # deb-src http://security.ubuntu.com/ubuntu/ jammy-security main restricted + deb [arch=amd64] http://security.ubuntu.com/ubuntu/ jammy-security universe + # deb-src http://security.ubuntu.com/ubuntu/ jammy-security universe + deb [arch=amd64] http://security.ubuntu.com/ubuntu/ jammy-security multiverse + # deb-src http://security.ubuntu.com/ubuntu/ jammy-security multiverse + + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy main restricted + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates main restricted + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy universe + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates universe + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy multiverse + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates multiverse + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-backports main restricted universe multiverse + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security main restricted + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security universe + deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security multiverse + ``` + + + +6. #### Update the package information: `sudo apt-get update && sudo apt-get upgrade -y` + +7. #### Install the required webkitgtk library for your chosen architecture + - For ARMv7: `sudo apt install libwebkit2gtk-4.1-dev:armhf` + - For ARMv8 (ARM64): `sudo apt install libwebkit2gtk-4.1-dev:arm64` + +8. #### Install OpenSSL or use a vendored version + + This is not always required so you may want to proceed first and check if you see errors like `Failed to find OpenSSL development headers`. + - Either install the development headers system-wide: + - For ARMv7: `sudo apt install libssl-dev:armhf` + - For ARMv8 (ARM64): `sudo apt install libssl-dev:arm64` + - Or enable the vendor feature for the OpenSSL Rust crate which will affect all other Rust dependencies using the same minor version. You can do so by adding this to the dependencies section in your `Cargo.toml` file: + + ```toml + openssl-sys = {version = "0.9", features = ["vendored"]} + ``` + +9. #### Set the `PKG_CONFIG_SYSROOT_DIR` to the appropriate directory based on your chosen architecture + - For ARMv7: `export PKG_CONFIG_SYSROOT_DIR=/usr/arm-linux-gnueabihf/` + - For ARMv8 (ARM64): `export PKG_CONFIG_SYSROOT_DIR=/usr/aarch64-linux-gnu/` + +10. #### Build the app for your desired ARM version + - For ARMv7: cargo tauri build --target armv7-unknown-linux-gnueabihf + - For ARMv8 (ARM64): cargo tauri build --target aarch64-unknown-linux-gnu + + Choose the appropriate set of instructions based on whether you want to cross-compile your Tauri application for ARMv7 or ARMv8 (ARM64). Please note that the specific steps may vary depending on your Linux distribution and setup. + + diff --git a/src/content/docs/distribute/snapcraft.mdx b/src/content/docs/distribute/snapcraft.mdx index 477278344b..c79d067793 100644 --- a/src/content/docs/distribute/snapcraft.mdx +++ b/src/content/docs/distribute/snapcraft.mdx @@ -2,6 +2,7 @@ title: Snapcraft sidebar: order: 1 +i18nReady: true --- ## Prerequisites @@ -83,6 +84,24 @@ apps: # - network # Add whatever plugs you need here, see https://snapcraft.io/docs/snapcraft-interfaces for more info. # The gnome extension already includes [ desktop, desktop-legacy, gsettings, opengl, wayland, x11, mount-observe, calendar-service ] + # - single-instance-plug # add this if you're using the single-instance plugin + #slots: + # Add the slots you need to expose to other snaps + # - single-instance-plug # add this if you're using the single-instance plugin + +# Add these lines only if you're using the single-instance plugin +# Check https://v2.tauri.app/plugin/single-instance/ for details +#slots: +# single-instance: +# interface: dbus +# bus: session +# name: org.net_mydomain_MyApp.SingleInstance # Remember to change net_mydomain_MyApp to your app ID with "_" instead of "." and "-" +# +#plugs: +# single-instance-plug: +# interface: dbus +# bus: session +# name: org.net_mydomain_MyApp.SingleInstance # Remember to change net_mydomain_MyApp to your app ID with "_" instead of "." and "-" package-repositories: - type: apt @@ -129,9 +148,7 @@ parts: - The `package-repositories` section allows you to add a package repository to help you satisfy your dependencies. - `build-packages`/`build-snaps` defines the build dependencies for your snap. - `stage-packages`/`stage-snaps` defines the runtime dependencies for your snap. -- The `override-pull` section runs a series of commands before the sources are pulled. -- `craftctl default` performs the default pull commands. -- The `organize` section moves your files to the proper directories so that the binary and desktop file can be exposed to the `apps` sections. +- The `override-build` section runs a series of commands after the sources were pulled. ## Building diff --git a/src/content/docs/distribute/windows-installer.mdx b/src/content/docs/distribute/windows-installer.mdx index 6e7555284a..1cfe34c8bc 100644 --- a/src/content/docs/distribute/windows-installer.mdx +++ b/src/content/docs/distribute/windows-installer.mdx @@ -2,6 +2,7 @@ title: Windows Installer sidebar: order: 1 +i18nReady: true --- import CommandTabs from '@components/CommandTabs.astro'; @@ -10,8 +11,8 @@ import { Tabs, TabItem } from '@astrojs/starlight/components'; Tauri applications for Windows are either distributed as Microsoft Installers (`.msi` files) using the [WiX Toolset v3] or as setup executables (`-setup.exe` files) using [NSIS]. -Please note that `.msi` installers can **only be created on Windows** as cross-compilation doesn't work. -Cross-compilation for NSIS installers is currently experimental. +Please note that `.msi` installers can **only be created on Windows** as WiX can only run on Windows systems. +Cross-compilation for NSIS installers is shown below. This guide provides information about available customization options for the installer. @@ -24,18 +25,27 @@ To build and bundle your app into a Windows installer you can use the Tauri CLI yarn="yarn tauri build" pnpm="pnpm tauri build" deno="deno task tauri build" + bun="bun tauri build" cargo="cargo tauri build" /> -### Experimental: Build Windows apps on Linux and macOS +:::note[VBSCRIPT requirement for MSI packages] -Cross compiling Windows apps on Linux and macOS hosts is possible when using [NSIS]. -Note that this is currently considered highly experimental and may not work on every system or for every project. +Building MSI packages (`"targets": "msi"` or `"targets": "all"` in `tauri.conf.json`) requires the VBSCRIPT optional feature to be enabled on Windows. This feature is enabled by default on most Windows installations, but if you encounter errors like `failed to run light.exe`, you may need to enable it manually through **Settings** → **Apps** → **Optional features** → **More Windows features**. See the [Prerequisites guide](/start/prerequisites/#vbscript-for-msi-installers) for detailed instructions. + +::: + +### Build Windows apps on Linux and macOS + +Cross compiling Windows apps on Linux and macOS hosts is possible with caveats when using [NSIS]. +It is not as straight forward as compiling on Windows directly and is not tested as much. Therefore it should only be used as a last resort if local VMs or CI solutions like GitHub Actions don't work for you. :::note + Signing cross compiled Windows installers requires an external signing tool. See the [signing documentation] for more information. + ::: Since Tauri officially only supports the MSVC Windows target, the setup is a bit more involved. @@ -128,6 +138,7 @@ Now it should be as simple as adding the runner and target to the `tauri build` yarn="yarn tauri build --runner cargo-xwin --target x86_64-pc-windows-msvc" pnpm="pnpm tauri build --runner cargo-xwin --target x86_64-pc-windows-msvc" deno="deno task tauri build --runner cargo-xwin --target x86_64-pc-windows-msvc" + bun="bun tauri build --runner cargo-xwin --target x86_64-pc-windows-msvc" cargo="cargo tauri build --runner cargo-xwin --target x86_64-pc-windows-msvc" /> @@ -145,8 +156,9 @@ using the `--target` flag: npm="npm run tauri build -- --target i686-pc-windows-msvc" yarn="yarn tauri build --target i686-pc-windows-msvc" pnpm="pnpm tauri build --target i686-pc-windows-msvc" - cargo="cargo tauri build --target i686-pc-windows-msvc" deno="deno task tauri build --target i686-pc-windows-msvc" + bun="bun tauri build --target i686-pc-windows-msvc" + cargo="cargo tauri build --target i686-pc-windows-msvc" /> By default, Rust only installs toolchains for your machine's target, @@ -162,6 +174,7 @@ Now you can add the rust target with `rustup target add aarch64-pc-windows-msvc` yarn="yarn tauri build --target aarch64-pc-windows-msvc" pnpm="pnpm tauri build --target aarch64-pc-windows-msvc" deno="deno task tauri build --target aarch64-pc-windows-msvc" + bun="bun tauri build --target aarch64-pc-windows-msvc" cargo="cargo tauri build --target aarch64-pc-windows-msvc" /> @@ -187,11 +200,11 @@ tauri-plugin-notification = { version = "2.0.0", features = [ "windows7-compat" ## FIPS Compliance -If your system requires the MSI bundle to be FIPS compliant you can set the `TAURI_FIPS_COMPLIANT` environment variable to `true` +If your system requires the MSI bundle to be FIPS compliant you can set the `TAURI_BUNDLER_WIX_FIPS_COMPLIANT` environment variable to `true` before running `tauri build`. In PowerShell you can set it for the current terminal session like this: ```powershell -$env:TAURI_FIPS_COMPLIANT="true" +$env:TAURI_BUNDLER_WIX_FIPS_COMPLIANT="true" ``` ## WebView2 Installation Options @@ -518,7 +531,7 @@ Supported hooks are: - `NSIS_HOOK_PREUNINSTALL`: Runs before removing any files, registry keys and shortcuts. - `NSIS_HOOK_POSTUNINSTALL`: Runs after files, registry keys and shortcuts have been removed. -For example, create a `hooks.nsi` file in the `src-tauri/windows` folder and define the hooks you need: +For example, create a `hooks.nsh` file in the `src-tauri/windows` folder and define the hooks you need: ```nsh !macro NSIS_HOOK_PREINSTALL @@ -545,13 +558,74 @@ Then you must configure Tauri to use that hook file: "bundle": { "windows": { "nsis": { - "installerHooks": "./windows/hooks.nsi" + "installerHooks": "./windows/hooks.nsh" } } } } ``` +#### Installing Dependencies with Hooks + +You can use installer hooks to automatically install system dependencies that your application requires. This is particularly useful for runtime dependencies like Visual C++ Redistributables, DirectX, OpenSSL or other system libraries that may not be present on all Windows systems. + +**MSI Installer Example (Visual C++ Redistributable):** + +```nsh +!macro NSIS_HOOK_POSTINSTALL + ; Check if Visual C++ 2019 Redistributable is installed (via Windows Registry) + ReadRegDWord $0 HKLM "SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64" "Installed" + + ${If} $0 == 1 + DetailPrint "Visual C++ Redistributable already installed" + Goto vcredist_done + ${EndIf} + + ; Install from bundled MSI if not installed + ${If} ${FileExists} "$INSTDIR\resources\vc_redist.x64.msi" + DetailPrint "Installing Visual C++ Redistributable..." + ; Copy to TEMP folder and then execute installer + CopyFiles "$INSTDIR\resources\vc_redist.x64.msi" "$TEMP\vc_redist.x64.msi" + ExecWait 'msiexec /i "$TEMP\vc_redist.x64.msi" /passive /norestart' $0 + + ; Check wether installation process exited successfully (code 0) or not + ${If} $0 == 0 + DetailPrint "Visual C++ Redistributable installed successfully" + ${Else} + MessageBox MB_ICONEXCLAMATION "Visual C++ installation failed. Some features may not work." + ${EndIf} + + ; Clean up setup files from TEMP and your installed app + Delete "$TEMP\vc_redist.x64.msi" + Delete "$INSTDIR\resources\vc_redist.x64.msi" + ${EndIf} + + vcredist_done: +!macroend +``` + +**Key considerations:** + +- A good practice is to always check if the dependency is already installed using registry keys or file existence or via Windows [where] command. +- Use `/passive`, `/quiet`, or `/silent` flags to avoid interrupting the installation flow. Check out [msiexec] options for `.msi` files, or the setup manual for app-specific flags +- Include `/norestart` to prevent automatic system reboots during installation for setups that restarts user devices +- Clean up temporary files and bundled installers to avoid bloating the application +- Consider that dependencies might be shared with other applications when uninstalling +- Provide meaningful error messages if installation fails + +Ensure to bundle the dependency installers in your `src-tauri/resources` folder and add to `tauri.conf.json` so they get bundled, and can be accessed during installation from `$INSTDIR\resources\`: + +```json title="tauri.conf.json" +{ + "bundle": { + "resources": [ + "resources/my-dependency.exe", + "resources/another-one.msi + ] + } +} +``` + ### Install Modes By default the installer will install your application for the current user only. @@ -642,3 +716,5 @@ to verify the current Webview2 version and run the Webview2 bootstrapper if it d [NSIS configuration]: /reference/config/#nsisconfig [installMode]: /reference/config/#installmode [NSISInstallerMode]: /reference/config/#nsisinstallermode +[where]: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/where +[msiexec]: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/msiexec diff --git a/src/content/docs/es/about/book.md b/src/content/docs/es/about/book.md new file mode 100644 index 0000000000..858321461c --- /dev/null +++ b/src/content/docs/es/about/book.md @@ -0,0 +1,32 @@ +--- +title: El libro de Tauri +i18nReady: true +--- + +:::note[Actualización del progreso] + +Estamos trabajando activamente en la autoría y redacción del Libro de Tauri. Hemos sufrido retrasos debido al inmenso crecimiento de Tauri, pero recientemente hemos vuelto a dar prioridad a este proyecto. Aunque todavía no tenemos detalles sobre los plazos de publicación, puedes estar atento a esta página para estar al día. + +Nos gustaría pedir disculpas por este retraso más allá de la fecha de publicación originalmente comunicada. Si has donado a través de GitHub Sponsors u Open Collective y deseas solicitar un reembolso, puedes hacerlo a través de Open Collective: [Contacta con Tauri en Open Collective](https://opencollective.com/tauri/contact). + +::: + +### Visión general + +El Libro de Tauri te guiará a través de la historia de Tauri y las decisiones de diseño que hemos tomado. También hablará en profundidad de por qué la privacidad, la seguridad y la sostenibilidad son discusiones importantes y fundamentales que puedes aplicar a cualquier proyecto de software moderno. + +Los temas incluidos son: + +- El método y el razonamiento que hay detrás del diseño de Tauri. +- Las opciones que tienes al construir con Tauri. +- Que no tienes que elegir entre enviar rápido y ser sostenible y responsable. +- Por qué elegimos el lenguaje Rust como capa de enlace y aplicación para Tauri. +- Por qué es importante una revisión binaria. + +### Historia + +En 2020, la fabricación de aplicaciones nativas se ha vuelto más fácil y accesible que nunca. Sin embargo, tanto los principiantes como los desarrolladores experimentados se enfrentan a decisiones difíciles en un panorama de seguridad y privacidad que cambia rápidamente. Esto es especialmente cierto en el entorno semiconfiable de los dispositivos de usuario. + +Tauri elimina las conjeturas de la ecuación, ya que fue diseñado desde cero para adoptar nuevos paradigmas de desarrollo seguro y flexibilidad creativa que aprovechan las características del lenguaje Rust y te permite construir una aplicación utilizando cualquier framework de frontend que desees. Descubre cómo puedes diseñar, construir, auditar y desplegar aplicaciones nativas diminutas, rápidas, robustas y seguras para las principales plataformas de escritorio y móviles, todo ello a partir exactamente del mismo código base y en un tiempo récord, sin necesidad siquiera de conocer el lenguaje de programación Rust. + +Los autores y cofundadores de Tauri, Daniel y Lucas, te llevan en un viaje de la teoría a la ejecución, durante el cual aprenderás por qué se construyó Tauri y cómo funciona bajo el capó. Junto con los puntos de vista de los invitados que se especializan en código abierto, DevOps, seguridad y arquitectura empresarial, este libro también presenta discusiones filosóficas con formato de discurso y puntos de vista de sostenibilidad de código abierto de los que sus aplicaciones de próxima generación se beneficiarán - y sus usuarios se beneficiarán. diff --git a/src/content/docs/es/about/governance.md b/src/content/docs/es/about/governance.md new file mode 100644 index 0000000000..cd6fb163f8 --- /dev/null +++ b/src/content/docs/es/about/governance.md @@ -0,0 +1,50 @@ +--- +title: Gobernanza de Tauri +i18nReady: true +--- + +Uno de los principales objetivos de la estructura organizativa de Tauri es garantizar que nos mantenemos fieles a nuestros valores de código abierto y lo hacemos de forma sostenible, respetando la salud y el bienestar de los contribuyentes. [El Programa Tauri dentro de Commons Conservancy](https://dracc.commonsconservancy.org/0035/) se estableció para comprometerse con esos valores y facilitar un proceso de gobernanza abierto, transparente y eficiente a lo largo del futuro desarrollo de Tauri y sus materiales auxiliares. + +## Grupo de Trabajo de Tauri + +El Grupo de Trabajo Tauri es el marco colectivo creado para hacer posible este proceso de gobernanza. Está formado por los siguientes componentes: + +- Miembros del Grupo de Trabajo +- Junta Directiva de Tauri +- Dominios y dominios potenciales +- Equipos + +![Diagrama de Gobernanza de Tauri](@assets/about/governance/diagram.svg) + +### Miembros del Grupo de Trabajo + +Todas las personas que componen el Grupo de Trabajo Tauri. + +### Junta Directiva de Tauri + +La Junta Directiva de Tauri es el órgano central de toma de decisiones del Programa Tauri y es responsable de la salud y estabilidad general del Programa Tauri. La Junta vota las decisiones más importantes del Programa y las cuestiones planteadas por el Grupo de Trabajo. + +Un Director de la Junta puede ser un colaborador técnico, ser parte interesada en el futuro de Tauri, compartir experiencia de la industria o tener pasión por los aspectos normativos y legales dentro del Código Abierto. + +### Dominios y Líderes de Dominios + +Los dominios son unidades organizativas que representan un área de interés dentro de Tauri. + +Los líderes de dominio son colaboradores de confianza dentro de la comunidad Tauri con experiencia en el dominio que lideran. Son responsables de establecer la dirección, supervisar y apoyar las actividades dentro de ese dominio. + +Los dominios y líderes de dominio actuales se describen en el repositorio de [Gobernanza y Orientación en GitHub](https://github.com/tauri-apps/governance-and-guidance). + +### Equipos + +Los equipos son pequeños grupos de colaboradores que apoyan o mantienen áreas específicas del Programa Tauri. Son un medio para que Tauri ejecute sus tareas y objetivos a más largo plazo, especialmente cuando las contribuciones ad hoc no pueden lograr los mismos resultados. + +## Involúcrate + +Si estás interesado en convertirte en Director de la Junta de Tauri o en Líder de Dominio, las elecciones para esos puestos se celebran a lo largo del año. En el caso de los líderes de dominio, se celebran en primavera y otoño, y en el de los directores del consejo, en verano. Las instrucciones para presentar tu candidatura se publican en el [Blog de Tauri](https://tauri.app/blog) antes de cada elección. + +## Recursos Adicionales + +- [Repositorio de Gobernanza y Orientación](https://github.com/tauri-apps/governance-and-guidance): Información más detallada sobre la Gobernanza de Tauri y los actuales Dominios y Líderes de Dominio +- [Contrato Social](https://github.com/tauri-apps/governance-and-guidance/blob/main/SOCIAL_CONTRACT.md): El contrato social informa nuestra toma de decisiones y nuestra organización. +- [Código de Conducta](https://github.com/tauri-apps/governance-and-guidance/blob/main/CODE_OF_CONDUCT.md) +- [Estatutos del Programa Tauri](https://dracc.commonsconservancy.org/0035/) diff --git a/src/content/docs/es/about/index.mdx b/src/content/docs/es/about/index.mdx new file mode 100644 index 0000000000..673d73ebfa --- /dev/null +++ b/src/content/docs/es/about/index.mdx @@ -0,0 +1,30 @@ +--- +title: Sobre Tauri +i18nReady: true +--- + +:::tip + +Si lo que buscas es una rápida descripción técnica y empezar a crear una aplicación, visita la página [¿Qué es Tauri?](/es/start/). Si quieres saber más sobre la filosofía del proyecto, sigue leyendo. + +::: + +import { LinkCard, CardGrid } from '@astrojs/starlight/components'; + + + + + + diff --git a/src/content/docs/es/about/philosophy.md b/src/content/docs/es/about/philosophy.md new file mode 100644 index 0000000000..e14a8879e0 --- /dev/null +++ b/src/content/docs/es/about/philosophy.md @@ -0,0 +1,47 @@ +--- +title: Filosofía de Tauri +i18nReady: true +--- + +Tauri es un conjunto de herramientas que ayuda a los desarrolladores a crear aplicaciones para las principales plataformas de escritorio, utilizando prácticamente cualquier framework frontend existente. El núcleo está construido con Rust, y la CLI aprovecha Node.js haciendo de Tauri un enfoque genuinamente polifacético para crear y mantener grandes aplicaciones. + + + +## Seguridad Ante Todo + +En el mundo actual, todo modelo honesto de amenaza asume que el dispositivo del usuario ya ha sido comprometido. Esto pone a los desarrolladores de aplicaciones en una situación complicada, porque si el dispositivo ya está en peligro, ¿cómo se puede confiar en el software? + +Una defensa en profundidad es el enfoque que hemos adoptado. Queremos que seas capaz de tomar todas las precauciones posibles para minimizar la superficie que presentas a los atacantes. Tauri te permite elegir qué puntos finales de API enviar, si quieres o no un servidor localhost integrado en tu aplicación, e incluso aleatoriza los manejadores funcionales en tiempo de ejecución. Estas y otras técnicas forman una línea de base segura que te capacita a ti y a tus usuarios. + +Ralentizar a los atacantes dificultando enormemente los ataques estáticos y aislando los sistemas entre sí es el nombre del juego. Y si vienes del ecosistema Electron, puedes estar tranquilo: por defecto, Tauri solo distribuye binarios, no archivos ASAR. + +Al elegir construir Tauri con la seguridad como fuerza guía, te damos todas las oportunidades para adoptar una postura de seguridad proactiva. + +## Políformismos, no Silos + +La mayoría de frameworks contemporáneos utilizan un único paradigma lingüístico y, por tanto, están atrapados en una burbuja de conocimientos e idiomas. Esto puede funcionar bien para determinadas aplicaciones de nicho, pero también fomenta una especie de tribalismo. + +Esto puede verse en la forma en que las comunidades de desarrollo de React, Angular y Vue se apiñan en sus pilas, generando en última instancia muy poca polinización cruzada. + +Esta misma situación puede observarse en los campos de batalla Rust vs. Node vs. C++, donde los partidarios de la línea dura adoptan sus posturas y se niegan a colaborar entre comunidades. + +Hoy en día, Tauri utiliza Rust para el backend - pero en un futuro no muy lejano, otros backends como Go, Nim, Python, Csharp, etc. serán posibles. Esto se debe a que estamos manteniendo los enlaces oficiales de Rust a la organización [webview](https://github.com/webview) y planeamos permitirte cambiar el backend según tus necesidades. Dado que nuestra API puede implementarse en cualquier lenguaje con interoperabilidad con C, la conformidad total está sólo a un PR de distancia. + +## Código Abierto Honesto + +Nada de esto tendría sentido sin una comunidad. Hoy en día, las comunidades de software son lugares increíbles donde la gente se ayuda mutuamente y hace cosas increíbles. + +El código abierto significa cosas distintas para cada persona, pero la mayoría estará de acuerdo en que sirve para apoyar la libertad. Cuando el software no respeta tus derechos, puede parecer injusto y comprometer potencialmente tus libertades al funcionar de forma poco ética. + +Por eso estamos orgullosos de que los defensores del FLOSS puedan crear aplicaciones con Tauri que sean "certificablemente" de código abierto y puedan incluirse en distribuciones GNU/Linux respaldadas por la FSF. + +## El Futuro + +El futuro de Tauri depende de tu implicación y tus contribuciones. Pruébalo, presenta problemas, únete a un grupo de trabajo o haz una donación - cada contribución es importante. En cualquier caso, no dudes en ponerte en contacto con nosotros. diff --git a/src/content/docs/es/about/trademark.md b/src/content/docs/es/about/trademark.md new file mode 100644 index 0000000000..0b339de2c8 --- /dev/null +++ b/src/content/docs/es/about/trademark.md @@ -0,0 +1,118 @@ +--- +title: Directrices sobre Marcas +i18nReady: true +--- + +Esta política de marcas comerciales se ha elaborado para ayudarle a entender cómo utilizar las marcas comerciales, marcas de servicio y logotipos de TAURI propiedad del Programa Tauri dentro de Commons Conservancy. + +Aunque nuestro software está disponible bajo una licencia de software libre y de código abierto, esa licencia de derechos de autor no incluye una licencia para utilizar nuestra marca, y esta Política pretende explicar cómo utilizar nuestras marcas de forma coherente con la legislación de fondo y las expectativas de la comunidad. + +**Esta política cubre:** + +- ONuestras marcas denominativas y de servicios: TAURI, TAO, WRY. +- Nuestros logotipos: Los logotipos TAURI, TAO, WRY (y todos los derivados visuales). + +Esta política abarca todas las marcas comerciales y de servicios, estén registradas o no. + +## Directrices generales + +Siempre que utilices una de nuestras marcas, debe hacerlo de forma que no induzca a error a nadie sobre lo que está recibiendo y de quién. Por ejemplo, no puede decir que está distribuyendo software TAURI cuando lo que está distribuyendo es una versión modificada del mismo (también conocida como Fork), porque los destinatarios podrían no entender las diferencias entre sus versiones modificadas y las nuestras. + +Tampoco puedes utilizar nuestro logotipo en su sitio web de forma que sugiera que su sitio web es un sitio web oficial o que nosotros respaldamos su sitio web. + +Sin embargo, puedes decir que te gusta el software TAURI, que participa en la comunidad TAURI, que proporciona una versión no modificada del software TAURI. + +No podrá utilizar ni registrar nuestras marcas, o variaciones de las mismas, como parte de su propia marca comercial, marca de servicio, nombre de dominio, nombre de empresa, nombre comercial, nombre de producto o nombre de servicio. + +La legislación sobre marcas no permite el uso de nombres o marcas demasiado similares a los nuestros. Por lo tanto, no puedes utilizar una variación obvia de cualquiera de nuestras marcas o cualquier equivalente fonético, equivalente en un idioma extranjero, despegue o abreviatura de un producto o servicio similar o compatible. Consideraríamos lo siguiente demasiado similar a una de nuestras Marcas: + +- TAURIMAGE +- Aplicación de Tauri Wallet + +## Usos Aceptados + +### Aplicaciones + +TAURI es un marco para crear aplicaciones para dispositivos informáticos. Puedes afirmar que tu aplicación utiliza TAURI, pero debes tener cuidado para evitar dar la impresión de que tu aplicación está aprobada por el Programa Tauri dentro de Commons Conservancy, o que es una aplicación oficial. Debes tener cuidado de no enviar su aplicación con el ICONO por defecto. + +### Plugins y Plantillas + +Puedes publicar el código de plugins y plantillas utilizando las convenciones de nomenclatura apropiadas, pero por favor, menciona que estos trabajos no están aprobados oficialmente. Solo se consideran oficiales las bases de código gestionadas por la organización dentro de la organización de GitHub `tauri-apps`. + +## Modificaciones del Núcleo (Forks) + +Si distribuyes una versión modificada de nuestro software (TAURI CORE), debe eliminar de ella todos nuestros logotipos y nombres. Debes conservar nuestra licencia original en formato SPDX. Puedes utilizar nuestras marcas denominativas, pero no nuestros logotipos, para describir con veracidad el origen del software que está proporcionando. Por ejemplo, si el código que distribuyes es una modificación de nuestro software, puedes decir: "Este software se deriva del código fuente del software TAURI". + +### Declaraciones Sobre Compatibilidad + +Puedes utilizar las marcas denominativas, pero no los logotipos, para describir con veracidad la relación entre tu software y el nuestro. Cualquier otro uso puede implicar que hemos certificado o aprobado tu software. Si deseas utilizar nuestros logotipos, póngase en contacto con nosotros para tratar los términos de la licencia. + +### Nombres de Productos Compatibles + +Si deseas describir tu producto haciendo referencia al software TAURI, estas son las condiciones en las que puede hacerlo. Puedes llamar a su software XYZ (donde XYZ es el nombre de tu producto) para TAURI sólo si: + +- Todas las versiones del software TAURI que entregues con tu producto son los binarios exactos proporcionados por nosotros, o fabricados por el núcleo del software y las herramientas que proporcionamos. +- Tu producto es totalmente compatible con las API del software TAURI. +- Utiliza la siguiente leyenda en materiales de marketing o descripciones de productos: "TAURI es una marca comercial del Progama de Tauri dentro de Commons Conservancy. https://tauri.app/" + +### Grupos de Usuarios + +Puedes utilizar las marcas de Word como parte del nombre de su grupo de usuarios siempre que: + +- El objetivo principal del grupo es nuestro software. +- El grupo no obtiene beneficios. +- Los gastos de asistencia a las reuniones se limitan a cubrir los costes del local, la comida y la bebida. + +No estás autorizado a celebrar una conferencia utilizando nuestras marcas. + +### Sin Nombres de Dominio + +No debes registrar ningún dominio que incluya nuestras marcas denominativas o cualquier variante o combinación de las mismas. + +### Otros Usos Lucrativos de las Marcas TAURI + +Si estás realizando un vídeo, una serie de tutoriales, un libro u otro material educativo por el que recibas un pago a través de suscripciones, ventas, publicidad o similares, debe obtener un permiso explícito de licencia del Programa Tauri dentro de Commons Conservancy. + +## Cómo Mostrar Nuestras Marcas + +Cuando tengas derecho a utilizar nuestra marca, le indicamos cómo exhibirla. + +### Marcas y Leyendas Comerciales + +La primera mención o la mención más destacada de una marca en una página web, documento o documentación debe ir acompañada de un símbolo que indique si la marca es una marca registrada ("®") o una marca no registrada ("™"). Si no sabes cuál se aplica, ponte en contacto con nosotros. (La propia TAURI es una marca registrada). + +Coloca el siguiente aviso al pie de la página en la que hayas utilizado la marca: TAURI es una marca registrada de [El Programa Tauri dentro de Commons Conservancy]". + +### Uso de Marcas Comerciales en Textos + +Utiliza siempre las marcas registradas en su forma exacta y con la ortografía correcta, sin abreviar, separar con guiones ni combinar con ninguna otra palabra o palabras. + +- Inaceptable: TAUREE +- Aceptable: TAURI + +No pluralice una marca. + +- Inaceptable: Tengo diecisiete TAURIs funcionando en mi ordenador. +- Aceptable: Estoy ejecutando diecisiete aplicaciones TAURI en mi ordenador y me sobra ram. + +Utiliza siempre una marca como adjetivo que modifica a un sustantivo. + +- Inaceptable: Esto es un TAURI. +- Aceptable: Esto es una aplicación de sofware TAURI. + +### Uso de los Logos + +No puedes modificar ningún logotipo salvo para escalarlo. Esto significa que no puedes añadir elementos decorativos, cambiar los colores, modificar las proporciones, distorsionarlo, añadir elementos ni combinarlo con otros logotipos. + +Disponemos de una versión de alto contraste del logotipo, que puede descargar en la sección de elementos. + +## Elementos + +- Aquí puedes descargar las [Directrices de la marca](/assets/brand_guidelines.pdf) completas - (PDF, 74,3 MB) +- Aquí puedes descargar los formatos SVG y PNG del LOGOTIPO y el Wordmark en el [Logopack](/assets/logopack.zip) - (ZIP, 203 KB) + +--- + +El Programa Tauri de Commons Conservancy se reserva todos los derechos a modificar estas directrices sobre marcas comerciales en cualquier momento. Si tienes alguna pregunta o consulta, envíanos un correo electrónico a `trademark@tauri.app`. + +Estas directrices se basan en las Directrices sobre el modelo de marca, disponibles en http://www.modeltrademarkguidelines.org, utilizadas bajo una licencia Creative Commons Attribution 3.0 Unported: https://creativecommons.org/licenses/by/3.0/deed.en_EU. Versión 1.0 del 20 de agosto de 2022 diff --git a/src/content/docs/es/plugin/autostart.mdx b/src/content/docs/es/plugin/autostart.mdx new file mode 100644 index 0000000000..e7022c6564 --- /dev/null +++ b/src/content/docs/es/plugin/autostart.mdx @@ -0,0 +1,158 @@ +--- +title: Inicio automático +description: Inicia automáticamente tu aplicación al arrancar el sistema. +plugin: autostart +i18nReady: true +--- + +import PluginLinks from '@components/PluginLinks.astro'; +import Compatibility from '@components/plugins/Compatibility.astro'; + +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; +import PluginPermissions from '@components/PluginPermissions.astro'; + + + +Inicia automáticamente tu aplicación al arrancar el sistema. + +## Plataformas compatibles + + + +## Configuración + +Instala el plugin de autostart para comenzar. + + + + + Usa el gestor de paquetes de tu proyecto para añadir la dependencia: + + {' '} + + + + + + + + 1. Ejecuta el siguiente comando en la carpeta `src-tauri` para añadir el plugin a las dependencias del proyecto en `Cargo.toml`: + + ```sh frame=none + cargo add tauri-plugin-autostart --target 'cfg(any(target_os = "macos", windows, target_os = "linux"))' + ``` + + 2. Modifica `lib.rs` para inicializar el plugin: + + ```rust title="src-tauri/src/lib.rs" ins={5-6} + #[cfg_attr(mobile, tauri::mobile_entry_point)] + pub fn run() { + tauri::Builder::default() + .setup(|app| { + #[cfg(desktop)] + app.handle().plugin(tauri_plugin_autostart::init(tauri_plugin_autostart::MacosLauncher::LaunchAgent, Some(vec!["--flag1", "--flag2"]) /* arbitrary number of args to pass to your app */)); + Ok(()) + }) + .run(tauri::generate_context!()) + .expect("error al ejecutar la aplicación tauri"); + } + ``` + + 3. Puedes instalar los enlaces de JavaScript Guest utilizando tu gestor de paquetes de JavaScript preferido: + + + + + + + + +## Uso + +El plugin de autostart está disponible tanto en JavaScript como en Rust. + + + + +```javascript +import { enable, isEnabled, disable } from '@tauri-apps/plugin-autostart'; +// si utilizas `"withGlobalTauri": true`, deberías usar +// const { enable, isEnabled, disable } = window.__TAURI__.autostart; + +// Activar el arranque automático +await enable(); +// Comprobar el estado de activación +console.log(`registered for autostart? ${await isEnabled()}`); +// Desactivar el arranque automático +disable(); +``` + + + + +```rust +#[cfg_attr(mobile, tauri::mobile_entry_point)] +pub fn run() { + tauri::Builder::default() + .setup(|app| { + #[cfg(desktop)] + { + use tauri_plugin_autostart::MacosLauncher; + use tauri_plugin_autostart::ManagerExt; + + app.handle().plugin(tauri_plugin_autostart::init( + MacosLauncher::LaunchAgent, + Some(vec!["--flag1", "--flag2"]), + )); + + // Obtener el gestor de arranque automático + let autostart_manager = app.autolaunch(); + // Activar el arranque automático + let _ = autostart_manager.enable(); + // Comprobar el estado de activación + println!("registered for autostart? {}", autostart_manager.is_enabled().unwrap()); + // Desactivar el arranque automático + let _ = autostart_manager.disable(); + } + Ok(()) + }) + .run(tauri::generate_context!()) + .expect("error al ejecutar la aplicación tauri"); +} +``` + + + + +## Permisos + +Por defecto, todos los comandos y ámbitos de plugin potencialmente peligrosos están bloqueados y no se pueden acceder. Debes modificar los permisos en tu configuración de `capabilities` para habilitar estos. + +Consulta la [Descripción general de capacidades](/es/security/capabilities/) para obtener más información y la [guía paso a paso](/es/learn/security/using-plugin-permissions/) para utilizar los permisos de plugin. + +```json title="src-tauri/capabilities/default.json" +{ + "permissions": [ + ..., + "autostart:allow-enable", + "autostart:allow-disable", + "autostart:allow-is-enabled" + ] +} +``` + + diff --git a/src/content/docs/es/plugin/barcode-scanner.mdx b/src/content/docs/es/plugin/barcode-scanner.mdx new file mode 100644 index 0000000000..4839bc4073 --- /dev/null +++ b/src/content/docs/es/plugin/barcode-scanner.mdx @@ -0,0 +1,136 @@ +--- +title: Escáner de códigos de barras +description: Permite que tu aplicación móvil utilice la cámara para escanear códigos QR, EAN-13 y otros tipos de códigos de barras. +sidebar: + badge: + text: Nuevo + variant: tip +plugin: barcode-scanner +i18nReady: true +--- + +import PluginLinks from '@components/PluginLinks.astro'; +import Compatibility from '@components/plugins/Compatibility.astro'; + +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; +import PluginPermissions from '@components/PluginPermissions.astro'; + + + +Permite que tu aplicación móvil utilice la cámara para escanear códigos QR, EAN-13 y otros tipos de códigos de barras. + +## Plataformas compatibles + + + +## Instalación + +Instala el plugin de escáner de códigos de barras para comenzar. + + + + + Usa el gestor de paquetes de tu proyecto para añadir la dependencia: + + {' '} + + + + + + + + 1. Ejecuta el siguiente comando en la carpeta `src-tauri` para añadir el plugin a las dependencias del proyecto en `Cargo.toml`: + + ```sh frame=none + cargo add tauri-plugin-barcode-scanner --target 'cfg(any(target_os = "android", target_os = "ios"))' + ``` + + 2. Modifica `lib.rs` para inicializar el plugin: + + ```rust title="src-tauri/src/lib.rs" ins={5-6} + #[cfg_attr(mobile, tauri::mobile_entry_point)] + pub fn run() { + tauri::Builder::default() + .setup(|app| { + #[cfg(mobile)] + app.handle().plugin(tauri_plugin_barcode_scanner::init()); + Ok(()) + }) + .run(tauri::generate_context!()) + .expect("error al ejecutar la aplicación tauri"); + } + ``` + + 3. Instala los enlaces de JavaScript Guest utilizando tu gestor de paquetes de JavaScript preferido: + + + + + + + + +## Configuración + +En iOS, el plugin de escáner de códigos de barras requiere el valor de la propiedad de lista de información `NSCameraUsageDescription`, que debe describir por qué tu aplicación necesita utilizar la cámara. + +En el archivo `src-tauri/Info.ios.plist`, añade el siguiente fragmento: + +```xml title=src-tauri/Info.ios.plist + + + + + NSCameraUsageDescription + Leer códigos QR + + +``` + +## Uso + +El plugin de escáner de códigos de barras está disponible en JavaScript. + +```javascript +import { scan, Format } from '@tauri-apps/plugin-barcode-scanner'; +// cuando uses `"withGlobalTauri": true`, deberías usar +// const { scan, Format } = window.__TAURI__.barcodeScanner; + +// `windowed: true` en realidad establece la vista web en transparente +// en lugar de abrir una vista separada para la cámara +// asegúrate de que tu interfaz de usuario esté lista para mostrar lo que hay debajo con un elemento transparente +scan({ windowed: true, formats: [Format.QRCode] }); +``` + +## Permisos + +Por defecto, todos los comandos y ámbitos de plugin potencialmente peligrosos están bloqueados y no se pueden acceder. Debes modificar los permisos en tu configuración de `capabilities` para habilitar estos. + +Consulta la [Descripción general de capacidades](/es/security/capabilities/) para obtener más información y la [guía paso a paso](/es/learn/security/using-plugin-permissions/) para utilizar los permisos de plugin. + +```json title="src-tauri/capabilities/mobile.json" +{ + "$schema": "../gen/schemas/mobile-schema.json", + "identifier": "mobile-capability", + "windows": ["main"], + "platforms": ["iOS", "android"], + "permissions": ["barcode-scanner:allow-scan", "barcode-scanner:allow-cancel"] +} +``` + + diff --git a/src/content/docs/es/plugin/clipboard.mdx b/src/content/docs/es/plugin/clipboard.mdx new file mode 100644 index 0000000000..53b9cc15c5 --- /dev/null +++ b/src/content/docs/es/plugin/clipboard.mdx @@ -0,0 +1,119 @@ +--- +title: Portapapeles +description: Lee y escribe en el portapapeles del sistema. +plugin: clipboard-manager +i18nReady: true +--- + +import Stub from '@components/Stub.astro'; +import PluginLinks from '@components/PluginLinks.astro'; +import Compatibility from '@components/plugins/Compatibility.astro'; + +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; +import PluginPermissions from '@components/PluginPermissions.astro'; + + + +Lee y escribe en el portapapeles del sistema utilizando el plugin de portapapeles. + +## Plataformas compatibles + + + +## Configuración + +Instala el plugin de portapapeles para comenzar. + + + + + Usa el gestor de paquetes de tu proyecto para añadir la dependencia: + + + + + + + + 1. Ejecuta el siguiente comando en la carpeta `src-tauri` para añadir el plugin a las dependencias del proyecto en `Cargo.toml`: + + ```sh frame=none + cargo add tauri-plugin-clipboard-manager + ``` + + 2. Modifica `lib.rs` para inicializar el plugin: + + ```rust title="src-tauri/src/lib.rs" ins={4} + #[cfg_attr(mobile, tauri::mobile_entry_point)] + pub fn run() { + tauri::Builder::default() + .plugin(tauri_plugin_clipboard_manager::init()) + .run(tauri::generate_context!()) + .expect("error al ejecutar la aplicación tauri"); + } + ``` + + 3. Si deseas gestionar el portapapeles en JavaScript, también debes instalar el paquete de npm: + + + + + + + + +## Uso + +{/* TODO: Link to which language to use, frontend vs. backend guide when it's made */} + +El plugin de portapapeles está disponible tanto en JavaScript como en Rust. + + + + +```javascript +import { writeText, readText } from '@tauri-apps/plugin-clipboard-manager'; +// cuando uses `"withGlobalTauri": true`, deberías usar +// const { writeText, readText } = window.__TAURI__.clipboardManager; + +// Escribe contenido al portapapeles +await writeText('¡Tauri es increíble!'); + +// Leer contenido del portapapeles +const content = await readText(); +console.log(content); +// Imprime "¡Tauri es increíble!" en la consola +``` + + + + +```rust +use tauri_plugin_clipboard_manager::ClipboardExt; + +app.clipboard().write_text("¡Tauri es increíble!".to_string()).unwrap(); + +// Leer contenido del portapapeles +let content = app.clipboard().read_text(); +println!("{:?}", content.unwrap()); +// Muestra "¡Tauri es increíble!" en la terminal + + +``` + + + + + diff --git a/src/content/docs/es/plugin/localhost.mdx b/src/content/docs/es/plugin/localhost.mdx new file mode 100644 index 0000000000..4cb91cf2b3 --- /dev/null +++ b/src/content/docs/es/plugin/localhost.mdx @@ -0,0 +1,92 @@ +--- +title: Localhost +description: Usa un servidor localhost en aplicaciones en producción. +plugin: localhost +i18nReady: true +--- + +import PluginLinks from '@components/PluginLinks.astro'; +import Compatibility from '@components/plugins/Compatibility.astro'; + +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; + + + +Expone los recursos de tu aplicación a través de un servidor localhost en lugar de usar el protocolo personalizado por defecto. + +:::caution +Este plugin conlleva riesgos de seguridad considerables y solo debes usarlo si sabes lo que estás haciendo. Si tienes dudas, utiliza la implementación del protocolo personalizado por defecto. +::: + +## Plataformas compatibles + + + +## Configuración + +Instala el plugin localhost para comenzar. + + + + + Usa el gestor de paquetes de tu proyecto para añadir la dependencia: + + + + + + + + + 1. Ejecuta el siguiente comando en la carpeta `src-tauri` para añadir el plugin a las dependencias del proyecto en `Cargo.toml`: + + ```sh frame=none + cargo add tauri-plugin-localhost + ``` + + 2. Modifica `lib.rs` para inicializar el plugin: + + ```rust title="src-tauri/src/lib.rs" ins={4} + #[cfg_attr(mobile, tauri::mobile_entry_point)] + pub fn run() { + tauri::Builder::default() + .plugin(tauri_plugin_localhost::Builder::new().build()) + .run(tauri::generate_context!()) + .expect("error al ejecutar la aplicación tauri"); + } + ``` + + + + + + +## Uso + +El plugin localhost está disponible en Rust. + +```rust title="src-tauri/src/lib.rs" {4} {7-14} +use tauri::{webview::WebviewWindowBuilder, WebviewUrl}; + +pub fn run() { + let port: u16 = 9527; + + tauri::Builder::default() + .plugin(tauri_plugin_localhost::Builder::new(port).build()) + .setup(move |app| { + let url = format!("http://localhost:{}", port).parse().unwrap(); + WebviewWindowBuilder::new(app, "main".to_string(), WebviewUrl::External(url)) + .title("Ejemplo de Localhost") + .build()?; + Ok(()) + }) + .run(tauri::generate_context!()) + .expect("error al ejecutar la aplicación tauri"); +} +``` diff --git a/src/content/docs/es/plugin/notification.mdx b/src/content/docs/es/plugin/notification.mdx new file mode 100644 index 0000000000..bdbd3f43af --- /dev/null +++ b/src/content/docs/es/plugin/notification.mdx @@ -0,0 +1,319 @@ +--- +title: Notificaciones +description: Envía notificaciones nativas al usuario. +i18nReady: true +plugin: notification +--- + +import PluginLinks from '@components/PluginLinks.astro'; +import Compatibility from '@components/plugins/Compatibility.astro'; +import PluginPermissions from '@components/PluginPermissions.astro'; +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; + + + +Envía notificaciones nativas al usuario utilizando el plugin de notificaciones. + +## Plataformas soportadas + + + +## Configuración + +Instala el plugin de notificaciones para comenzar. + + + + + Utiliza el gestor de paquetes de tu proyecto para añadir la dependencia: + + + + + + + + + 1. Ejecuta el siguiente comando en el directorio `src-tauri` para añadir el plugin a las dependencias del proyecto en `Cargo.toml`: + + ```sh frame=none + cargo add tauri-plugin-notification + ``` + + 2. Modifica `lib.rs` para inicializar el plugin: + + ```rust title="src-tauri/src/lib.rs" ins={4} + #[cfg_attr(mobile, tauri::mobile_entry_point)] + pub fn run() { + tauri::Builder::default() + .plugin(tauri_plugin_notification::init()) + .run(tauri::generate_context!()) + .expect("error while running tauri application"); + } + ``` + + 3. Si deseas utilizar notificaciones desde JavaScript, instala también el paquete npm: + + + + + + + + + +## Uso + +Aquí hay algunos ejemplos de cómo usar el plugin de notificaciones: + +- [Enviar notificaciones a los usuarios](#enviar-notificación) +- [Añadir una acción a una notificación](#actions) +- [Añadir un adjunto a una notificación](#adjuntos) +- [Enviar una notificación a un canal específico](#canales) + +El plugin de notificaciones está disponible tanto en JavaScript como en Rust. + +### Enviar notificación + +Sigue estos pasos para enviar una notificación: + + +1. Comprueba si se ha concedido el permiso + +2. Solicita permiso si no se ha concedido + +3. Envía la notificación + + + + + + +```javascript +import { + isPermissionGranted, + requestPermission, + sendNotification, +} from '@tauri-apps/plugin-notification'; +// si se usa `"withGlobalTauri": true`, puedes hacer +// const { isPermissionGranted, requestPermission, sendNotification, } = window.__TAURI__.notification; + +// Tienes permiso para enviar una notificación? +let permissionGranted = await isPermissionGranted(); + +// Si no es así, necesitamos solicitarlo +if (!permissionGranted) { + const permission = await requestPermission(); + permissionGranted = permission === 'granted'; +} + +// Una vez que se concede el permiso, envía la notificación +if (permissionGranted) { + sendNotification({ title: 'Tauri', body: 'Tauri is awesome!' }); +} +``` + + + + +```rust +tauri::Builder::default() + .plugin(tauri_plugin_notification::init()) + .setup(|app| { + use tauri_plugin_notification::NotificationExt; + app.notification() + .builder() + .title("Tauri") + .body("Tauri es genial") + .show() + .unwrap(); + + Ok(()) + }) + .run(tauri::generate_context!()) + .expect("error mientras se ejecutaba la aplicación tauri"); +``` + + + + +### Actions + +:::caution[Mobile Only] +La API de Actions solo está disponible en plataformas móviles. +::: + +Las acciones añaden botones e inputs interactivos a las notificaciones. Úsalas para crear una experiencia interactiva para tus usuarios. + +#### Registrar tipos de acciones + +Registra tipos de acciones para definir elementos interactivos: + +```javascript +import { registerActionTypes } from '@tauri-apps/plugin-notification'; + +await registerActionTypes([ + { + id: 'messages', + actions: [ + { + id: 'reply', + title: 'Responder', + input: true, + inputButtonTitle: 'Enviar', + inputPlaceholder: 'Escribe tu respuesta...', + }, + { + id: 'mark-read', + title: 'Marcar como leído', + foreground: false, + }, + ], + }, +]); +``` + +#### Propiedades de las acciones + +| Propiedad | Descripción | +| ------------------------ | ------------------------------------------------------ | +| `id` | Identificador único de la acción | +| `title` | Texto a mostrar en la acción del botón | +| `requiresAuthentication` | Requiere autenticación en el dispositivo | +| `foreground` | Pone la aplicación en primer plano cuando es accionada | +| `destructive` | Muestra la acción en rojo en iOS | +| `input` | Habilita el campo de texto | +| `inputButtonTitle` | Texto para el botón para enviar el input | +| `inputPlaceholder` | Texto de ejemplo en el campo de texto | + +#### Suscribirse a acciones + +Suscribirse a notificaciones con acciones: + +```javascript +import { onAction } from '@tauri-apps/plugin-notification'; + +await onAction((notification) => { + console.log('Acción realizada:', notification); +}); +``` + +### Adjuntos + +Los adjuntos añaden contenido multimedia a las notificaciones. El soporte varía según la plataforma. + +```javascript +import { sendNotification } from '@tauri-apps/plugin-notification'; + +sendNotification({ + title: 'Nueva imagen', + body: 'Mira esta imagen', + attachments: [ + { + id: 'image-1', + url: 'asset:///notification-image.jpg', + }, + ], +}); +``` + +#### Propiedades de los adjuntos + +| Propiedad | Descripción | +| --------- | ---------------------------------------------------------- | +| `id` | Identificador único | +| `url` | URL del contenido usando los protocolos asset:// o file:// | + +Nota: Prueba los adjuntos en tus plataformas que quieras soportar para asegurarte de su compatibilidad. + +### Canales + +Los canales organizan las notificaciones en categorías con diferentes comportamientos. Aunque se usan principalmente en Android, proporcionan una API consistente en todas las plataformas. + +#### Crear un canal + +```javascript +import { + createChannel, + Importance, + Visibility, +} from '@tauri-apps/plugin-notification'; + +await createChannel({ + id: 'messages', + name: 'Mensajes', + description: 'Notificaciones para nuevos mensajes', + importance: Importance.High, + visibility: Visibility.Private, + lights: true, + lightColor: '#ff0000', + vibration: true, + sound: 'notification_sound', +}); +``` + +#### Propiedades de los canales + +| Propiedad | Descripción | +| ------------- | -------------------------------------------------- | +| `id` | Identificador único | +| `name` | Nombre a mostrar | +| `description` | Propósito del canal | +| `importance` | Nivel de prioridad (None, Min, Low, Default, High) | +| `visibility` | Nivel de privacidad (Secret, Private, Public) | +| `lights` | Habilitar indicador LED (Android) | +| `lightColor` | Color del indicador LED (Android) | +| `vibration` | Habilitar vibraciones | +| `sound` | Nombre del fichero para sonido personalizado | + +#### Gestionar canales + +Listar canales existentes: + +```javascript +import { channels } from '@tauri-apps/plugin-notification'; + +const existingChannels = await channels(); +``` + +Eliminar un canal: + +```javascript +import { removeChannel } from '@tauri-apps/plugin-notification'; + +await removeChannel('messages'); +``` + +#### Usando canales + +Enviar una notificación usando un canal: + +```javascript +import { sendNotification } from '@tauri-apps/plugin-notification'; + +sendNotification({ + title: 'Nuevo mensaje', + body: 'Tienes un nuevo mensaje', + channelId: 'messages', +}); +``` + +Nota: Crea canales antes de enviar notificaciones que los referencien. Los identificadores de canal inválidos impiden que las notificaciones se muestren. + +## Consideraciones de seguridad + +Aparte de los procedimientos normales de sanitización de la entrada del usuario, actualmente no hay consideraciones de seguridad conocidas. + + diff --git a/src/content/docs/es/start/frontend/nextjs.mdx b/src/content/docs/es/start/frontend/nextjs.mdx index 43969fe697..ff0d9f7f1e 100644 --- a/src/content/docs/es/start/frontend/nextjs.mdx +++ b/src/content/docs/es/start/frontend/nextjs.mdx @@ -1,90 +1,131 @@ --- title: Next.js i18nReady: true +tableOfContents: + collapseLevel: 1 + minHeadingLevel: 2 + maxHeadingLevel: 5 --- -import { Tabs, TabItem } from '@astrojs/starlight/components'; +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; import CommandTabs from '@components/CommandTabs.astro'; -Next.js es un framework para React. Aprende más sobre Next.js en https://nextjs.org. Esta guía es precisa a partir de Next.js 13.4.19. +Next.js es un meta framework para React. Aprende más sobre Next.js en https://nextjs.org. Esta guía es válida para Next.js 14.2.3. ## Checklist - Usa exports estáticos estableciendo `output: 'export'`. Tauri no soporta soluciones basadas en el servidor. -- Usa `out/` como `distDir` en `tauri.conf.json`. +- Usa el directorio `out` como `frontendDist` en `tauri.conf.json`. ## Ejemplo de Configuración -1. Actualiza la configuración de Tauri: - - - - -```json -// tauri.conf.json -{ - "build": { - "beforeDevCommand": "npm run dev", - "beforeBuildCommand": "npm run build", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } -} -``` - - - - -```json -// tauri.conf.json -{ - "build": { - "beforeDevCommand": "yarn dev", - "beforeBuildCommand": "yarn generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } -} -``` - - - - -```json -// tauri.conf.json -{ - "build": { - "beforeDevCommand": "pnpm dev", - "beforeBuildCommand": "pnpm generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } -} -``` - - - - -2. Actualiza la configuración de Next.js: - -```ts -// next.conf.ts -const isProd = process.env.NODE_ENV === 'production'; -module.exports = async (phase, { defaultConfig }) => { - // En modo de desarrollo usamos TAURI_DEV_HOST para servir los archivos si es necesario - const internalHost = process.env.TAURI_DEV_HOST || 'localhost'; - const nextConfig = { - // Aségurate de que Next.js use SSG en lugar de SSR - // https://nextjs.org/docs/pages/building-your-application/deploying/static-exports - output: 'export', - // Nota: Esta función experimental es necesaria para usar NextJS Image en modo SSG. - // Consulta https://nextjs.org/docs/messages/export-image-api para ver diferentes soluciones. - images: { - unoptimized: true, - }, - // Configura assetPrefix o el servidor no resolverá correctamente tus archivos. - assetPrefix: isProd ? null : `http://${internalHost}:3000`, - }; - return nextConfig; -}; -``` + + +1. ##### Actualiza la configuración de Tauri + + + + + + ```json + // src-tauri/tauri.conf.json + { + "build": { + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run build", + "devUrl": "http://localhost:3000", + "frontendDist": "../out" + } + } + ``` + + + + + + ```json + // src-tauri/tauri.conf.json + { + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn build", + "devUrl": "http://localhost:3000", + "frontendDist": "../out" + } + } + ``` + + + + + + ```json + // src-tauri/tauri.conf.json + { + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm build", + "devUrl": "http://localhost:3000", + "frontendDist": "../out" + } + } + ``` + + + + + + ```json + // src-tauri/tauri.conf.json + { + "build": { + "beforeDevCommand": "deno task dev", + "beforeBuildCommand": "deno task build", + "devUrl": "http://localhost:3000", + "frontendDist": "../out" + } + } + ``` + + + + + +2. ##### Actualiza la configuración de Next.js + + ```ts + // next.conf.mjs + const isProd = process.env.NODE_ENV === 'production'; + + const internalHost = process.env.TAURI_DEV_HOST || 'localhost'; + + /** @type {import('next').NextConfig} */ + const nextConfig = { + // Asegurate de que Next.js usa SSG en lugar de SSR + // https://nextjs.org/docs/pages/building-your-application/deploying/static-exports + output: 'export', + // Nota: Esta función es necesaria para usar el componente Image de Next.js en modo SSG. + // Consulta https://nextjs.org/docs/messages/export-image-api para ver algunas soluciones alternativas. + images: { + unoptimized: true, + }, + // Configura assetPrefix; de lo contrario, el servidor no resolverá correctamente tus recursos. + assetPrefix: isProd ? undefined : `http://${internalHost}:3000`, + }; + + export default nextConfig; + ``` + +3. ##### Actualiza la configuración de package.json + + ```json + "scripts": { + "dev": "next dev", + "build": "next build", + "start": "next start", + "lint": "next lint", + "tauri": "tauri" + } + ``` + + diff --git a/src/content/docs/es/start/frontend/nuxt.mdx b/src/content/docs/es/start/frontend/nuxt.mdx index a3a4b0c7f0..88dd828b3a 100644 --- a/src/content/docs/es/start/frontend/nuxt.mdx +++ b/src/content/docs/es/start/frontend/nuxt.mdx @@ -1,102 +1,117 @@ --- title: Nuxt i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 5 --- -import { Tabs, TabItem } from '@astrojs/starlight/components'; +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; -Aprende más sobre Nuxt en https://nuxt.com. Esta guía es precisa a partir de Nuxt 3.7. +Nuxt es un meta framework para Vue. Aprende más sobre Nuxt en https://nuxt.com. Esta guía es válida para Nuxt 3.11. ## Checklist - Usa SSG estableciendo `ssr: false`. Tauri no soporta soluciones basadas en el servidor. -- Configura el host a `0.0.0.0`. +- Usa `process.env.TAURI_DEV_HOST` como dirección IP del servidor de desarrollo cuando se configure para ejecutarse en dispositivos físicos con iOS. - Usa `dist/` como `distDir` en `tauri.conf.json`. - Compila usando `nuxi generate`. - (Opcional): Deshabilita la telemetría estableciendo `telemetry: false` en `nuxt.config.ts`. ## Ejemplo de Configuración -1. Actualiza la configuración de Tauri: - - - - -```json -// tauri.conf.json -{ - "build": { - "beforeDevCommand": "npm run dev", - "beforeBuildCommand": "npm run generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } -} -``` - - - - -```json -// tauri.conf.json -{ - "build": { - "beforeDevCommand": "yarn dev", - "beforeBuildCommand": "yarn generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } -} -``` - - - - -```json -// tauri.conf.json -{ - "build": { - "beforeDevCommand": "pnpm dev", - "beforeBuildCommand": "pnpm generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } -} -``` - - - - - -2. Actualiza la configuración de Nuxt: - -```ts -export default defineNuxtConfig({ - // (opcional) Habilita las herramientas de desarrollo de Nuxt - devtools: { enabled: true }, - // Habilita SSG - ssr: false, - vite: { - // Mejor soporte para la salida de Tauri CLI - clearScreen: false, - // Habilita las variables de entorno - // Las variables de entorno adicionales se pueden encontrar en - // https://v2.tauri.app/reference/environment-variables/ - envPrefix: ['VITE_', 'TAURI_'], - server: { - // Tauri requiere un puerto consistente - strictPort: true, - // Habilita el servidor de desarrollo para pueda ser accedido por otros dispositivos para el desarrollo móvil - host: '0.0.0.0', - hmr: { - // Usa un websocket para la recarga rápida en móviles - protocol: 'ws', - // Asegúrate de que esté disponible en la red - host: '0.0.0.0', - // Usa un puerto específico para hmr - port: 5183, + + +1. ##### Actualiza la configuración de Tauri: + + + + + + ```json + // tauri.conf.json + { + "build": { + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run generate", + "devUrl": "http://localhost:3000", + "frontendDist": "../dist" + } + } + ``` + + + + + ```json + // tauri.conf.json + { + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn generate", + "devUrl": "http://localhost:3000", + "frontendDist": "../dist" + } + } + ``` + + + + + ```json + // tauri.conf.json + { + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm generate", + "devUrl": "http://localhost:3000", + "frontendDist": "../dist" + } + } + ``` + + + + + ```json + // tauri.conf.json + { + "build": { + "beforeDevCommand": "deno task dev", + "beforeBuildCommand": "deno task generate", + "devUrl": "http://localhost:3000", + "frontendDist": "../dist" + } + } + ``` + + + + + +2. ##### Actualiza la configuración de Nuxt: + + ```ts + export default defineNuxtConfig({ + // (opcional) Habilita las herramientas de desarrollo de Nuxt + devtools: { enabled: true }, + // Habilita SSG + ssr: false, + // Permite que el servidor de desarrollo sea detectable por otros dispositivos al ejecutarse en dispositivos físicos con iOS + devServer: { host: process.env.TAURI_DEV_HOST || 'localhost' }, + vite: { + // Mejor soporte para la salida de Tauri CLI + clearScreen: false, + // Habilita las variables de entorno + // Las variables de entorno adicionales se pueden encontrar en + // https://v2.tauri.app/reference/environment-variables/ + envPrefix: ['VITE_', 'TAURI_'], + server: { + // Tauri requiere un puerto consistente + strictPort: true, + }, }, - }, - }, -}); -``` + }); + ``` + + diff --git a/src/content/docs/es/start/frontend/qwik.mdx b/src/content/docs/es/start/frontend/qwik.mdx new file mode 100644 index 0000000000..03ac887c9c --- /dev/null +++ b/src/content/docs/es/start/frontend/qwik.mdx @@ -0,0 +1,142 @@ +--- +title: Qwik +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 5 +--- + +import { Steps, TabItem, Tabs } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; + +Esta guía te llevará paso a paso para crear aplicación Tauri usando el framework web Qwik. Aprende más sobre Qwik en https://qwik.dev. + +## Checklist + +- Usa [SSG](https://qwik.dev/docs/guides/static-site-generation/). Tauri no soporta oficialmente soluciones basadas en el servidor. +- Usa `dist/` en lugar de `frontendDist` en `tauri.conf.json`. + +## Ejemplo de Configuración + + + +1. ##### Crea una nueva aplicación Qwik + + `} + yarn={`yarn create qwik@latest + cd `} + pnpm={`pnpm create qwik@latest + cd `} + deno={`deno run -A npm:create-qwik@latest + cd `} + /> + +1. ##### Instala el `static adapter` + + + +1. ##### Añade la CLI de Tauri a tu proyecto + + + +1. ##### Inicializa un nuevo projecto Tauri + + + +1. ##### Configura Tauri + + + + + + ```json + // tauri.conf.json + { + "build": { + "devUrl": "http://localhost:5173" + "frontendDist": "../dist", + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run build" + } + } + ``` + + + + + + ```json + // tauri.conf.json + { + "build": { + "devUrl": "http://localhost:5173" + "frontendDist": "../dist", + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn build" + } + } + ``` + + + + + + ```json + // tauri.conf.json + { + "build": { + "devUrl": "http://localhost:5173" + "frontendDist": "../dist", + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm build" + } + } + ``` + + + + + + ```json + // tauri.conf.json + { + "build": { + "devUrl": "http://localhost:5173" + "frontendDist": "../dist", + "beforeDevCommand": "deno task dev", + "beforeBuildCommand": "deno task build" + } + } + ``` + + + + + +1. ##### Ejecuta tu aplicación `tauri` + + + + diff --git a/src/content/docs/es/start/frontend/sveltekit.mdx b/src/content/docs/es/start/frontend/sveltekit.mdx new file mode 100644 index 0000000000..39c17d3386 --- /dev/null +++ b/src/content/docs/es/start/frontend/sveltekit.mdx @@ -0,0 +1,137 @@ +--- +title: SvelteKit +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 5 +--- + +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; +import CommandTabs from '@components/CommandTabs.astro'; + +SvelteKit es un meta framework para Svelte. Aprende más sobre SvelteKit en https://svelte.dev/. Esta guía es válida para SvelteKit 2.5.7 y Svelte 4.2.15. + +## Checklist + +- Usa [SSG](https://svelte.dev/docs/kit/adapter-static) y/o [SPA](https://svelte.dev/docs/kit/single-page-apps) a través de `static-adapter`. Tauri no soporta oficialmente soluciones basadas en el servidor. +- Usa `build/` en lugar de `frontendDist` en `tauri.conf.json`. + +## Ejemplo de Configuración + + + +1. ##### Instala `@sveltejs/adapter-static` + + + +1. ##### Actualiza la configuración de Tauri + + + + + + ```json + // tauri.conf.json + { + "build": { + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run build", + "devUrl": "http://localhost:5173", + "frontendDist": "../build" + } + } + ``` + + + + + + ```json + // tauri.conf.json + { + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn build", + "devUrl": "http://localhost:5173", + "frontendDist": "../build" + } + } + ``` + + + + + + ```json + // tauri.conf.json + { + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm build", + "devUrl": "http://localhost:5173", + "frontendDist": "../build" + } + } + ``` + + + + + + ```json + // tauri.conf.json + { + "build": { + "beforeDevCommand": "deno task dev", + "beforeBuildCommand": "deno task build", + "devUrl": "http://localhost:5173", + "frontendDist": "../build" + } + } + ``` + + + + + +1. ##### Actualiza la configuración de SvelteKit: + + ```js title="svelte.config.js" {1} + import adapter from '@sveltejs/adapter-static'; + import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; + + /** @type {import('@sveltejs/kit').Config} */ + const config = { + // Consulta https://svelte.dev/docs/kit/integrations#preprocessors + // para más información sobre preprocesadores + preprocess: vitePreprocess(), + + kit: { + adapter: adapter(), + }, + }; + + export default config; + ``` + +1. ##### Desactiva el SSR + + Por último, necesitamos desactivar el SRR y habilitar el prerenderizado añadiendo un archivo raíz `+layout.ts` (o `+layout.js` si no estás usando TypeScript) con el siguiente contenido: + + ```ts + // src/routes/+layout.ts + export const prerender = true; + export const ssr = false; + ``` + + Ten en cuenta que `static-adapter` no requiere desactivar el SSR para toda la aplicación, pero permite usar APIs que dependen del objeto global window (como la API de Tauri) sin necesidad de realizar [comprobaciones del lado del cliente](https://svelte.dev/docs/kit/faq#how-do-i-use-x-with-sveltekit-how-do-i-use-a-client-side-only-library-that-depends-on-document-or-window). + + Además, si prefieres el modo de Aplicación de Página Única (SPA) en lugar de SSG, puedes cambiar las configuraciones del adaptador y el archivo `+layout.ts` según la [documentación del adaptador](https://svelte.dev/docs/kit/single-page-apps). + + diff --git a/src/content/docs/es/start/frontend/trunk.mdx b/src/content/docs/es/start/frontend/trunk.mdx index b8c8ea594f..31ab0a9d17 100644 --- a/src/content/docs/es/start/frontend/trunk.mdx +++ b/src/content/docs/es/start/frontend/trunk.mdx @@ -1,44 +1,51 @@ --- title: Trunk i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 5 --- -Trunk es una herramienta de empaquetado de aplicaciones web WASM para Rust. Obtén más información sobre Trunk en https://trunkrs.dev. Esta guía es precisa a partir de Trunk 0.17.5. +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; + +Trunk es una herramienta de empaquetado de aplicaciones web WASM para Rust. Aprende más sobre Trunk en https://trunkrs.dev. Esta guía es válida para Trunk 0.17.5. ## Checklist - Usa SSG, Tauri no soporta oficialmente soluciones basadas en el servidor. -- Usa `address = "0.0.0.0"` para que el servidor web esté disponible en la red para el desarrollo móvil. -- Usa `ws_protocol = "ws"` para que el websocket de recarga rápida pueda conectarse correctamente para el desarrollo móvil. +- Usa `serve.ws_protocol = "ws"` para que el websocket de recarga rápida pueda conectarse correctamente para el desarrollo móvil. - Habilita `withGlobalTauri` para asegurarte de que las APIs de Tauri están disponibles en la variable `window.__TAURI__` y pueden ser importadas usando `wasm-bindgen`. ## Ejemplo de Configuración -1. Actualiza la configuración de Tauri: - -```json -// tauri.conf.json -{ - "build": { - "beforeDevCommand": "trunk serve", - "beforeBuildCommand": "trunk build", - "devPath": "http://localhost:8080", - "distDir": "../dist" - }, - "app": { - "withGlobalTauri": true - } -} -``` - -2. Actualiza la configuración de Trunk: - -```toml -# Trunk.toml -[watch] -ignore = ["./src-tauri"] - -[serve] -address = "0.0.0.0" -ws_protocol = "ws" -``` + + +1. ##### Actualiza la configuración de Tauri + + ```json + // tauri.conf.json + { + "build": { + "beforeDevCommand": "trunk serve", + "beforeBuildCommand": "trunk build", + "devUrl": "http://localhost:8080", + "frontendDist": "../dist" + }, + "app": { + "withGlobalTauri": true + } + } + ``` + +1. ##### Actualiza la configuración de Trunk + + ```toml + # Trunk.toml + [watch] + ignore = ["./src-tauri"] + + [serve] + ws_protocol = "ws" + ``` + + diff --git a/src/content/docs/es/start/index.mdx b/src/content/docs/es/start/index.mdx new file mode 100644 index 0000000000..eb5749850f --- /dev/null +++ b/src/content/docs/es/start/index.mdx @@ -0,0 +1,50 @@ +--- +title: ¿Qué es Tauri? +i18nReady: true +sidebar: + order: 0 +--- + +Tauri es un framework que sirve para crear binarios pequeños y rápidos para las principales plataformas de escritorio y móviles. Los desarrolladores pueden usar cualquier framework de frontend que compile a HTML, JavaScript y CSS para crear su experiencia de usuario, y al mismo tiempo aprovechar lenguajes como Rust, Swift y Kotlin para la lógica del backend cuando sea necesario. + +Empieza a construir tu aplicación con [`create-tauri-app`](https://github.com/tauri-apps/create-tauri-app) usando uno de los comandos que se encuentran abajo. Asegurate de seguir la [guía de prerrequisitos](/es/start/prerequisites/) para instalar todas las dependencias requeridas por Tauri y después mira las [guías de Configuración de Frontend](/es/start/frontend/) para ver las configuraciones recomendadas. + +import Cta from '../../_fragments/cta.mdx'; + + + +Después de haber creado tu primera aplicación, puedes explorar las diferentes características y fórmulas de Tauri en el [Listado de Características y Fórmulas](/es/plugin/). + +## ¿Por qué Tauri? + +Tauri tiene 3 ventajas principales que los desarrolladores pueden aprovechar: + +- Base segura para construir aplicaciones +- Tamaño de paquete más pequeño usando la vista web nativa del sistema +- Flexibilidad para que los desarrolladores usen cualquier frontend y soporte para múltiples lenguajes + +Aprende más sobre la filosofía de Tauri en la [publicación del blog de Tauri 1.0](/blog/tauri-1-0/). + +### Base segura + +Al estar contruido en Rust, Tauri es capaz de aprovechar la memoria, hilos y tipado seguro ofrecidos por Rust. Las aplicaciones construidas en Tauri pueden obtener estos beneficios automáticamente sin la necesidad de estar desarrolladas por expertos en Rust. + +Además, Tauri se somete a auditorías de seguridad para sus versiones principales y secundarias. Esto no solo abarca el código en la organización de Tauri, sino que también todas las dependencias de las que Tauri depende. Por supuesto, esto no elimina todo el riesgo, pero provee de una base muy sólida para que los desarrolladores construyan sobre ella. + +Lee la [póliza de seguidad de Tauri](https://github.com/tauri-apps/tauri/security/policy) y el [reporte de auditoría de Tauri 2.0](https://github.com/tauri-apps/tauri/blob/dev/audits/Radically_Open_Security-v2-report.pdf). + +### Tamaño de aplicaciones más pequeño + +Las aplicaciones hechas con Tauri se aprovechan de la vista web nativa del sistema del usuario. Una aplicación de Tauri solo contiene el código y los recursos específicos para esa aplicación, sin la necesidad de tener que empaquetar un motor de navegador en cada aplicación. Esto significa que una aplicación sencilla de Tauri puede tener un tamaño menor a 600KB. + +Aprende más sobre como crear aplicaciones optimizadas en el [concepto de Tamaño de Aplicación](/es/concept/size/). + +### Arquitectura flexible + +Dado que Tauri usa tecnologías web, prácticamente cualquier framework de frontend es compatible con Tauri. La [guía de Configuración de Frontend](/es/start/frontend/) incluye configuraciones comunes para frameworks de frontend populares. + +Las conexiones entre JavaScript y Rust están disponibles para los desarrolladores usando la función `invoke` en JavaScript, mientras que los enlaces para Swift y Kotlin están disponibles para [los Plugins de Tauri](/es/develop/plugins/). + +[TAO](https://github.com/tauri-apps/tao) se encarga de la creación de ventanas en Tauri y [WRY](https://github.com/tauri-apps/wry) de la renderización web. Ambas librerías son mantenidas por Tauri y pueden ser utilizadas directamente si se requiere un nivel más profundo de integración al que Tauri expone. + +Además, Tauri mantiene varios plugins para ampliar las funcionalidades que ofrece el núcleo de Tauri. Puedes encontrar estos plugins junto con los proporcionados por la comunidad en la [sección de Plugins](/es/plugin/). diff --git a/src/content/docs/es/start/migrate/from-tauri-1.mdx b/src/content/docs/es/start/migrate/from-tauri-1.mdx index 8eecd5db01..f19ebf752e 100644 --- a/src/content/docs/es/start/migrate/from-tauri-1.mdx +++ b/src/content/docs/es/start/migrate/from-tauri-1.mdx @@ -2,7 +2,7 @@ title: Actualizar desde Tauri 1.0 i18nReady: true sidebar: - order: 12 + order: 15 --- import { Tabs, TabItem } from '@astrojs/starlight/components'; @@ -10,7 +10,7 @@ import CommandTabs from '@components/CommandTabs.astro'; Esta guía te guiará a través de la actualización de tu aplicación Tauri 1.0 a Tauri 2.0. -## Preparándose para móvil +## Preparación para móvil La interfaz móvil de Tauri requiere que tu proyecto produzca una biblioteca compartida. Si estás apuntando a móviles para tu aplicación existente, debes cambiar tu crate para producir ese tipo de artefacto junto con el ejecutable de escritorio. @@ -63,8 +63,6 @@ La CLI de Tauri v2 incluye un comando `migrate` que automatiza la mayor parte de cargo tauri migrate' /> -{/* TODO: 2.0 */} - Para saber más sobre el comando `migrate`, consulta la [Referencia de la interfaz de línea de comandos](/reference/cli/#migrate) ## Resumen de los cambios @@ -74,6 +72,7 @@ A continuación se resumen los cambios de Tauri 1.0 a Tauri 2.0: ### Configuración de Tauri - Los campos `package > productName` y `package > version` se han trasladado al campo de nivel superior. +- el nombre del binario ya no se renombra automáticamente para coincidir con `productName`, por lo que debes agregar una string `mainBinaryName` en el objeto de nivel superior que coincida con `productName`. - `package` eliminado. - La clave `tauri` ha pasado a ser `app`. - `tauri > allowlist` eliminado. Véase [Migrar permisos](#migrar-permisos). @@ -83,15 +82,19 @@ A continuación se resumen los cambios de Tauri 1.0 a Tauri 2.0: - `tauri > updater > active` eliminado. - `tauri > updater > dialog` eliminado. - `tauri > updater` movido a `plugins > updater`. +- Se ha agragado `bundle > createUpdaterArtifacts`, debe ser configurado al usar el actualizador de la aplicación. + - configúralo a `v1Compatible` cuando actualices desde aplicaciones de la V1 que ya habían sido distribuidas. Consulta la [guía del actualizador](/es/plugin/updater/) para más información. - `tauri > systemTray` renombrado a `app > trayIcon`. - `tauri > pattern` movido a `app > security > pattern`. - `tauri > bundle` movido a nivel superior. +- `tauri > bundle > identifier` movido a objeto del nivel superior. - `tauri > bundle > dmg` movido a `bundle > macOS > dmg` - `tauri > bundle > deb` movido a `bundle > linux > deb` - `tauri > bundle > appimage` movido a `bundle > linux > appimage` - `tauri > bundle > macOS > license` eliminado, utiliza `bundle > licenseFile` en su lugar. - `tauri > bundle > windows > wix > license` eliminado, utiliza `bundle > licenseFile` en su lugar. - `tauri > bundle > windows > nsis > license` eliminado, utiliza `bundle > licenseFile` en su lugar. +- `tauri > bundle > windows > webviewFixedRuntimePath` eliminado, utiliza `bundle > windows > webviewInstallMode` en su lugar. - `build > withGlobalTauri` movido a `app > withGlobalTauri`. - `build > distDir` renombrado a `frontendDist`. - `build > devPath` renombrado a `devUrl`. @@ -132,7 +135,6 @@ A continuación se resumen los cambios de Tauri 1.0 a Tauri 2.0: - El método `Plugin::setup_with_config` ha sido eliminado. Utiliza el actualizado `tauri::Plugin::PluginApi` en su lugar. - Los métodos `scope::ipc::RemoteDomainAccessScope::enable_tauri_api` y `scope::ipc::RemoteDomainAccessScope::enables_tauri_api` han sido eliminados. Habilita cada plugin del núcleo individualmente mediante `scope::ipc::RemoteDomainAccessScope::add_plugin` en su lugar. - El módulo `scope::IpcScope` ha sido eliminado, utiliza `scope::ipc::Scope` en su lugar. -- El módulo `scope::IpcScope` ha sido eliminado, utiliza `scope::ipc::Scope` en su lugar. - Los módulos `scope::FsScope`, `scope::GlobPattern` y `scope::FsScopeEvent` han sido eliminados, utiliza `scope::fs::Scope`, `scope::fs::Pattern` y `scope::fs::Event` respectivamente. - El módulo `updater` ha sido eliminado. Utiliza `tauri-plugin-updater` en su lugar. [Migración](#migrar-al-plugin-de-actualizaciones) - El campo `Env.args` ha sido eliminado, utiliza el campo `Env.args_os` en su lugar. @@ -157,6 +159,8 @@ El paquete `@tauri-apps/api` ya no proporciona módulos no centrales. Sólo se e - El módulo `@tauri-apps/api/updater` ha sido eliminado. Utiliza `@tauri-apps/plugin-updater` en su lugar. [Migración](#migrar-al-plugin-de-actualizaciones) - El módulo `@tauri-apps/api/window` ha sido renombrado a `@tauri-apps/api/webviewWindow`. [Migración](#migrar-a-la-nueva-api-de-ventanas) +Los plugins the la V1 ahora están publicados como `@tauri-apps/plugin-`. Anteriormente, estaban disponibles desde git como `tauri-plugin--api`. + ### Cambios en las variables de entorno La mayoría de las variables de entorno leídas y escritas por el CLI de Tauri fueron renombradas por consistencia y prevención de errores: @@ -193,6 +197,10 @@ Para admitirlo, renombramos el tipo de ventana Rust `Window` a `WebviewWindow` y El tipo de API JS `WebviewWindow` ahora se reexporta desde `@tauri-apps/api/webviewWindow` en lugar de `@tauri-apps/api/window`. +### Nueva URL de origen en Windows + +On Windows the frontend files in production apps are now hosted on `http://tauri.localhost` instead of `https://tauri.localhost`. Because of this IndexedDB, LocalStorage and Cookies will be reset unless `dangerousUseHttpScheme` was used in v1. To prevent this you can set `app > windows > useHttpsScheme` to `true` or use `WebviewWindowBuilder::use_https_scheme` to keep using the `https` scheme. + ## Pasos Detallados de Migración Escenarios comunes que puedes encontrar al migrar tu aplicación de Tauri 1.0 a Tauri 2.0. @@ -566,7 +574,7 @@ tauri::Builder::default() }) ``` -El plugin HTTP reexporta [reqwest](https://docs.rs/reqwest/latest/reqwest/) para que puedas consultar su documentación para obtener más información. +El plugin HTTP reexporta [reqwest](https://docs.rs/reqwest/latest/reqwest/) así que puedes consultar su documentación para obtener más información.
@@ -1007,7 +1015,7 @@ Consulta [TrayIconBuilder](https://docs.rs/tauri/2.0.0/tauri/tray/struct.TrayIco #### Migrar a Menú -Utiliza `tauri::menu::Menu` en lugar de `tauri::SystemTrayMenu`, `tauri::menu::Submenu` en lugar de `tauri::SystemTraySubmenu`, y `tauri::menu::PredefinedMenuItem` en lugar de `tauri::SystemTrayMenuItem`. [Migración](#migrar-a-menú) +Utiliza `tauri::menu::Menu` en lugar de `tauri::SystemTrayMenu`, `tauri::menu::Submenu` en lugar de `tauri::SystemTraySubmenu`, y `tauri::menu::PredefinedMenuItem` en lugar de `tauri::SystemTrayMenuItem`. #### Eventos de Bandeja @@ -1016,7 +1024,7 @@ Utiliza `tauri::menu::Menu` en lugar de `tauri::SystemTrayMenu`, `tauri::menu::S ```rust use tauri::{ menu::{MenuBuilder, MenuItemBuilder}, - tray::{ClickType, TrayIconBuilder}, + tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}, }; tauri::Builder::default() @@ -1032,11 +1040,17 @@ tauri::Builder::default() _ => (), }) .on_tray_icon_event(|tray, event| { - if event.click_type == ClickType::Left { + if let TrayIconEvent::Click { + button: MouseButton::Left, + button_state: MouseButtonState::Up, + .. + } = event + { let app = tray.app_handle(); if let Some(webview_window) = app.get_webview_window("main") { - let _ = webview_window.show(); - let _ = webview_window.set_focus(); + let _ = webview_window.unminimize(); + let _ = webview_window.show(); + let _ = webview_window.set_focus(); } } }) @@ -1086,10 +1100,12 @@ import { relaunch } from '@tauri-apps/plugin-process'; const update = await check(); if (update?.available) { - console.log(`Update to ${update.version} available! Date: ${update.date}`); - console.log(`Release notes: ${update.body}`); + console.log( + `¡Actualización a ${update.version} disponible! Fecha: ${update.date}` + ); + console.log(`Notas del parche: ${update.body}`); await update.downloadAndInstall(); - // requires the `process` plugin + // requiere el plugin `process` await relaunch(); } ``` @@ -1141,9 +1157,9 @@ use tauri::{path::BaseDirectory, Manager}; tauri::Builder::default() .setup(|app| { - let home_dir_path = app.path().home_dir().expect("failed to get home dir"); + let home_dir_path = app.path().home_dir().expect("no se pudo obtener el directorio home"); - let path = app.path().resolve("path/to/something", BaseDirectory::Config)?; + let path = app.path().resolve("path/haz/algo", BaseDirectory::Config)?; Ok(()) }) @@ -1151,7 +1167,7 @@ tauri::Builder::default() ### Migrar a la nueva API de Ventanas -En el lado de Rust, `Window` fue renombrado a `WebviewWindow` y su constructor `WindowBuilder` ahora se llama `WebviewWindowBuilder`. +En el lado de Rust, `Window` fue renombrado a `WebviewWindow`, su constructor `WindowBuilder` ahora se llama `WebviewWindowBuilder` y `WindowUrl` ahora se llama `WebviewUrl`. Además, la función `Manager::get_window` fue renombrada a `get_webview_window` y la API `parent_window` de la ventana fue renombrada a `parent_raw` para admitir una API de ventana principal de alto nivel. @@ -1160,13 +1176,20 @@ En el lado de JavaScript, la clase `WebviewWindow` ahora se exporta en la ruta ` La función `onMenuClicked` fue eliminada, ahora puedes interceptar eventos de menú al crear un menú en JavaScript en su lugar. +### Migrar Archivos Adicionales Incrustados (Recursos) + +En el lado de JavaScript, asegúrate de [Migrar al Plugin del Sistema de Archivos](#migrar-al-plugin-del-sistema-de-archivos). +Además, ten en cuenta que los cambios hechos en la lista blanca de la v1 en [Migrar Permisos](#migrar-permisos). + +En el lado de Rust, asegúrate de [Migrar de Path a Tauri Manager](#migrar-de-path-a-tauri-manager). + ### Migrar de Binarios Externos Incrustados (Sidecar) En Tauri v1, los binarios externos y sus argumentos se definían en la lista blanca. En la v2, utiliza el nuevo sistema de permisos. Lee [Migración de Permisos](#migrar-permisos) para más información. En el lado de JavaScript, asegúrate de [Migrar al Plugin Shell](#migrar-al-plugin-shell). -En el lado de Rust, la API `tauri::api::process` ha sido eliminada. Usa `tauri_plugin_shell::ShellExt` y las APIs `tauri_plugin_shell::process::CommandEvent` en su lugar. Lee la guía de [Incrustar Binarios Externos](/develop/sidecar/#running-it-from-rust) para ver cómo. +En el lado de Rust, la API `tauri::api::process` ha sido eliminada. Usa `tauri_plugin_shell::ShellExt` y las APIs `tauri_plugin_shell::process::CommandEvent` en su lugar. Lee la guía de [Incrustar Binarios Externos](/es/develop/sidecar/#running-it-from-rust) para ver cómo. El indicador de características "process-command-api" ha sido eliminado en la v2. Por lo tanto, ejecutar los binarios externos ya no requiere que esta característica esté definida en la configuración de Tauri. @@ -1179,4 +1202,4 @@ Para habilitar permisos para tu aplicación, debes crear archivos de capacidades El comando `migrate` de la CLI analiza automáticamente tu lista blanca v1 y genera el archivo de capacidad asociado. -Para obtener más información sobre permisos y capacidades, consulta [la documentación](/security/). +Para obtener más información sobre permisos y capacidades, consulta [la documentación de seguridad](/es/security/). diff --git a/src/content/docs/es/start/prerequisites.mdx b/src/content/docs/es/start/prerequisites.mdx index e26bd247c4..17aa11511f 100644 --- a/src/content/docs/es/start/prerequisites.mdx +++ b/src/content/docs/es/start/prerequisites.mdx @@ -1,6 +1,8 @@ --- title: Prerrequisitos i18nReady: true +sidebar: + order: 0 --- import { Tabs, TabItem, Card } from '@astrojs/starlight/components'; @@ -36,6 +38,7 @@ sudo apt install libwebkit2gtk-4.1-dev \ curl \ wget \ file \ + libxdo-dev \ libssl-dev \ libayatana-appindicator3-dev \ librsvg2-dev @@ -55,7 +58,8 @@ sudo pacman -S --needed \ openssl \ appmenu-gtk-module \ libappindicator-gtk3 \ - librsvg + librsvg \ + xdotool ``` @@ -69,8 +73,9 @@ sudo dnf install webkit2gtk4.1-devel \ wget \ file \ libappindicator-gtk3-devel \ - librsvg2-devel -sudo dnf group install "C Development Tools and Libraries" + librsvg2-devel \ + libxdo-devel +sudo dnf group install "c-development" ``` @@ -100,10 +105,25 @@ sudo zypper in webkit2gtk3-devel \ sudo zypper in -t pattern devel_basis ``` + + +```sh +sudo apk add \ + build-base \ + webkit2gtk \ + curl \ + wget \ + file \ + openssl \ + libayatana-appindicator-dev \ + librsvg +``` -TODO: Need to build out NixOS instructions +:::note +Las instrucciones para Nix/NixOS pueden ser encontradas en [NixOS Wiki](https://wiki.nixos.org/wiki/Tauri). +::: @@ -146,7 +166,7 @@ Sigue los pasos a continuación para instalar las dependencias requeridas. 1. Descarga el instalador de [Microsoft C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) y ábrelo para comenzar la instalación. 2. Durante la instalación marque la opción "Desarrollo de escritorio con C ++". -![Visual Studio C++ Build Tools installer screenshot](./visual-studio-build-tools-installer.png) +![Captura de pantalla de Visual Studio C++ Build Tools installer](./visual-studio-build-tools-installer.png) Siguiente: [Instalar WebView2](#webview2). @@ -186,12 +206,53 @@ Aquí está el archivo como un script plano: [rustup.sh](https://sh.rustup.rs/) Visita https://www.rust-lang.org/tools/install para instalar `rustup`. +Alternativamente, puedes user `winget` para instalar rustup usando el siguiente comando en PowerShell: + +```powershell +winget install --id Rustlang.Rustup +``` + +:::caution[MSVC toolchain como predeterminado] + +Para un soporte total para Tauri y herramientas como [`trunk`](https://trunkrs.dev/) asegurate de que la toolchain MSVC de Rust sea el `default host triple` en el diálogo del instalador. Dependiendo de tu sistema, debería ser `x86_64-pc-windows-msvc`, `i686-pc-windows-msvc`, o `aarch64-pc-windows-msvc`. + +Si ya tienes Rust instalado, puedes asegurarte de que esté instalada la toolchain correcta ejecutando el siguiente comando: + +```powershell +rustup default stable-msvc +``` + +::: + -Asegúrate de reiniciar tu Terminal (y en algunos casos tu sistema) para que los cambios surtan efecto. +**Asegúrate de reiniciar tu Terminal (y en algunos casos tu sistema) para que los cambios surtan efecto.** + +Siguiente: [Configurar para Móvil](#configurar-para-móvil) si deseas construir para Android e iOS, o, si te gustaría usar un framework de JavaScript, [instala Node](#nodejs). De lo contrario, [Crea un Proyecto](/es/start/create-project/). -Siguiente: [Configurar para Móvil](#configurar-para-móvil) si deseas construir para Android e iOS. De lo contrario, [Crea un Proyecto](/start/create-project/). +## Node.js + +:::note[Ecosistema de JavaScript] +Solo si tu intención es usar un framework frontend de JavaScript +::: + +1. Visita la [web de Node.js](https://nodejs.org), descarga la version de Soporte a Largo Plazo (LTS) e instálala. + +2. Comprueba si Node se ha instalado correctamente ejecutando: + +```sh +node -v +# v20.10.0 +npm -v +# 10.2.3 +``` + +Es importante reiniciar tu Terminal para asegurarse de que reconoce la nueva instalación. En algunos casos, puede que necesites reiniciar tu ordenador. + +Aunque npm es el gestor de paquetes predeterminado para Node.js, puedes usar otros como por ejemplo pnpm o yarn. Para habilitarlos, ejecuta `corepack enable` en tu Terminal. Este paso es opcional y únicamente necesario si prefieres usar otro gestor de paquetes que no sea npm. + +Next: [Configurar para Móvil](#configurar-para-móvil) o [Crea un proyecto](/es/start/create-project/). ## Configurar para Móvil @@ -207,7 +268,7 @@ Si deseas compilar tu aplicación para Android o iOS, entonces hay algunas depen {/* TODO: Can this be done in the 4th step? */} - + ```sh @@ -238,16 +299,16 @@ export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home" - Android SDK Build-Tools - Android SDK Command-line Tools -4. Establece las variables de entorno `ANDROID_HOME` y `NDK_HOME`. Reemplaza los números de versión para que coincidan con la versión instalada. +4. Establece las variables de entorno `ANDROID_HOME` y `NDK_HOME`. {/* TODO: Does the version number change below? */} - + ```sh export ANDROID_HOME="$HOME/Android/Sdk" -export NDK_HOME="$ANDROID_HOME/ndk/25.0.8775105" +export NDK_HOME="$ANDROID_HOME/ndk/$(ls -1 $ANDROID_HOME/ndk)" ``` @@ -255,19 +316,28 @@ export NDK_HOME="$ANDROID_HOME/ndk/25.0.8775105" ```sh export ANDROID_HOME="$HOME/Library/Android/sdk" -export NDK_HOME="$ANDROID_HOME/ndk/25.0.8775105" +export NDK_HOME="$ANDROID_HOME/ndk/$(ls -1 $ANDROID_HOME/ndk)" ``` -{/* TODO: Do we need a note about this version? */} - ```ps [System.Environment]::SetEnvironmentVariable("ANDROID_HOME", "$env:LocalAppData\Android\Sdk", "User") -[System.Environment]::SetEnvironmentVariable("NDK_HOME", "$env:LocalAppData\Android\Sdk\ndk\25.0.8775105", "User") +$VERSION = Get-ChildItem -Name "$env:LocalAppData\Android\Sdk\ndk" +[System.Environment]::SetEnvironmentVariable("NDK_HOME", "$env:LocalAppData\Android\Sdk\ndk\$VERSION", "User") +``` + +:::tip +PowerShell no detectará las nuevas variables de entorno hasta que reinicies o cierres sesión. +Sin embargo, puedes actualizar la sesión actual: + +```ps +[System.Environment]::GetEnvironmentVariables("User").GetEnumerator() | % { Set-Item -Path "Env:\$($_.key)" -Value $_.value } ``` +::: + @@ -291,7 +361,7 @@ rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-andro -Siguiente: [Configurar para iOS](#ios) o [Crear un proyecto](/start/create-project/). +Siguiente: [Configurar para iOS](#ios) o [Crear un proyecto](/es/start/create-project/). ### iOS @@ -299,14 +369,12 @@ Siguiente: [Configurar para iOS](#ios) o [Crear un proyecto](/start/create-proje El desarrollo de iOS requiere Xcode y solo está disponible en macOS. Asegúrate de haber instalado Xcode y no Xcode Command Line Tools en la [sección de dependencias del sistema de macOS](#macos). ::: -1. Agrega los destinos de compilación de iOS con `rustup` en Terminal: +1. Agrega los destinos de compilación de iOS con `rustup` en la Terminal: ```sh rustup target add aarch64-apple-ios x86_64-apple-ios aarch64-apple-ios-sim ``` -Asegúrate de haber instalado Xcode y no Xcode Command Line Tools en la [sección de dependencias del sistema de macOS](#macos). - 2. Instala [Homebrew](https://brew.sh): ```sh @@ -319,14 +387,14 @@ Asegúrate de haber instalado Xcode y no Xcode Command Line Tools en la [secció brew install cocoapods ``` -Siguiente: [Crear un proyecto](/start/create-project/). +Siguiente: [Crear un proyecto](/es/start/create-project/). ## Solución de Problemas -Si tienes algún problema durante la instalación, asegúrate de revisar la [Guía de Solución de Problemas](/develop/debug/) o comunícate en el [Discord de Tauri](https://discord.com/invite/tauri). +Si tienes algún problema durante la instalación, asegúrate de revisar la [Guía de Solución de Problemas](/es/develop/debug/) o comunícate en el [Discord de Tauri](https://discord.com/invite/tauri). -¡Ahora que has instalado todos los prerequisitos estás listo para [crear tu primer proyecto Tauri](/start/create-project/)! +¡Ahora que has instalado todos los prerequisitos estás listo para [crear tu primer proyecto Tauri](/es/start/create-project/)! diff --git a/src/content/docs/fr/develop/development-cycle.mdx b/src/content/docs/fr/develop/development-cycle.mdx deleted file mode 100644 index 894a4cd913..0000000000 --- a/src/content/docs/fr/develop/development-cycle.mdx +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Development Cycle ---- - -import CommandTabs from '@components/CommandTabs.astro'; - -### 1. Démarrez votre serveur de développement - -Maintenant que tout est configuré, vous devez démarrer votre serveur de développement d'applications fourni par votre framework ou bundler d'interface utilisateur (en supposant que vous en utilisiez un, bien sûr). - -:::note - -Chaque framework possède ses propres outils de développement. Il n'entre pas dans le cadre de ce document de les couvrir tous ou de rester à jour. - -::: - -### 2. Démarrer la fenêtre de développement de Tauri - - - -La première fois que vous exécutez cette commande, le gestionnaire de packages Rust prend plusieurs minutes pour télécharger et créer tous les packages requis. Comme ils sont mis en cache, les builds suivants sont beaucoup plus rapides, car seul votre code a besoin d'être reconstruit. - -Une fois que Rust a terminé la construction, la vue Web s'ouvre et affiche votre application Web. Vous pouvez apporter des modifications à votre application Web, et si vos outils le permettent, la vue Web devrait se mettre à jour automatiquement, tout comme un navigateur. Lorsque vous apportez des modifications à vos fichiers Rust, ils sont reconstruits automatiquement et votre application redémarre automatiquement. - -:::caution[À propos de Cargo.toml et du contrôle de code source] - -Dans votre référentiel de projet, vous **DEVEZ** valider le `src-tauri/Cargo.lock` avec le `src-tauri/Cargo.toml` sur git car Cargo utilise le fichier de verrouillage pour fournir des versions déterministes. Par conséquent, il est recommandé que toutes les applications enregistrent leur `Cargo.lock`. Vous **NE DEVEZ PAS** valider le dossier `src-tauri/target` ou l'un de ses contenus. - -::: diff --git a/src/content/docs/fr/start/migrate/from-tauri-1.mdx b/src/content/docs/fr/start/migrate/from-tauri-1.mdx index cb1198bf0a..7830622401 100644 --- a/src/content/docs/fr/start/migrate/from-tauri-1.mdx +++ b/src/content/docs/fr/start/migrate/from-tauri-1.mdx @@ -978,8 +978,9 @@ tauri::Builder::default() { let app = tray.app_handle(); if let Some(webview_window) = app.get_webview_window("main") { - let _ = webview_window.show(); - let _ = webview_window.set_focus(); + let _ = webview_window.unminimize(); + let _ = webview_window.show(); + let _ = webview_window.set_focus(); } } }) diff --git a/src/content/docs/fr/start/prerequisites.mdx b/src/content/docs/fr/start/prerequisites.mdx index d423798b87..1e37a541e4 100644 --- a/src/content/docs/fr/start/prerequisites.mdx +++ b/src/content/docs/fr/start/prerequisites.mdx @@ -31,13 +31,13 @@ Tauri exige un système varié de dépendances pour le développement sur Linux. ```sh sudo apt update -sudo apt install libwebkit2gtk-4.0-dev \ +sudo apt install libwebkit2gtk-4.1-dev \ build-essential \ curl \ wget \ file \ + libxdo-dev \ libssl-dev \ - libgtk-3-dev \ libayatana-appindicator3-dev \ librsvg2-dev ``` @@ -48,16 +48,16 @@ sudo apt install libwebkit2gtk-4.0-dev \ ```sh sudo pacman -Syu sudo pacman -S --needed \ - webkit2gtk \ + webkit2gtk-4.1 \ base-devel \ curl \ wget \ file \ openssl \ appmenu-gtk-module \ - gtk3 \ libappindicator-gtk3 \ - librsvg + librsvg \ + xdotool ``` @@ -65,14 +65,15 @@ sudo pacman -S --needed \ ```sh sudo dnf check-update -sudo dnf install webkit2gtk4.0-devel \ +sudo dnf install webkit2gtk4.1-devel \ openssl-devel \ curl \ wget \ file \ libappindicator-gtk3-devel \ - librsvg2-devel -sudo dnf group install "C Development Tools and Libraries" + librsvg2-devel \ + libxdo-devel +sudo dnf group install "c-development" ``` @@ -92,7 +93,7 @@ sudo emerge --ask \ ```sh sudo zypper up -sudo zypper in webkit2gtk3-soup2-devel \ +sudo zypper in webkit2gtk3-devel \ libopenssl-devel \ curl \ wget \ @@ -102,10 +103,27 @@ sudo zypper in webkit2gtk3-soup2-devel \ sudo zypper in -t pattern devel_basis ``` + + + +```sh +sudo apk add \ + build-base \ + webkit2gtk \ + curl \ + wget \ + file \ + openssl \ + libayatana-appindicator-dev \ + librsvg +``` + -TODO: Need to build out NixOS instructions +:::note +Les instructions pour Nix/NixOS peuvent être trouvées dans le [NixOS Wiki](https://wiki.nixos.org/wiki/Tauri). +::: @@ -194,7 +212,30 @@ Visitez https://www.rust-lang.org/tools/install pour installer `rustup`. Assurez-vous de relancer votre terminal (et parfois votre système) pour que les modifications prennent effet. -Suivant: [Configuration pour Mobile](#configuration-pour-mobile) si vous voulez construire une application pour Android et iOS. Dans le cas contraire, [Create a Project](/start/create-project/). +Suivant: [Configuration pour Mobile](#configuration-pour-mobile) si vous voulez construire une application pour Android et iOS, ou, si vous souhaitez utiliser un framework JavaScript, commencez par [installer Node](#nodejs). Dans le cas contraire, [créer votre projet Tauri](/fr/start/create-project/). + +## Node.js + +:::note[JavaScript ecosystem] +Seulement si vous prévoyez d'utiliser un framework JavaScript frontend. +::: + +1. Allez sur le site [Node.js](https://nodejs.org), télécharger la version Long Term Support (LTS) et l'installer. + +2. Vérifiez que Node a été installé avec succès en exécutant: + +```sh +node -v +# v20.10.0 +npm -v +# 10.2.3 +``` + +Il est important de redémarrer votre terminal pour qu'il reconnaisse la nouvelle installation. Dans certains cas, vous devrez redémarrer votre ordinateur. + +Bien que npm soit le gestionnaire de paquets par défaut pour Node.js, vous pouvez aussi en utiliser d'autres comme pnpm ou yarn. Pour les activer, lancez `corepack enable` dans votre Terminal. Cette étape est optionnelle et n'est nécessaire que si vous préférez utiliser un gestionnaire de paquets autre que npm. + +Suivant: [Configuration pour Mobile](#configuration-pour-mobile) ou [créer votre premier projet Tauri](/fr/start/create-project/). ## Configuration pour Mobile @@ -246,14 +287,24 @@ export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home" {/* TODO: Does the version number change below? */} - + + +```sh +export ANDROID_HOME="$HOME/Android/Sdk" +export NDK_HOME="$ANDROID_HOME/ndk/$(ls -1 $ANDROID_HOME/ndk)" +``` + + + + ```sh export ANDROID_HOME="$HOME/Library/Android/sdk" -export NDK_HOME="$ANDROID_HOME/ndk/25.0.8775105" +export NDK_HOME="$ANDROID_HOME/ndk/$(ls -1 $ANDROID_HOME/ndk)" ``` + {/* TODO: Do we need a note about this version? */} @@ -286,30 +337,40 @@ rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-andro -Suivant: [Installation pour Android](#ios) ou [Create a project](/start/create-project/). +Suivant: [Installation pour Android](#ios) ou [créer votre premier projet Tauri](/fr/start/create-project/). ### iOS :::caution[macOS Only] -Le développement iOS exige Xcode et est seulement disponible sur macOS +Le développement iOS exige Xcode et est seulement disponible sur macOS. Assurez-vous d'avoir installé Xcode et non Xcode Command Line Tools dans la section [Dépendances systèmes macOS](#macos). ::: -Ajoutez les "targets" iOS avec `rustup` dans le terminal: +1. Ajoutez les “targets” iOS avec rustup dans le terminal: ```sh rustup target add aarch64-apple-ios x86_64-apple-ios aarch64-apple-ios-sim ``` -Assurez-vous d'avoir installé Xcode et non Xcode Command Line Tools dans la section [Dépendances systèmes macOS](#macos). +2. Installez [Homebrew](https://brew.sh): + +```sh +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" +``` + +3. Installez [Cocoapods](https://cocoapods.org) using Homebrew: + +```sh +brew install cocoapods +``` -Suivant: [Create a project](/start/create-project/). +Suivant: [créer votre projet Tauri](/fr/start/create-project/). ## Problèmes -Si vous rencontrez un problème durant l'installation, assurez-vous de consulter le [guide de résolution de problèmes](/develop/debug/) ou rejoignez le [Discord de Tauri](https://discord.com/invite/tauri) +Si vous rencontrez un problème durant l'installation, assurez-vous de consulter le [guide de résolution de problèmes](/fr/develop/debug/) ou rejoignez le [Discord de Tauri](https://discord.com/invite/tauri) -Maintenant que vous avez installé tous les prérequis, vous êtes fin prêt pour [créer votre premier projet Tauri](/start/create-project/) ! +Maintenant que vous avez installé tous les prérequis, vous êtes fin prêt pour [créer votre premier projet Tauri](/fr/start/create-project/) ! diff --git a/src/content/docs/index.mdx b/src/content/docs/index.mdx index e0e4f97f4b..783b6b149c 100644 --- a/src/content/docs/index.mdx +++ b/src/content/docs/index.mdx @@ -8,31 +8,21 @@ template: splash tableOfContents: false prev: false next: false -hero: - tagline: Create small, fast, secure, cross-platform applications - image: - file: ../../assets/logo-outline.svg - actions: - - text: Get Started - link: /start/ - icon: right-arrow - variant: primary - - text: Tauri 1.0 Documentation - link: https://v1.tauri.app - icon: external - variant: minimal --- import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components'; import Cta from '@fragments/cta.mdx'; +import Hero from '@components/Hero.astro'; +import SponsorList from '@components/sponsors/SponsorList.astro'; +import 'src/styles/home.css'; -
- -
-
-
+ -
+
@@ -46,11 +36,8 @@ import Cta from '@fragments/cta.mdx'; Build your app for Linux, macOS, Windows, Android and iOS - all from a - single codebase. - - - Write your frontend in JavaScript, application logic in Rust, and integrate - deep into the system with Swift and Kotlin. + single codebase. Write your frontend in JavaScript, application logic in + Rust, and integrate deep into the system with Swift and Kotlin. Front-of-mind for the Tauri Team that drives our highest priorities and @@ -60,8 +47,6 @@ import Cta from '@fragments/cta.mdx'; By using the OS's native web renderer, the size of a Tauri app can be little as 600KB. - - With performance and security at the center, Rust is the language for the - next generation of apps. - + + diff --git a/src/content/docs/it/develop/index.mdx b/src/content/docs/it/develop/index.mdx index 5be772ca00..769f8bda07 100644 --- a/src/content/docs/it/develop/index.mdx +++ b/src/content/docs/it/develop/index.mdx @@ -4,11 +4,12 @@ description: Concetti fondamentali per lo sviluppo con Tauri. sidebar: order: 0 label: Panoramica +draft: true --- import CommandTabs from '@components/CommandTabs.astro'; -Ora che hai [tutto configurato](/start/), sei pronto per avviare la tua applicazione con Tauri. +Ora che hai [tutto configurato](/it/start/), sei pronto per avviare la tua applicazione con Tauri. Se stai usando un framework UI o un bundler di JavaScript, probabilmente avrai già accesso a un server locale che velocizza il processo di sviluppo, quindi, se non hai ancora configurato l'URL della tua app @@ -49,7 +50,7 @@ Nota che in questo esempio la cartella `src` deve contenere un file `index.html` Il server di sviluppo incorporato di Tauri non supporta l'autenticazione o la criptazione reciproca. Non dovresti mai usarlo per lo sviluppo su reti non affidabili. -Leggi le [considerazioni sulla sicurezza del server di sviluppo](/security/lifecycle/#development-server) +Leggi le [considerazioni sulla sicurezza del server di sviluppo](/it/security/lifecycle/#development-server) per una spiegazione più dettagliata. ::: diff --git a/src/content/docs/ja/404.md b/src/content/docs/ja/404.md new file mode 100644 index 0000000000..42fbbac994 --- /dev/null +++ b/src/content/docs/ja/404.md @@ -0,0 +1,22 @@ +--- +title: '404' +topic: guides # this sidebar is active when viewing this page +template: doc +editUrl: false +tableOfContents: false +lastUpdated: false +pagefind: false +next: false +prev: false +hero: + title: '404' + tagline: お探しのページは見つかりません。URL を確認するか、検索バーから再検索してください。 +--- + +

+ 検索上で問題がある場合には、GitHub 上でレポートの提出 または Discord での問題報告 を行なって下さい。 +

+ +
+Doc-JP 2.00.00 +
diff --git a/src/content/docs/ja/about/book.md b/src/content/docs/ja/about/book.md new file mode 100644 index 0000000000..4ca703a565 --- /dev/null +++ b/src/content/docs/ja/about/book.md @@ -0,0 +1,40 @@ +--- +title: The Tauri Book +i18nReady: true +--- + +:::note[進捗アプデート(2024/11/12)] + +私たちは『The Tauri Book』の執筆に積極的に取り組んでいます。が、Tauri の格段に大きな成長による遅延に直面してしまい、最近このプロジェクトの優先順位を変更しました。リリースのタイムラインについてはまだ詳細不明ですが、このページから目を離さずに最新情報を確認してください。 + +当初お知らせした公開日より遅れてしまったことをお詫び申し上げます。GitHub Sponsors または Open Collective を通じて寄付をされていて、払い戻しを希望される場合は、Open Collective 経由で行なうことができます: [Open Collective で Tauri に問い合わせる](https://opencollective.com/tauri/contact)。 + +::: + +### Tauri Book の概要 + +『The Tauri Book』では、Tauri の歴史と、私たちが行なった設計上の決定事項について説明します。また、なぜプライバシー・セキュリティ・持続可能性が重要であるのかや、現代のどのソフトウェア・プロジェクトにも適用できる基本的な考察についても詳しく説明します。 + +含まれる内容は次のとおりです: + +- Tauri 設計の裏にある手法とその理由 +- Tauri でプログラムをビルドする場合にできること(オプション) +- 「迅速なリリース」か「持続可能で信頼できること」かのどちらかを選択する必要がないということ +- Tauri のバインディング/アプリケーション層として Rust 言語を選択した理由 +- バイナリ・レビューが重要な理由 + +### Tauri の歴史 + +2020 年、ネイティブ・アプリ(特定プラットフォーム向けアプリ)の作成はこれまで以上に簡単でアクセスしやすくなりました。とはいうものの、セキュリティとプライバシーの様相が急速に変化する中においては、初心者も熟練した開発者も同じように難しい選択に直面しています。このことは、信頼性の低いユーザー・デバイス環境では特にその傾向があります。 + +Tauri では、あれこれ推測する必要がありません。というのも、Rust の言語機能を活用し、自分の好きなフロントエンド・フレームワークを使用してアプリの構築を行なえるようになる「開発の安全性と柔軟な創造性」という新しいパラダイムを取り込むためにゼロから設計されているためです。 +Rust プログラミング言語の知識がなくても、まったく同じコードベースから、記録的な速さで、主要なデスクトップおよびモバイル・プラットフォーム向けの小型で高速、堅牢、かつ安全なネイティブ・アプリケーションをどんなふうに設計、構築、監査、展開できるのかを見つけてください。 + +著者であり Tauri の共同設立者でもある Daniel と Lucas が、皆さまを理論から実行までの旅にお連れします。その中で、Tauri が作られた理由と、その内部でどのように動作しているのかを学びます。 +また、この本では、オープンソース、DevOps(開発と運用)、セキュリティ、エンタープライズ・アーキテクチャを専門とするその分野の方々の洞察とともに、会話形式の哲学的議論とオープンソースの持続可能性の観点も紹介します。そこから、あなたの作成する次世代のアプリは便宜を受け、あなたのユーザーもその恩恵にあずかることでしょう。 + +> > > 《訳注》 **DevOps** ソフトウェア開発で「開発(Development)」と「運用(Operations)」を連携して行なう手法。詳しくは Wikioedia の「[DevOps](https://ja.wikipedia.org/wiki/DevOps)」の項を参照してください。 + +
+ 【※ この日本語版は、「Nov 12, 2024 英語版」に基づいています】 +
diff --git a/src/content/docs/ja/about/governance.md b/src/content/docs/ja/about/governance.md new file mode 100644 index 0000000000..8e2cb610de --- /dev/null +++ b/src/content/docs/ja/about/governance.md @@ -0,0 +1,58 @@ +--- +title: Tauri の管理体制(ガバナンス) +i18nReady: true +--- + +Tauri の組織構造の主目標の一つは、貢献者の健康と幸せを尊重しながら、オープンソースの価値に忠実であり続け、その持続的な実行を保証することです。[コモンズ・コンサーヴァンシー/タウリ・プログラム](https://dracc.commonsconservancy.org/0035/) は、Tauri とその付帯的な所産の将来の開発を通して、こうした価値観にコミットし、オープンで透明性があり効率的な組織のガバナンス・プロセス(管理統治)を促進するために設立されました。 + +> > > 《訳注》 **コモンズ・コンサーヴァンシー** The Commons Conservancy 日本語の定訳はない模様。「Commons(共有財産)」を「Conservancy(保護管理する団体)」の意味。オープンソース・プロジェクトの実際の開発作業ではなく、プロジェクト運営の法人格組織を設立する目的の下に設置されています。 + +## Tauri Working Group(作業部会) + +「Tauri ワーキング・グループ」は、このガバナンス・プロセスを実現するために作られた集合的な組織で、次の構成員で成り立っています: + +- ワーキング・グループのメンバー +- Tauri 理事会および理事 +- Tauri 各ドメインの担当責任者 +- Tauri 各ドメイン・チーム + +![Tauri governance diagram](@assets/about/governance/diagram.svg) + +### ワーキング・グループのメンバー + +「Tauri ワーキング・グループ」を構成するすべての個人のことです。 + +### Tauri 理事会および理事 + +「Tauri 理事会」は、「Tauri 開発活動プログラム」の中心的な意思決定機関であり、その全体的な健全性と安定性に責任を負っています。理事会は、「Tauri 開発活動プログラム」の主要な決定事項やワーキング・グループによって提起された問題について採決を行ないます。 + +> > > 《訳注》 **Tauri 開発活動プログラム** 原文は「The Tauri Programme」。そのまま「Tauri プログラム」と表記すると、個々のアプリ・プログラムと区別しづらいため、開発活動を司る「開発母体」あるいは「開発組織」を「開発活動プログラム」と表現してあります。 + +個々の理事とは、技術的な貢献者であったり、Tauri の将来的な利害関係者であったり、業界での経験を共有したり、オープンソース内の規制や法的側面に情熱を持っている人々、のような方々です。 + +### 各ドメインの担当責任者(Domains & Domain Leads) + +「ドメイン Domains」とは、Tauri 内の特定の関心領域を代表する組織単位です。 + +「ドメイン・リード Domain Leads」(担当責任者)とは、自分が率いるドメインに関する専門知識を持つ、Tauri コミュニティ内の信頼される貢献者です。そのドメイン内の活動の方向性を定め、監督し、サポートする責任を負っています。 + +現在の各「ドメイン」とその「ドメイン・リード」については、GitHub の[Governance and Guidance Repository](https://github.com/tauri-apps/governance-and-guidance) に概要が記載されています。 + +### ドメイン・チーム + +「チーム Teams」とは、「Tauri 開発活動プログラム」の特定の領域(ドメイン)をサポートまたは維持する小人数の貢献者のグループです。このようなチームは、とりわけその時々の短期的な貢献では同じ結果を達成できない場合などに、Tauri が用いる長期的な課題と目標を達成するための手段です。 + +## Tauri に参画する + +もしあなたが、「Tauri の理事」または「ドメイン・リード」になりたい場合は、これらの役職の選挙は年間を通じて行なわれます。「ドメイン・リード」の選挙は春と秋に行なわれ、「理事」の選挙は夏に行なわれます。応募方法の説明は、それぞれの選挙の前に [Tauri ブログ](https://tauri.app/blog/) (英語版)に掲載されます。 + +## 追加情報 + +- [Governance and Guidance Repository](https://github.com/tauri-apps/governance-and-guidance)(英語版): Tauriのガバナンスと現在のドメインおよびドメイン・リードに関する詳細情報 +- [社会契約 Social Contract](https://github.com/tauri-apps/governance-and-guidance/blob/main/SOCIAL_CONTRACT.md)(英語版): 「社会契約」(道徳倫理規範)は Tauri 意思決定と組織の在り方を示しています +- [行動規範 Code of Conduct](https://github.com/tauri-apps/governance-and-guidance/blob/main/CODE_OF_CONDUCT.md)(英語版) +- [「Tauri 開発活動プログラム」規約 Tauri Programme Statutes](https://dracc.commonsconservancy.org/0035/)(英語版) + +
+ 【※ この日本語版は、「Nov 12, 2024 英語版」に基づいています】 +
diff --git a/src/content/docs/ja/about/index.mdx b/src/content/docs/ja/about/index.mdx new file mode 100644 index 0000000000..67e2430aba --- /dev/null +++ b/src/content/docs/ja/about/index.mdx @@ -0,0 +1,34 @@ +--- +title: Tauri について +i18nReady: true +--- + +:::tip[(ヒント)] + +もし、素早く読める技術の概要を求めていたり、アプリの作成を始めたいと思っている場合には、 [Tauri とは?](/ja/start/) のページをご覧ください。Tauri プロジェクトの理念について詳しく知りたい場合には、このまま読み進めてください。 + +::: + +import { LinkCard, CardGrid } from '@astrojs/starlight/components'; + + + + + + + +
+ 【※ この日本語版は、「Nov 12, 2024 英語版」に基づいています】 +
diff --git a/src/content/docs/ja/about/philosophy.md b/src/content/docs/ja/about/philosophy.md new file mode 100644 index 0000000000..5fb80fd866 --- /dev/null +++ b/src/content/docs/ja/about/philosophy.md @@ -0,0 +1,57 @@ +--- +title: Tauri の理念 +i18nReady: true +--- + +Tauri は、既存の実質的にどのフロントエンド・フレームワークを使用してでも、開発者が主要なデスクトップ・プラットフォーム向けのアプリケーションを作成するのに役立つツールキットです。「コア」部は Rust で書かれ、CLI 部は Node.js を活用しているため、Tauri は優れたアプリの作成と保守を行なうための真に多言語的なアプローチ手法になっています。 + + + +## 安心第一(セキュリティ・ファースト) + +今日の世界では、すべての「素朴な脅威モデル」は、ユーザーのデバイスがすでにセキュリティ侵害を受けていると想定しています。そのため、アプリ開発者は厄介な状況に陥ります。なぜなら、デバイスがすでに危険にさらされている場合、どうすればソフトウェアは信頼できるのでしょうか。 + +> > > 《訳注》 **素朴な脅威モデル** 原文は「**honest** threat model」。honest 部分の定訳が不明であるため「素朴な、飾りのない」の意と解釈しています。なお、下記の「[本物のオープンソース](#本物のオープンソース)の原文も「**honest** open source」であるが、この honest は「本物の、純正の」の意としてあります。 + +「多重防御 Defence in depth」が Tauri の採ったアプローチです。攻撃者に曝される表層部分を最小限に抑えるために、あなたがあらゆる予防策を講じられるようにしたいと考えました。Tauri を使用すれば、配布する API エンドポイントを選択したり、アプリにローカルホスト・サーバーを組み込むかどうかを選択したり、実行時の機能ハンドルをランダム化したりすることができます。こうした技術やその他の技術により、あなたやあなたのアプリ・ユーザーの防御力を強化する安全なベースラインが形成されます。 + +「静的攻撃 Static attacks」を極めて困難にし、システムを互いに分離することで攻撃者の侵攻を遅らせることが、最も重要です。もしも、別のフレームワークである Electron エコシステムから移行してきた場合でも、ご安心ください、デフォルトでは Tauri はバイナリのみを公開し、 ASAR ファイルは公開しません。 + +> > > 《訳注》 **ASAR** Atom Shell Archive Formatの略。[Electron](https://www.electronjs.org/ja/docs/latest/tutorial/asar-archives) で用いられている、複数のファイルを1つにまとめるためのシンプルなアーカイブ形式。アプリケーションの頒布形式を作成した後、アプリのソースコードが ASAR アーカイブにバンドルされます。 + +セキュリティという判断基準から Tauri でビルドすることを選択することにより、先を見通したセキュリティ重視の姿勢を取るさまざまな機会があなたに訪れるでしょう。 + +## 多言語対応(サイロ化ではなく) + +現代のフレームワークのほとんどは単一の言語体系を使用しており、それゆえ、狭い知識と慣用句の泡の中に閉じ込められています。これは特定のニッチなアプリケーションではうまく機能しますが、ある種の部族主義(サイロ化)も助長します。 + +この状況は、React、Angular、Vue の各々の開発コミュニティがそれぞれの問題に身を寄せ合い、最終的には異種交配がほとんど生まれていないということからもわかります。 + +同じ状況は、Rust 対 Node 対 C++ の戦場でも見られます。そこでは、強硬派が独自の立場を取り、コミュニティ間での連携を拒否しています。 + +現在、Tauri はバックエンドに Rust を使用していますが、そう遠くない将来、Go、Nim、Python、C# などの他のバックエンドも可能になるでしょう。なぜならば、Tauri は [webview](https://github.com/webview) 機関への公式 Rust バインディングを保守していますが、皆様の必要に応じてバックエンドを切り替えられるようにする予定だからです。Tauri の API は「C 相互運用性」を備えた任意の言語で実装できるため、完全な多言語化への実現には、あとは「PR(プル・リクエスト)」をひとつ出すだけです。 + +## 本物のオープンソース + +コミュニティがなければ、オープンソースのどれも意味をなさないでしょう。今日のソフトウェア・コミュニティは、驚くべき場所です。そこでは、人々が互いに助け合い、素晴らしいものを作ります。オープンソースはそうした動きの非常に大きな部分を担っています。 + +オープンソースの意味は人によって異なりますが、ほとんどの人はオープンソースが自由を後押しするのに役立っていることに同意するでしょう。ソフトウェアがあなたの権利を尊重しない場合、倫理に反する動作により、それは不公平に思え、潜在的にはあなたの自由を侵害している可能性があります。 + +このため、FLOSS 支持者が「正真正銘の」オープンソースである Tauri を使用したアプリケーションを作成し、FSF(フリーソフトウェア財団)が承認した GNU/Linux ディストリビューションに含められることを私たちは誇りに思っています。 + +> > > 《訳注》 **FLOSS**(free/libre open-source software) オープンソースの自由ソフトウェア。 + +## Tauri の将来 + +Tauri の将来は、皆さんの関与と貢献にかかっています。実際に Tauri を試したり、問題を報告したり、ワーキング・グループ(各作業部会)に参加したり、寄付をしてみてください。どのような貢献も不可欠です。とにかく、ぜひ、まずはご連絡ください。 + +
+ 【※ この日本語版は、「Nov 12, 2024 英語版」に基づいています】 +
diff --git a/src/content/docs/ja/about/trademark.md b/src/content/docs/ja/about/trademark.md new file mode 100644 index 0000000000..8762ac79f2 --- /dev/null +++ b/src/content/docs/ja/about/trademark.md @@ -0,0 +1,139 @@ +--- +title: 商標ガイドライン +i18nReady: true +--- + +:::[warning【ご注意】] +《訳注》 この日本語訳は「参考訳」であり、正確な法令解釈ではありません。商標に関する取り扱いは「英語版」の記載に則って行なってください。 +::: + +この方針文書「商標ガイドライン」は、「The Tauri Programme within the Commons Conservancy」 が所有する「TAURI 商標」、「サービス・マーク」、および「ロゴ」の使用方法を理解していただくために作成されています。 + +> 《訳注》 **The Tauri Programme within the Commons Conservancy** Tauri 開発チームの公式名称。「コモンズ・コンサーヴァンシー内の Tauri プログラム」(共有財産保護管理団体サイト内に登録されている Tauri プログラム、の意)。法令関連内容を示す本稿では、原文表記とします。「コモンズ・コンサーヴァンシー」については、[Tauri の管理体制(ガバナンス)](/ja/about/governance/) を参照してください。 + +Tauri のソフトウェアは自由/無償のオープンソース・ソフトウェア・ライセンスに基づいて提供されていますが、その著作権ライセンスには Tauri の商標を使用するライセンスは含まれていません。この方針文書は、「背景法」および「コミュニティの期待」に基づいて Tauri の商標を使用する方法を説明することを目的としています。 + +**この「方針文書」が扱う範囲は:** + +- Tauri の「文字商標」と「サービス/マーク」: TAURI、TAO、WRY +- Tauri の「ロゴ」: The TAURI、TAO、WRY の各ロゴ(ならびに、すべての視覚的な派生物) + +> 《訳注》 **文字商標** 原文は「word trademarks」。企業名や製品名の文字だけを使って作成された商標。「ワード・マーク word mark」。 + +この方針文書は、登録されているか否かに関係なく、すべての「商標」と「サービス・マーク」に適用されます。 + +## 一般的なガイドライン + +Tauri の商標のいずれかを使用する場合は、受け手側が「誰から何を」受け取っているのかに関して、常にだれにも誤解を抱かせないような形で行なわなければなりません。たとえば、TAURI ソフトウェアの改変版(フォークとも呼ばれます)を配布する場合には、「TAURI ソフトウェアを配布している」と言うことはできません。受け手側が、改変版と Tauri 公式版との相違を理解できない可能性があるからです。 + +また、あなたのウェブサイトが Tauri の公式ウェブサイトであるかのような、あるいは Tauri があなたのウェブサイトを公認しているかのような誤解を与える形で、あなたのウェブサイト上に Tauri のロゴを使用することはできません。 + +ただし、TAURI ソフトウェアが好きだとか、TAURI コミュニティに参加している、TAURI ソフトウェアの改変されていないそのままのバージョンを提供している、などと言うことは可能です。 + +Tauri の商標またはそのバリエーションを、あなた自身の商標、サービス・マーク、ドメイン名、会社名、商号、製品名、またはサービス名の一部として使用または登録することはできません。 + +商標法では、Tauri の商標と酷似した名称や商標の使用を認めていません。したがって、Tauri の商標類や発音表記の明らかな「変形」、「外国語の同義語」、「模写」、または類似する/互換性のある製品やサービスの「略語」、を使用することはできません。Tauri では、以下のような事例を Tauri の商標類に極めて類似しているとみなします: + +- TAURIMAGE +- Tauri Wallet App + +## 許容される使用例 + +### アプリケーション + +TAURI は、コンピュータ機器用のアプリケーションを作成するためのフレームワークです。あなたのアプリケーションが TAURI を使用していることを謳うことはできますが、そのアプリケーションが「the Tauri Programme within the Commons Conservancy」によって認定されているとか公式アプリケーションであるという印象を与えないように注意する必要があります。また、そのアプリケーションに Tauri のアイコンを付けて*公開しない*ように注意してください。 + +### プラグインとテンプレート + +適切な命名規則を使用してプラグインやテンプレートのコードを公開することはできますが、そうした著作物は「正式に承認されたものではない」ことを明記してください。GitHub 組織内の `tauri-apps` によって管理されているコードベースのみが公式版と見なされます。 + +## Tauri Core の改変版(フォーク) + +Tauri ソフトウェア(TAURI CORE)の改変版を配布する場合は、Tauri のロゴと名前をすべて削除する必要があります。しかし、オリジナルのライセンスを SPDX 形式で残さなければなりません。あなたが提供しようとしているソフトウェアの出所を誠実に記述するために、Tauri の「ワード・マーク」は使用できますが、Tauri の「ロゴ」は使用できません。たとえば、配布するコードが Tauri ソフトウェアの改変版である場合、「このソフトウェアは、TAURI ソフトウェアのソースコードから派生したものです」と記載できます。 + +> 《訳注》 **SPDX 形式** [Software Package Data Exchange](https://ja.wikipedia.org/wiki/Software_Package_Data_Exchange)「ソフトウェア・パッケージ・データ交換」の略。 + +### Tauri との互換性に関する告知について + +あなたのソフトウェアと Tauri ソフトウェアの関係を誠実に表現するために、「ワード・マーク」は使用できますが、「ロゴ」は使用できません。それ以外の使用方法は、Tauri があなたのソフトウェアを認定または承認したと受け取られる可能性があります。もし、Tauri のロゴを使用したいとお考えの場合は、ライセンス条件についてご相談ください。 + +### 互換性のある製品の命名について + +TAURI ソフトウェアに関連付けて、あなたの製品を説明したいとお考えの場合、その条件は次のとおりです。以下の条件を満たす場合に限り、あなたのソフトウェアを「TAURI の XYZ」(XYZ はあなたの製品名)と呼ぶことができます: + +- あなたの製品とともに公開される TAURI ソフトウェアのすべてのバージョンは、Tauri によって提供するバイナリそのもの、もしくは Tauri が提供するコア・ソフトウェアとツールによって作成されたものであること。 +- あなたの製品が TAURI ソフトウェアの API と完全に互換性があること。 +- マーケティング資料や製品説明に次の一文を記載すること:「TAURI is a trademark of The Tauri Programme within the Commons Conservancy. https://tauri.app/ 」(TAURI は、the Tauri Programme within the Commons Conservancy の商標です。https://tauri.app/)。 + +### ユーザー・グループでの商標利用について + +以下の条件を満たす場合、「ユーザー・グループ名」の一部として「ワード・マーク」を使用できます: + +- 当該グループの活動の中心が「Tauri ソフトウェア」であること。 +- 当該グループが営利活動を行なっていないこと。 +- 参加費用が、会場費・飲食費のみであること。 + +Tauri の商標を使用して会議を開催することは許可されていません。 + +### ドメイン名での商標使用禁止 + +Tauri の「ワード・マーク」またはその変形や組み合わせを含むドメイン名を登録することはできません。 + +### その他の TAURI 商標の営利目的使用について + +ビデオ、チュートリアル・シリーズ、書籍、その他の教育資料を作成し、サブスクリプション、販売、広告などを通じて報酬を受け取る場合は、「the Tauri Programme within the Commons Conservancy」から明示的なライセンス許可を取得する必要があります。 + +## Tauri 商標の表示方法 + +Tauri の商標類を使用する権利をお持ちの場合は、次の方法で表示してください。 + +### 商標マークと説明文について + +ウェブページ、文書、または資料の最初または最も目立つ箇所に商標マークが表示されている場合は、その商標が「登録商標(“®”)」であるか「未登録商標(“™”)」であるかを示す記号を付記する必要があります。どちらに該当するかが不明な場合は、Tauri までお問い合わせください。(「TAURI」自体は登録商標です。) + +商標マークを使用したページの下部に次の注意書きを記載してください。「TAURI is trademark of [The Tauri Programme within the Commons Conservancy]」(TAURI は「コモンズ・コンサーヴァンシーの Tauri 開発活動プログラム」の商標です、の意)。 + +### 文中の商標の使用について + +商標は常に「そのままの形」「正確な綴り」で使用し、省略したり、ハイフンでつないだり、他の単語と組み合わせたりしてはいけません。 + +- 不適切な例: TAUREE 《※ 綴りが異なります。》 +- 適切な例: TAURI + +商標を「複数形にしない」でください。 + +- 不適切な例: I have seventeen **TAURIs** running on my computer.(コンピューター上で 17 の TAURI を実行しています。) 《※ 複数形表記》 +- 適切な例: I am running seventeen **TAURI** applications on my computer and have ram to spare.(コンピューター上で 17 の TAURI アプリケーションを実行しており、RAM に余裕があります。) + +商標は常に名詞を修飾する「形容詞として」使用してください。 + +- Unacceptable: This is a TAURI. +- Acceptable: This is a TAURI software application. +- 不適切な例: This is a **TAURI**.(これは TAURI です。) 《※ 名詞として使用》 +- 適切な例: This is a **TAURI** software application.(これは TAURI のソフトウェア・アプリケーションです。 + +### ロゴの使用について + +ロゴは、拡大/縮小表示を除いて、いかなる変更もしてはいけません。つまり、装飾的な要素の追加、色や比率の変更、変形、別要素の追加、他のロゴとの組み合わせなどを行なうことはできません。 + +Tauri ではロゴの「高コントラスト」版も用意されていおり、次の「アセット」セクションからダウンロードできます。 + +## アセット + +- [ブランド・ガイドライン](/assets/brand_guidelines.pdf): このリンク(英語版)からは、商標に関する全資料をダウンロードできます - (PDF、74.3 MB) +- [ロゴ・パック](/assets/logopack.zip): こちらのリンクからは、「ロゴ」と「ワード・マーク」の SVG 形式と PNG 形式のデータがダウンロードできます - (ZIP、203 KB) + +--- + +「The Tauri Programme within the Commons Conservancy」 Conservancy 内の Tauri プログラムは、これらの商標ガイドラインをいつでも変更する権利を保持します。ご質問やお問い合わせがある場合は、`trademark@tauri.app` までメールをお送りください。 + +上記のガイドラインは、http://www.modeltrademarkguidelines.org で入手可能な「モデル商標ガイドライン」に基づいており、「クリエイティブ・コモンズ・アトリビューション 3.0 非移植ライセンス 1.0版 2022/08/20付」 (https://creativecommons.org/licenses/by/3.0/deed.en_EU) に基づいて使用されています。 + +> 《訳注》 原文表記は以下のとおり: +> +> - **モデル商標ガイドライン** [the Model Trademark Guidelines](http://www.modeltrademarkguidelines.org) +> - **クリエイティブ・コモンズ・アトリビューション 3.0 非移植ライセンス** [a Creative Commons Attribution 3.0 Unported license](https://creativecommons.org/licenses/by/3.0/deed.en_EU) + +
+ 【※ この日本語版は、「Nov 12, 2024 英語版」に基づいています】 +
diff --git a/src/content/docs/ja/concept/Inter-Process Communication/brownfield.md b/src/content/docs/ja/concept/Inter-Process Communication/brownfield.md new file mode 100644 index 0000000000..c83dc1a1c8 --- /dev/null +++ b/src/content/docs/ja/concept/Inter-Process Communication/brownfield.md @@ -0,0 +1,36 @@ +--- +title: ブラウンフィールド型(Brownfield Pattern) +i18nReady: true +--- + +_**デフォルトの IPC パターンです**_ + +このパターンは、Tauri を使用する上で最も明快で分かりやすいものです。というのも、既存のフロントエンド・プロジェクトと可能な限り互換性を持たせようとしているからです。手短に言えば、既存の Web フロントエンドがブラウザー内で使用するもの以外には、他に何も必要としないようになっているということです。 +ただ、これは既存のブラウザー・アプリケーションで動作する _**すべて**_ が、そのまま動作するというわけではありません。 + +一般的な「ブラウンフィールド」型のソフトウェア開発について馴染みがない場合は、Wikipedia の記事 [Brownfield Wikipedia article](日本語版なし)に判りやすい概説があります。 +Tauri の場合、(ブラウンフィールド型開発の対象となる)既存のソフトウェアとは、レガシー・システムではなく、現行ブラウザーのサポートと動作です。 + +## 設定 + +ブラウンフィールド型開発はデフォルトのパターンなので、設定オプションを指定する必要はありません。 +明示的に設定するには、`tauri.conf.json` 構成ファイル内の `tauri > pattern` オブジェクトを使用します。 + +```json +{ + "tauri": { + "pattern": { + "use": "brownfield" + } + } +} +``` + +_**ブラウンフィールド型では追加の設定オプションはありません。**_ + +[brownfield wikipedia article]: https://en.wikipedia.org/wiki/Brownfield_(software_development) + +
+【※ この日本語版は、「Feb 22, 2025 英語版」に基づいています】
+Doc-JP 2.00.00 +
diff --git a/src/content/docs/ja/concept/Inter-Process Communication/index.mdx b/src/content/docs/ja/concept/Inter-Process Communication/index.mdx new file mode 100644 index 0000000000..8e30717cd8 --- /dev/null +++ b/src/content/docs/ja/concept/Inter-Process Communication/index.mdx @@ -0,0 +1,100 @@ +--- +title: プロセス間通信 +sidebar: + label: Overview + order: 1 +i18nReady: true +--- + +import { CardGrid, LinkCard } from '@astrojs/starlight/components'; + +「プロセス間通信 Inter-Process Communication」(IPC)は、単独のプロセスが安全に通信することを可能にし、より複雑なアプリケーションを構築するための鍵となります。 + +具体的な「プロセス間通信(IPC)」の型(パターン)については、次の説明内容を参照してください: + + + + + + +Tauri は、[Asynchronous Message Passing](非同期メッセージ・パッシング、[日本語版リンク]())と呼ばれる特別なスタイルのプロセス間通信を使用します。この方法では、プロセス同士が単純なデータ表現を使用してシリアル化された「_リクエスト_(要求)」と「_レスポンス_(応答)」をやり取りします。メッセージ・パッシングは、インターネット上のクライアント・サーバー通信に使用される仕組みであるため、Web 開発の経験がある人なら誰でも馴染みがあるはずです。 + +また、メッセージ・パッシングは受信者が必要に応じて「リクエスト」を拒否または破棄できるため、「共有メモリ方式」や「直接関数アクセス方式」よりも安全な手法です。たとえば、Tauri コア・プロセスが「リクエスト」を悪意のあるものと判断した場合、そのリクエストは破棄され、対応する関数処理は実行されません。 + +以下では、Tauri の二つの「IPC プリミティブ(同期基本命令)」、すなわち「イベント `Events` 」と「コマンド `Commands` 」について詳しく説明します。 + +## イベント + +「イベント」は、自動追尾型・一方向性の「IPC メッセージ」で、ライフサイクル中の各イベントと状態の変化を伝達するのに最適です。 +「[コマンド](#コマンド)」とは異なり、「イベント」はフロントエンドと Tauri Core(コア部)の両方から発行できます。 + +
+ +```d2 sketch pad=50 +shape: sequence_diagram + +Frontend: { + shape: rectangle + label: "Webview\nFrontend" +} +Core: { + shape: rectangle + label: "Core\nBackend" +} + +Frontend -> Core: "イベント"{style.animated: true} +Core -> Frontend: "イベント"{style.animated: true} +``` + +
コア部と Webview 間でやり取りされるイベント
+
+ +## コマンド + +Tauri は、また、「IPC メッセージ」に加えて、[foreign function interface](外部関数インターフェース、[日本語版リンク](https://ja.wikipedia.org/wiki/Foreign_function_interface))のような抽象化も提供します[^1]。基本主要 API である `invoke` は、ブラウザの `fetch` API に似ており、フロントエンドが Rust 関数を呼び出し、引数を渡して、データを受信できるようにします。 + +このメカニズムは、内部で [JSON-RPC] のようなプロトコルを使用してリクエストとレスポンスをシリアル化するので、すべての引数と戻り値データは JSON の規格に従ってシリアル化可能である必要があります。 + +
+ +```d2 sketch pad=50 +shape: sequence_diagram + + +Frontend: { + label: "Webview\nFrontend" +} + +Core: { + label: "Core\nBackend" +} +InvokeHandler: { + label: "Invoke\nHandler" +} + +Frontend -> Core: "IPC リクエスト"{style.animated: true} +Core -> InvokeHandler: "コマンド 呼び出し"{style.animated: true} +InvokeHandler -> Core: "戻り値 シリアル化"{style.animated: true} +Core -> Frontend: "レスポンス"{style.animated: true} +``` + +
コマンド呼び出しに関与する IPC メッセージ
+
+ +[^1]: コマンドは、内部ではメッセージ・パッシングを使用しているため、実際の「外部関数インターフェース(FFI)」と同じようなセキュリティ上の落とし穴はありません。 + +[Asynchronous Message Passing]: https://en.wikipedia.org/wiki/Message_passing#Asynchronous_message_passing +[json-rpc]: https://www.jsonrpc.org +[foreign function interface]: https://en.wikipedia.org/wiki/Foreign_function_interface + +
+ 【※ この日本語版は、「Feb 22, 2025 英語版」に基づいています】 +
+ Doc-JP 2.00.00 +
diff --git a/src/content/docs/ja/concept/Inter-Process Communication/isolation.md b/src/content/docs/ja/concept/Inter-Process Communication/isolation.md new file mode 100644 index 0000000000..42a94d9862 --- /dev/null +++ b/src/content/docs/ja/concept/Inter-Process Communication/isolation.md @@ -0,0 +1,121 @@ +--- +title: アイソレーション型(Isolation Pattern) +i18nReady: true +--- + +アイソレーション(分離・隔絶)型は、フロントエンドから送信された Tauri API メッセージが Tauri コア部に到達する前に、JavaScript を使用して傍受・変更する方法です。アイソレーション型で挿入される安全な JavaScript コードは、アイソレーション型アプリケーションと呼ばれます。 + +## アイソレーション型の必要性 + +アイソレーション型の目的は、Tauri コア部への望ましくないあるいは悪意のあるフロントエンドからの呼び出しから、アプリケーションを保護するための仕組みを開発者に提供することです。アイソレーション型が必要となったのは、フロントエンドで実行される信頼できないコンテンツから生じる脅威に対応するために生まれました。このような脅威は多くの依存関係を持つアプリケーションによくあるケースです。アプリケーションが遭遇する可能性のある多くの脅威源のリストについては、[セキュリティ:脅威モデル] を参照してください。 + +上記の最大の脅威モデルは「開発時の脅威」でしたが、このような脅威は、アイソレーション型を設計する際に念頭に置かれていたものです。多くのフロントエンドのビルド・ツールが、しばしば深くネスト化された数十(もしくは数百)の依存関係で成り立っているだけではなく、複雑なアプリケーション側にも、数多くの(こちらもしばしば深くネスト化された)依存関係があり得るので、最終出力版にバンドルされるのです。 + +## アイソレーション型を使用する局面 + +Tauri は、アイソレーション型が使用できる場合には常に使用することを強く推奨しています。アイソレーション型のアプリケーションではフロントエンドからの _**すべての**_ メッセージを「捕捉」(インターセプト)するため、アイソレーション型が _常に_ 使用されます。 + +さらに Tauri では、外部の Tauri API を使用するときは常に、アプリケーションを「封鎖」(ロックダウン)することを強く推奨しています。アプリの開発者は、安全なアイソレーション型アプリケーションを利用して IPC 入力を検証し、その入力内容が確実に想定されるパラメータの範囲内にあることを確かめます。事例としては、ファイルの読み取りまたは書き込みの呼び出しが、そのアプリケーションの想定外の場所へのパスにアクセスしようとしていないかを確認したり、あるいは、Tauri API の「HTTP フェッチコール」が 「Origin ヘッダー」にそのアプリケーションが想定しているもののみを設定しているかを確認したりすることです。 + +とはいえ、フロントエンドからの _**すべての**_ メッセージを捕捉するため、常時動作 API、たとえば [Events] など、でも動作します。一部のイベントでは、アプリ独自の Rust コードにアクションを実行させる可能性があるので、それにも同様の検証手法で対応することができます。 + +## アイソレーション型の適用 + +アイソレーション型で重要なのは、フロントエンドと Tauri Core(タウリ・コア部)との間に安全なアプリケーションを挿入して、IPC 受信メッセージを捕捉し修正することです。これには、` + +## 보안 우선 + +오늘날의 세계에서 모든 "정직한 위협 모델"은 사용자의 장치가 이미 보안 침해를 당했다고 가정합니다. 이로 인해 앱 개발자는 어려운 상황에 처하게 됩니다. 장치가 이미 위험에 처한 경우 소프트웨어를 어떻게 신뢰할 수 있습니까? + +> > > 《번역 주》 **정직한 위협 모델** 원문은 "**honest** threat model". honest 부분의 정해진 번역이 불분명하여 "정직한, 꾸밈없는"의 의미로 해석했습니다. 아래의 "[진정한 오픈 소스](#진정한-오픈-소스)"의 원문도 "**honest** open source"이지만, 이 honest는 "진정한, 순수한"의 의미로 사용되었습니다. + +"심층 방어(Defence in depth)"가 Tauri가 취한 접근 방식입니다. 공격자에게 노출되는 표면을 최소화하기 위해 모든 예방 조치를 취할 수 있도록 하고 싶었습니다. Tauri를 사용하면 배포할 API 엔드포인트를 선택하고, 앱에 로컬 호스트 서버를 포함할지 여부를 선택하고, 런타임 기능 핸들을 무작위화할 수 있습니다. 이러한 기술과 기타 기술은 귀하와 귀하의 앱 사용자의 방어력을 강화하는 안전한 기준선을 형성합니다. + +"정적 공격(Static attacks)"을 매우 어렵게 만들고 시스템을 서로 분리하여 공격자의 침입을 지연시키는 것이 가장 중요합니다. 다른 프레임워크인 Electron 생태계에서 마이그레이션한 경우에도 안심하십시오. 기본적으로 Tauri는 바이너리만 게시하고 ASAR 파일은 게시하지 않습니다. + +> > > 《번역 주》 **ASAR** Atom Shell Archive Format의 약자. [Electron](https://www.electronjs.org/ko/docs/latest/tutorial/asar-archives)에서 사용되는 여러 파일을 하나로 묶기 위한 간단한 아카이브 형식입니다. 애플리케이션 배포 형식을 만든 후 앱의 소스 코드가 ASAR 아카이브에 번들로 제공됩니다. + +보안이라는 판단 기준에서 Tauri로 빌드하기로 선택함으로써 미래를 내다보는 보안 중심의 자세를 취할 수 있는 다양한 기회가 생길 것입니다. + +## 다국어 지원(사일로가 아닌) + +현대의 대부분의 프레임워크는 단일 언어 체계를 사용하므로 좁은 지식과 관용구의 거품 속에 갇혀 있습니다. 이는 특정 틈새 애플리케이션에서는 잘 작동하지만 일종의 부족주의(사일로화)를 조장하기도 합니다. + +이 상황은 React, Angular, Vue의 각 개발 커뮤니티가 각자의 문제에 몰두하여 결국 이종 교배가 거의 일어나지 않는다는 점에서도 알 수 있습니다. + +같은 상황은 Rust 대 Node 대 C++의 전쟁터에서도 볼 수 있습니다. 거기서는 강경파가 독자적인 입장을 취하고 커뮤니티 간의 협력을 거부합니다. + +현재 Tauri는 백엔드에 Rust를 사용하지만, 머지않아 Go, Nim, Python, C#과 같은 다른 백엔드도 가능해질 것입니다. 왜냐하면 Tauri는 [webview](https://github.com/webview) 기관에 대한 공식 Rust 바인딩을 유지 관리하고 있지만, 여러분의 필요에 따라 백엔드를 전환할 수 있도록 할 예정이기 때문입니다. Tauri의 API는 "C 상호 운용성"을 갖춘 모든 언어로 구현할 수 있으므로 완전한 다국어화를 실현하려면 "PR(풀 리퀘스트)"을 하나 제출하기만 하면 됩니다. + +## 진정한 오픈 소스 + +커뮤니티가 없으면 오픈 소스의 어떤 것도 의미가 없습니다. 오늘날의 소프트웨어 커뮤니티는 놀라운 곳입니다. 거기서는 사람들이 서로 돕고 멋진 것을 만듭니다. 오픈 소스는 그러한 움직임의 매우 큰 부분을 차지합니다. + +오픈 소스의 의미는 사람마다 다르지만, 대부분의 사람들은 오픈 소스가 자유를 증진하는 데 도움이 된다는 데 동의할 것입니다. 소프트웨어가 귀하의 권리를 존중하지 않는 경우, 윤리에 반하는 동작으로 인해 불공평하게 느껴지고 잠재적으로 귀하의 자유를 침해할 수 있습니다. + +이 때문에 FLOSS 지지자들이 "진정한" 오픈 소스인 Tauri를 사용하여 애플리케이션을 만들고 FSF(자유 소프트웨어 재단)가 승인한 GNU/Linux 배포판에 포함될 수 있다는 것을 자랑스럽게 생각합니다. + +> > > 《번역 주》 **FLOSS**(free/libre open-source software) 오픈 소스 자유 소프트웨어. + +## Tauri의 미래 + +Tauri의 미래는 여러분의 참여와 기여에 달려 있습니다. 실제로 Tauri를 사용해 보거나, 문제를 보고하거나, 워킹 그룹(각 작업 그룹)에 참여하거나, 기부해 보십시오. 어떤 기여도 필수적입니다. 어쨌든, 꼭 연락 주시기 바랍니다. diff --git a/src/content/docs/ko/about/trademark.md b/src/content/docs/ko/about/trademark.md new file mode 100644 index 0000000000..649412bdc5 --- /dev/null +++ b/src/content/docs/ko/about/trademark.md @@ -0,0 +1,130 @@ +--- +title: 상표 가이드라인 +i18nReady: true +--- + +:::[warning【주의】] +《번역 주》 이 한국어 번역은 "참고 번역"이며 정확한 법령 해석이 아닙니다. 상표에 관한 취급은 "영문판"의 기재에 따라 주십시오. +::: + +이 방침 문서 "상표 가이드라인"은 "The Tauri Programme within the Commons Conservancy"가 소유한 "TAURI 상표", "서비스 마크" 및 "로고"의 사용 방법을 이해하는 데 도움을 드리기 위해 작성되었습니다. + +> 《번역 주》 **The Tauri Programme within the Commons Conservancy** Tauri 개발팀의 공식 명칭. "커먼즈 컨서번시 내의 Tauri 프로그램"(공유 재산 보호 관리 단체 사이트 내에 등록된 Tauri 프로그램이라는 의미). 법령 관련 내용을 나타내는 본고에서는 원문 표기를 사용합니다. "커먼즈 컨서번시"에 대해서는 [Tauri의 거버넌스](/ko/about/governance/)를 참조하십시오. + +Tauri의 소프트웨어는 자유/무료 오픈 소스 소프트웨어 라이선스에 따라 제공되지만, 그 저작권 라이선스에는 Tauri의 상표를 사용할 라이선스가 포함되어 있지 않습니다. 이 방침 문서는 "배경법" 및 "커뮤니티의 기대"에 따라 Tauri의 상표를 사용하는 방법을 설명하는 것을 목적으로 합니다. + +**이 "방침 문서"가 다루는 범위는:** + +- Tauri의 "문자 상표"와 "서비스/마크": TAURI, TAO, WRY +- Tauri의 "로고": The TAURI, TAO, WRY 각 로고(및 모든 시각적 파생물) + +> 《번역 주》 **문자 상표** 원문은 "word trademarks". 기업명이나 제품명의 문자만으로 만들어진 상표. "워드 마크 word mark". + +이 방침 문서는 등록 여부에 관계없이 모든 "상표"와 "서비스 마크"에 적용됩니다. + +## 일반적인 가이드라인 + +Tauri의 상표 중 하나를 사용하는 경우, 수신자가 "누구로부터 무엇을" 받고 있는지에 대해 항상 누구에게도 오해를 주지 않는 형태로 이루어져야 합니다. 예를 들어, TAURI 소프트웨어의 수정판(포크라고도 함)을 배포하는 경우, "TAURI 소프트웨어를 배포하고 있다"고 말할 수 없습니다. 수신자가 수정판과 Tauri 공식판의 차이를 이해하지 못할 수 있기 때문입니다. + +또한, 귀하의 웹사이트가 Tauri의 공식 웹사이트인 것처럼, 또는 Tauri가 귀하의 웹사이트를 공인하고 있는 것처럼 오해를 주는 형태로 귀하의 웹사이트에 Tauri의 로고를 사용할 수 없습니다. + +단, TAURI 소프트웨어를 좋아한다거나, TAURI 커뮤니티에 참여하고 있다거나, TAURI 소프트웨어의 수정되지 않은 그대로의 버전을 제공하고 있다는 등의 말은 할 수 있습니다. + +Tauri의 상표 또는 그 변형을 귀하 자신의 상표, 서비스 마크, 도메인 이름, 회사명, 상호, 제품명 또는 서비스명의 일부로 사용하거나 등록할 수 없습니다. + +상표법에서는 Tauri의 상표와 매우 유사한 명칭이나 상표의 사용을 인정하지 않습니다. 따라서 Tauri의 상표류나 발음 표기의 명백한 "변형", "외국어 동의어", "모사", 또는 유사하거나 호환되는 제품이나 서비스의 "약어"를 사용할 수 없습니다. Tauri에서는 다음과 같은 사례를 Tauri의 상표류에 매우 유사하다고 간주합니다: + +- TAURIMAGE +- Tauri Wallet App + +## 허용되는 사용 예 + +### 애플리케이션 + +TAURI는 컴퓨터 기기용 애플리케이션을 만들기 위한 프레임워크입니다. 귀하의 애플리케이션이 TAURI를 사용하고 있음을 표방할 수는 있지만, 그 애플리케이션이 "the Tauri Programme within the Commons Conservancy"에 의해 인증되었거나 공식 애플리케이션이라는 인상을 주지 않도록 주의해야 합니다. 또한, 그 애플리케이션에 Tauri의 아이콘을 붙여 _공개하지 않도록_ 주의하십시오. + +### 플러그인과 템플릿 + +적절한 명명 규칙을 사용하여 플러그인이나 템플릿 코드를 공개할 수는 있지만, 그러한 저작물은 "공식적으로 승인된 것이 아님"을 명기해야 합니다. GitHub 조직 내의 `tauri-apps`에 의해 관리되는 코드베이스만이 공식판으로 간주됩니다. + +## Tauri Core의 수정판(포크) + +Tauri 소프트웨어(TAURI CORE)의 수정판을 배포하는 경우, Tauri의 로고와 이름을 모두 삭제해야 합니다. 그러나 원본 라이선스를 SPDX 형식으로 남겨야 합니다. 귀하가 제공하려는 소프트웨어의 출처를 성실하게 기술하기 위해 Tauri의 "워드 마크"는 사용할 수 있지만, Tauri의 "로고"는 사용할 수 없습니다. 예를 들어, 배포하는 코드가 Tauri 소프트웨어의 수정판인 경우, "이 소프트웨어는 TAURI 소프트웨어의 소스 코드에서 파생되었습니다"라고 기재할 수 있습니다. + +> 《번역 주》 **SPDX 형식** [Software Package Data Exchange](https://ko.wikipedia.org/wiki/Software_Package_Data_Exchange) "소프트웨어 패키지 데이터 교환"의 약자. + +### Tauri와의 호환성에 관한 고지에 대하여 + +귀하의 소프트웨어와 Tauri 소프트웨어의 관계를 성실하게 표현하기 위해 "워드 마크"는 사용할 수 있지만, "로고"는 사용할 수 없습니다. 그 외의 사용 방법은 Tauri가 귀하의 소프트웨어를 인증 또는 승인했다고 받아들여질 수 있습니다. 만약 Tauri의 로고를 사용하고 싶다면, 라이선스 조건에 대해 상담해 주십시오. + +### 호환되는 제품의 명명에 대하여 + +TAURI 소프트웨어와 관련하여 귀하의 제품을 설명하고 싶다면, 그 조건은 다음과 같습니다. 다음 조건을 충족하는 경우에만 귀하의 소프트웨어를 "TAURI의 XYZ"(XYZ는 귀하의 제품명)라고 부를 수 있습니다: + +- 귀하의 제품과 함께 공개되는 TAURI 소프트웨어의 모든 버전은 Tauri가 제공하는 바이너리 자체이거나, Tauri가 제공하는 코어 소프트웨어와 도구로 만들어진 것이어야 합니다. +- 귀하의 제품이 TAURI 소프트웨어의 API와 완벽하게 호환되어야 합니다. +- 마케팅 자료나 제품 설명에 다음 문장을 기재해야 합니다: "TAURI is a trademark of The Tauri Programme within the Commons Conservancy. https://tauri.app/ "(TAURI는 the Tauri Programme within the Commons Conservancy의 상표입니다. https://tauri.app/). + +### 사용자 그룹에서의 상표 이용에 대하여 + +다음 조건을 충족하는 경우, "사용자 그룹명"의 일부로 "워드 마크"를 사용할 수 있습니다: + +- 해당 그룹의 활동 중심이 "Tauri 소프트웨어"일 것. +- 해당 그룹이 영리 활동을 하지 않을 것. +- 참가 비용이 장소비, 음식비에 한정될 것. + +Tauri의 상표를 사용하여 회의를 개최하는 것은 허용되지 않습니다. + +### 도메인 이름에서의 상표 사용 금지 + +Tauri의 "워드 마크" 또는 그 변형이나 조합을 포함하는 도메인 이름을 등록할 수 없습니다. + +### 기타 TAURI 상표의 영리 목적 사용에 대하여 + +비디오, 튜토리얼 시리즈, 서적, 기타 교육 자료를 제작하고 구독, 판매, 광고 등을 통해 보상을 받는 경우, "the Tauri Programme within the Commons Conservancy"로부터 명시적인 라이선스 허가를 받아야 합니다. + +## Tauri 상표의 표시 방법 + +Tauri의 상표류를 사용할 권리가 있는 경우, 다음 방법으로 표시하십시오. + +### 상표 마크와 설명문에 대하여 + +웹 페이지, 문서 또는 자료의 처음 또는 가장 눈에 띄는 곳에 상표 마크가 표시되는 경우, 그 상표가 "등록 상표("®")"인지 "미등록 상표("™")"인지를 나타내는 기호를 부기해야 합니다. 어느 쪽에 해당하는지 불분명한 경우, Tauri에 문의하십시오. ("TAURI" 자체는 등록 상표입니다.) + +상표 마크를 사용한 페이지 하단에 다음 주의 사항을 기재하십시오. "TAURI is trademark of [The Tauri Programme within the Commons Conservancy]"(TAURI는 "커먼즈 컨서번시의 Tauri 개발 활동 프로그램"의 상표입니다라는 의미). + +### 문중 상표의 사용에 대하여 + +상표는 항상 "그대로의 형태", "정확한 철자"로 사용하고, 생략하거나, 하이픈으로 연결하거나, 다른 단어와 조합해서는 안 됩니다. + +- 부적절한 예: TAUREE 《※ 철자가 다릅니다.》 +- 적절한 예: TAURI + +상표를 "복수형으로 만들지 마십시오". + +- 부적절한 예: I have seventeen **TAURIs** running on my computer. (컴퓨터에서 17개의 TAURI를 실행하고 있습니다.) 《※ 복수형 표기》 +- 적절한 예: I am running seventeen **TAURI** applications on my computer and have ram to spare. (컴퓨터에서 17개의 TAURI 애플리케이션을 실행하고 있으며 RAM에 여유가 있습니다.) + +상표는 항상 명사를 수식하는 "형용사로서" 사용하십시오. + +- Unacceptable: This is a TAURI. +- Acceptable: This is a TAURI software application. +- 부적절한 예: This is a **TAURI**. (이것은 TAURI입니다.) 《※ 명사로 사용》 +- 적절한 예: This is a **TAURI** software application. (이것은 TAURI의 소프트웨어 애플리케이션입니다.) + +### 로고의 사용에 대하여 + +로고는 확대/축소 표시를 제외하고 어떠한 변경도 해서는 안 됩니다. 즉, 장식적인 요소의 추가 색상이나 비율의 변경 변형 다른 요소의 추가, 로고와의 조합 등을 할 수 없습니다. + +Tauri에서는 로고의 "고대비" 버전도 준비되어 있으며, 다음 "자산" 섹션에서 다운로드할 수 있습니다. + +## 자산 + +- [브랜드 가이드라인](/assets/brand_guidelines.pdf): 이 링크(영문판)에서는 상표에 관한 모든 자료를 다운로드할 수 있습니다 - (PDF, 74.3 MB) +- [로고 팩](/assets/logopack.zip): 이 링크에서는 "로고"와 "워드 마크"의 SVG 형식과 PNG 형식의 데이터를 다운로드할 수 있습니다 - (ZIP, 203 KB) + +--- + +"The Tauri Programme within the Commons Conservancy" Conservancy 내의 Tauri 프로그램은 이러한 상표 가이드라인을 언제든지 변경할 권리를 보유합니다. 질문이나 문의 사항이 있는 경우 `trademark@tauri.app`으로 메일을 보내주십시오. + +위의 가이드라인은 http://www.modeltrademarkguidelines.org에서 구할 수 있는 "모델 상표 가이드라인"을 기반으로 하며, "크리에이티브 커먼즈 저작자표시 3.0 비이식 라이선스 1.0판 2022/08/20자" (https://creativecommons.org/licenses/by/3.0/deed.en_EU)에 따라 사용되었습니다. diff --git a/src/content/docs/ko/concept/Inter-Process Communication/brownfield.md b/src/content/docs/ko/concept/Inter-Process Communication/brownfield.md new file mode 100644 index 0000000000..1ccf67cf48 --- /dev/null +++ b/src/content/docs/ko/concept/Inter-Process Communication/brownfield.md @@ -0,0 +1,31 @@ +--- +title: 브라운필드 패턴(Brownfield Pattern) +i18nReady: true +--- + +_**기본 IPC 패턴입니다**_ + +이 패턴은 Tauri를 사용하는 데 있어 가장 명확하고 이해하기 쉬운 것입니다. 기존 프론트엔드 프로젝트와 최대한 호환되도록 하려고 하기 때문입니다. 간단히 말해, 기존 웹 프론트엔드가 브라우저 내에서 사용하는 것 외에는 다른 것이 필요하지 않도록 되어 있다는 것입니다. +단, 이것은 기존 브라우저 애플리케이션에서 작동하는 **_모든 것_**이 그대로 작동한다는 의미는 아닙니다. + +일반적인 "브라운필드"형 소프트웨어 개발에 익숙하지 않은 경우, Wikipedia의 [Brownfield Wikipedia article]()(한국어판 없음)에 알기 쉬운 개설이 있습니다. +Tauri의 경우, (브라운필드형 개발의 대상이 되는) 기존 소프트웨어란 레거시 시스템이 아니라 현재 브라우저의 지원과 동작입니다. + +## 설정 + +브라운필드형 개발은 기본 패턴이므로 설정 옵션을 지정할 필요가 없습니다. +명시적으로 설정하려면 `tauri.conf.json` 구성 파일 내의 `tauri > pattern` 객체를 사용합니다. + +```json +{ + "tauri": { + "pattern": { + "use": "brownfield" + } + } +} +``` + +_**브라운필드형에서는 추가 설정 옵션이 없습니다.**_ + +[brownfield wikipedia article]: https://en.wikipedia.org/wiki/Brownfield_(software_development) diff --git a/src/content/docs/ko/concept/Inter-Process Communication/index.mdx b/src/content/docs/ko/concept/Inter-Process Communication/index.mdx new file mode 100644 index 0000000000..952f6486aa --- /dev/null +++ b/src/content/docs/ko/concept/Inter-Process Communication/index.mdx @@ -0,0 +1,94 @@ +--- +title: 프로세스 간 통신 +sidebar: + label: Overview + order: 1 +i18nReady: true +--- + +import { CardGrid, LinkCard } from '@astrojs/starlight/components'; + +"프로세스 간 통신(Inter-Process Communication)"(IPC)은 단일 프로세스가 안전하게 통신할 수 있도록 하여 더 복잡한 애플리케이션을 구축하는 데 핵심적인 역할을 합니다. + +구체적인 "프로세스 간 통신(IPC)" 유형(패턴)에 대해서는 다음 설명을 참조하십시오. + + + + + + +Tauri는 [Asynchronous Message Passing](https://ko.wikipedia.org/wiki/메시지_전달)이라는 특별한 스타일의 프로세스 간 통신을 사용합니다. 이 방법에서는 프로세스들이 간단한 데이터 표현을 사용하여 직렬화된 "_요청_"과 "_응답_"을 주고받습니다. 메시지 전달은 인터넷상의 클라이언트-서버 통신에 사용되는 메커니즘이므로 웹 개발 경험이 있는 사람이라면 누구나 익숙할 것입니다. + +또한 메시지 전달은 수신자가 필요에 따라 "요청"을 거부하거나 폐기할 수 있으므로 "공유 메모리 방식"이나 "직접 함수 접근 방식"보다 안전한 방법입니다. 예를 들어, Tauri 코어 프로세스가 "요청"을 악의적인 것으로 판단하면 해당 요청은 폐기되고 해당 함수 처리는 실행되지 않습니다. + +아래에서는 Tauri의 두 가지 "IPC 프리미티브(동기 기본 명령)", 즉 "이벤트 `Events`"와 "명령 `Commands`"에 대해 자세히 설명합니다. + +## 이벤트 + +"이벤트"는 자동 추적형 단방향 "IPC 메시지"로, 라이프사이클 중 각 이벤트와 상태 변화를 전달하는 데 최적입니다. +"[명령](#명령)"과 달리 "이벤트"는 프론트엔드와 Tauri Core(코어부) 양쪽에서 발행할 수 있습니다. + +
+ +```d2 sketch pad=50 +shape: sequence_diagram + +Frontend: { + shape: rectangle + label: "Webview\nFrontend" +} +Core: { + shape: rectangle + label: "Core\nBackend" +} + +Frontend -> Core: "이벤트"{style.animated: true} +Core -> Frontend: "이벤트"{style.animated: true} +``` + +
코어부와 Webview 간에 주고받는 이벤트
+
+ +## 명령 + +Tauri는 또한 "IPC 메시지" 외에도 [foreign function interface](https://ko.wikipedia.org/wiki/외부_함수_인터페이스)와 같은 추상화도 제공합니다[^1]. 기본 주요 API인 `invoke`는 브라우저의 `fetch` API와 유사하며, 프론트엔드가 Rust 함수를 호출하고 인수를 전달하며 데이터를 수신할 수 있도록 합니다. + +이 메커니즘은 내부적으로 [JSON-RPC]와 같은 프로토콜을 사용하여 요청과 응답을 직렬화하므로 모든 인수와 반환 값 데이터는 JSON 표준에 따라 직렬화 가능해야 합니다. + +
+ +```d2 sketch pad=50 +shape: sequence_diagram + + +Frontend: { + label: "Webview\nFrontend" +} + +Core: { + label: "Core\nBackend" +} +InvokeHandler: { + label: "Invoke\nHandler" +} + +Frontend -> Core: "IPC 요청"{style.animated: true} +Core -> InvokeHandler: "명령 호출"{style.animated: true} +InvokeHandler -> Core: "반환 값 직렬화"{style.animated: true} +Core -> Frontend: "응답"{style.animated: true} +``` + +
명령 호출에 관련된 IPC 메시지
+
+ +[^1]: 명령은 내부적으로 메시지 전달을 사용하므로 실제 "외부 함수 인터페이스(FFI)"와 같은 보안상의 함정은 없습니다. + +[Asynchronous Message Passing]: https://en.wikipedia.org/wiki/Message_passing#Asynchronous_message_passing +[json-rpc]: https://www.jsonrpc.org +[foreign function interface]: https://en.wikipedia.org/wiki/Foreign_function_interface diff --git a/src/content/docs/ko/concept/Inter-Process Communication/isolation.md b/src/content/docs/ko/concept/Inter-Process Communication/isolation.md new file mode 100644 index 0000000000..9289fe2057 --- /dev/null +++ b/src/content/docs/ko/concept/Inter-Process Communication/isolation.md @@ -0,0 +1,116 @@ +--- +title: 아이솔레이션 패턴(Isolation Pattern) +i18nReady: true +--- + +아이솔레이션(분리, 격리) 패턴은 프론트엔드에서 전송된 Tauri API 메시지가 Tauri 코어부에 도달하기 전에 JavaScript를 사용하여 가로채고 변경하는 방법입니다. 아이솔레이션 패턴으로 삽입되는 안전한 JavaScript 코드는 아이솔레이션 애플리케이션이라고 합니다. + +## 아이솔레이션 패턴의 필요성 + +아이솔레이션 패턴의 목적은 Tauri 코어부에 대한 원치 않거나 악의적인 프론트엔드 호출로부터 애플리케이션을 보호하기 위한 메커니즘을 개발자에게 제공하는 것입니다. 아이솔레이션 패턴이 필요하게 된 것은 프론트엔드에서 실행되는 신뢰할 수 없는 콘텐츠로 인해 발생하는 위협에 대응하기 위해 만들어졌습니다. 이러한 위협은 많은 종속성을 가진 애플리케이션에서 흔히 볼 수 있는 사례입니다. 애플리케이션이 마주칠 수 있는 많은 위협 원인의 목록은 [보안: 위협 모델]을 참조하십시오. + +위의 가장 큰 위협 모델은 "개발 시 위협"이었지만, 이러한 위협은 아이솔레이션 패턴을 설계할 때 염두에 두었던 것입니다. 많은 프론트엔드 빌드 도구가 종종 깊이 중첩된 수십(또는 수백) 개의 종속성으로 이루어져 있을 뿐만 아니라, 복잡한 애플리케이션 측에도 수많은 (이 또한 종종 깊이 중첩된) 종속성이 있을 수 있으므로 최종 출력 버전에 번들로 제공됩니다. + +## 아이솔레이션 패턴을 사용하는 경우 + +Tauri는 아이솔레이션 패턴을 사용할 수 있는 경우 항상 사용하는 것을 강력히 권장합니다. 아이솔레이션 애플리케이션에서는 프론트엔드의 _**모든**_ 메시지를 "캡처"(인터셉트)하므로 아이솔레이션 패턴이 _항상_ 사용됩니다. + +또한 Tauri는 외부 Tauri API를 사용할 때 항상 애플리케이션을 "잠금"(록다운)할 것을 강력히 권장합니다. 앱 개발자는 안전한 아이솔레이션 애플리케이션을 이용하여 IPC 입력을 검증하고, 그 입력 내용이 확실히 예상되는 매개변수 범위 내에 있는지 확인합니다. 사례로는 파일 읽기 또는 쓰기 호출이 해당 애플리케이션의 예상치 못한 위치의 경로에 액세스하려고 하지 않는지 확인하거나, Tauri API의 "HTTP 페치 콜"이 "Origin 헤더"에 해당 애플리케이션이 예상하는 것만 설정하고 있는지 확인하는 것입니다. + +하지만 프론트엔드의 _**모든**_ 메시지를 캡처하기 때문에, 상시 동작 API, 예를 들어 [Events] 등에서도 작동합니다. 일부 이벤트에서는 앱 고유의 Rust 코드로 작업을 실행시킬 가능성이 있으므로, 그에도 유사한 검증 방법으로 대응할 수 있습니다. + +## 아이솔레이션 패턴의 적용 + +아이솔레이션 패턴에서 중요한 것은 프론트엔드와 Tauri Core(타우리 코어부) 사이에 안전한 애플리케이션을 삽입하여 IPC 수신 메시지를 캡처하고 수정하는 것입니다. 이는 ` + +## 安全优先 + +在当今世界,每个真实的威胁模型都假设用户的设备已经被入侵。这让应用程序开发人员陷入了一个复杂的境地,因为如果设备已经处于危险之中,如何能让软件可信呢? + +我们采取的是纵深防御。我们希望你能采取一切可能的预防措施来减少你面对攻击者的表面积。Tauri 允许你选择要发布的 API 端点,无论你是否希望在应用中内置本地主机服务器,它甚至可以在运行时随机化功能句柄。这些技术和其他技术构成了增强您和您的用户能力的安全基线。 + +通过使静态攻击变得极其困难和将系统彼此隔离来减慢攻击者的速度是游戏的名称。如果您来自电子生态系统,请放心,默认情况下 Tauri 只提供二进制文件,而不是 ASAR 文件。 + +通过选择以安全作为指导力量来构建 Tauri,我们为您提供了采取主动安全姿态的每一个机会。 + +## Polyglots, not Silos + +大多数当代框架使用单一语言范式,因此被困在知识和惯用法的泡沫中。这可以很好地适用于某些利基应用程序,但它也培养了一种部落主义。 + +这可以从 React、Angular 和 Vue 开发社区挤在一起的方式中看出,最终很少产生交叉影响。 + +同样的情况可以在 Rust、Node 和 c++ 的战场上看到,强硬派立场鲜明,拒绝跨社区合作。 + +今天,Tauri 使用 Rust 作为后端,但在不久的将来,其他后端,如 Go、Nim、Python、Csharp 等将成为可能。这是因为我们正在维护官方的 Rust 绑定到 [webview](https://github.com/webview) 组织,并计划让你根据自己的需要切换后端。由于我们的 API 可以使用 C interop 以任何语言实现,因此完全符合规范只需要一个 PR。 + +## 真正的开源 + +如果没有社区,这一切都没有意义。今天的软件社区是一个神奇的地方,人们在这里互相帮助并做出很棒的东西——开源是其中非常重要的一部分。 + +开源对不同的人来说意味着不同的东西,但大多数人都会同意它是为了支持自由。当软件不尊重你的权利时,它看起来是不公平的,并可能通过不道德的方式损害你的自由。 + +这就是为什么我们为 FLOSS 倡导者可以使用 Tauri 构建“可认证的”开源应用程序而感到自豪,这些应用程序可以包含在 FSF 认可的 GNU/Linux 发行版中。 + +## 未来 + +Tauri 的未来取决于你的参与和贡献。尝试它,文件问题,加入一个工作组或捐款-每一个贡献都是重要的。无论如何,请务必保持联系!! diff --git a/src/content/docs/zh-cn/about/trademark.md b/src/content/docs/zh-cn/about/trademark.md new file mode 100644 index 0000000000..7b5bb4dd62 --- /dev/null +++ b/src/content/docs/zh-cn/about/trademark.md @@ -0,0 +1,118 @@ +--- +title: 商标指南 +i18nReady: true +--- + +本商标政策旨在帮助您了解如何在共享资源保护协会内使用 Tauri 项目拥有的金牛座商标、服务标志和徽标。 + +虽然我们的软件是在免费和开源软件许可下提供的,但版权许可并不包括使用我们商标的许可,此政策旨在解释如何使用我们的商标符合背景法律和社区期望。 + +**本政策涵盖:** + +- 我们的文字商标和服务商标:TAURI、TAO、WRY +- 我们的标志:TAURI、TAO、WRY 标志 (以及所有视觉衍生品) + +本政策包括所有商标和服务商标,无论是否注册。 + +## 通用指南 + +无论何时你使用我们的标志,你必须总是以一种不误导任何人的方式这样做,他们从谁那里得到什么。例如,当你发布一个修改版本(又名 Fork)时,你不能说你在发布 TAURI 软件,因为收件人可能不理解你的修改版本和我们自己的版本之间的差异。 + +您也不能在您的网站上使用我们的标志,以表明您的网站是一个官方网站或我们认可您的网站。 + +但是,您可以说您喜欢 TAURI 软件,您参与了 TAURI 社区,您正在提供 TAURI 软件的未修改版本。 + +贵方不得使用或注册我方标志或其变体作为贵方自己的商标、服务标志、域名、公司名称、商号、产品名称或服务名称的一部分。 + +商标法不允许您使用与我们过于相似的名称或商标。因此,贵方不得对类似或兼容的产品或服务使用我们的任何标记的明显变体或任何语音等价物、外语等价物、起飞或缩写。我们认为下面的代码与我们的某个标记过于相似: + +- TAURIMAGE +- Tauri 钱包应用 + +## 可接受的用途 + +### 应用程序 + +TAURI 是一个为计算设备开发应用程序的框架。您可以声称您的应用程序使用了 TAURI,但应注意避免给人留下这样的印象,即您的应用程序是由 Commons Conservancy 的 Tauri 计划批准的,或者是一个正式的应用程序。一定要小心,不要在发布应用程序时使用默认图标。 + +### 插件和模板 + +您可以使用适当的命名约定发布插件和模板的代码,但请注意这些工作没有得到官方批准。只有由 GitHub 组织 `tauri-apps` 内的组织管理的代码库才被认为是官方的。 + +## 核心修改(fork) + +如果你发布我们的软件的修改版本(TAURI 核心),你必须删除我们所有的标志和命名从它。您必须保留我们的 SPDX 格式的原始许可证。您可以使用我们的文字标记,但不能使用我们的标志,以如实描述您所提供的软件的来源。例如,如果您发布的代码是对我们软件的修改,您可能会说,“此软件是从金牛座软件的源代码派生的。” + +### 关于兼容性的声明 + +您可以使用我们的文字标识,但不能使用我们的商标图案,以真实地描述您的软件与我们之间的关系。任何其他用途可能会暗示我们已经认证或批准了您的软件。如果您希望使用我们的商标图案,请联系我们讨论授权条款。 + +### 命名兼容的产品 + +如果您希望以 TAURI 软件为参考来描述您的产品,以下是您可以这样做的条件。只有在以下情况下,您才能将您的软件称为 XYZ(其中 XYZ 是您的产品名称): + +- 我们提供的所有 TAURI 软件版本,都是由我们提供的精确二进制文件或核心软件和工具制造的。 +- 您的产品与 TAURI 软件的 api 完全兼容。 +- 您在营销材料或产品描述中使用以下说明:“金牛座是 Tauri 项目的商标,隶属于共享资源保护协会。https://tauri.app ” + +### 用户组 + +只要满足以下条件,您可以将文字标识作为您的用户组名称的一部分使用: + +- 我们小组的主要焦点是我们的软件 +- 该集团没有盈利 +- 出席会议的任何费用仅用于支付场地、食物和饮料的费用 + +您无权使用我们的标志进行会议。 + +### 不包含域名 + +您不得注册任何域名,包括我们的词标记或任何变体或组合。 + +### TAURI 标志的其他盈利用途 + +如果您正在制作视频,教程系列,书籍或其他教育材料,并且您通过订阅,销售,广告或类似方式获得付款,那么您必须获得公共资源保护协会内 Tauri 计划的明确许可。 + +## 如何显示我们的标志 + +当您有权使用我们的标志时,这里是如何显示它。 + +### 商标标记和图例 + +在网页、文件或文件中,第一次或最突出地提及标志时,应附有一个符号,表明该标志是注册商标(“®”)还是未注册商标(“™”)。如果您不知道哪一种适用,请联系我们。(TAURI 本身就是一个注册商标。) + +在你使用标记的页面底部放置以下通知:TAURI 是 [Tauri 程序在共享资源保护协会]的商标。” + +### 使用文字商标 + +使用正确的商标,无论是缩写,连字符,或与任何其他词或词的组合。 + +- 不可接受的:TAUREE +- 可以接受:TAURI + +不要将商标复数化。 + +- 不可接受:我的电脑上运行着 17 个 TAURI。 +- 可接受:我的计算机上运行了 17 个 TAURI 应用程序,并且有空闲的 ram。 + +使用商标作为修饰名词的形容词。 + +- 不可接受:这是 TAURI。 +- 可接受:这是一个 TAURI 软件应用程序。 + +### 商标的使用 + +除了缩放,你不能改变任何 logo。这意味着你不能添加装饰元素,改变颜色,改变比例,扭曲它,添加元素,或将它与其他 logo 结合。 + +我们有一个高对比度的 logo 版本,你可以在下面的资源部分下载。 + +## 资产 + +- 你可以在这里下载整个[品牌指南](/assets/brand_guidelines.pdf) - (PDF,74.3 MB) +- 您可以在 [Logopack](/assets/logopack.zip) 中下载 LOGO 和 Wordmark 的 SVG 和 PNG 格式文件 - (ZIP,203 KB) + +--- + +共享资源保护协会内的 Tauri 项目保留在任何时候修改这些商标指南的所有权利。如有疑问,请发送电子邮件至 `trademark@tauri.app`。 + +这些准则基于《模板商标指南》,可在 http://www.modeltrademarkguidelines.org 上获取,采用创作共用署名 3.0 国际许可证使用:https://creativecommons.org/licenses/by/3.0/deed.en_EU。版本 1.0 日期为 2022 年 8 月 20 日。 diff --git a/src/content/docs/zh-cn/concept/Inter-Process Communication/brownfield.md b/src/content/docs/zh-cn/concept/Inter-Process Communication/brownfield.md new file mode 100644 index 0000000000..436c57c0c5 --- /dev/null +++ b/src/content/docs/zh-cn/concept/Inter-Process Communication/brownfield.md @@ -0,0 +1,27 @@ +--- +title: Brownfield 模式 +--- + +_**这是默认模式。**_ + +这是使用 Tauri 的最简单和最直接的模式,因为本模式会尽最大可能尝试与现有的前端项目兼容。简而言之,它尽量不要求额外的配置,跟现有的 web 前端应用在浏览器中使用的方式保持一致。但并不是 _**所有**_ 在现有浏览器应用中有效的功能都会开箱即用。 + +如果你不熟悉 Brownfield 软件开发模式,可以阅读 [Brownfield 维基百科]。对 Tauri 而言,现有软件特指现代浏览器支持的特性与行为规范,而非传统遗留系统。 + +## 配置 + +因为 Brownfield 模式是默认模式,所以无需设置任何配置选项。如果要显式设置它,你可以在 `tauri.conf.json` 配置文件中使用 `tauri > pattern` 对象。 + +```json +{ + "tauri": { + "pattern": { + "use": "brownfield" + } + } +} +``` + +_**Brownfield 模式没有额外的配置选项。**_ + +[Brownfield 维基百科]: https://en.wikipedia.org/wiki/Brownfield_(software_development) diff --git a/src/content/docs/zh-cn/concept/Inter-Process Communication/index.mdx b/src/content/docs/zh-cn/concept/Inter-Process Communication/index.mdx new file mode 100644 index 0000000000..3a90bfe69c --- /dev/null +++ b/src/content/docs/zh-cn/concept/Inter-Process Communication/index.mdx @@ -0,0 +1,93 @@ +--- +title: 进程间通信 +sidebar: + label: 概述 + order: 1 + i18nReady: true +--- + +import { CardGrid, LinkCard } from '@astrojs/starlight/components'; + +进程间通信(IPC)允许隔离的进程安全地进行通信,是构建更复杂应用程序的关键。 + +在以下指南中了解特定的 IPC 模式: + + + + + + +Tauri 使用一种特定风格的进程间通信,称为[异步消息传递],其中进程通过一些简单的数据表示交换*请求*和*响应*。对于任何有 Web 开发经验的人来说,消息传递应该听起来很熟悉,因为这种范式用于互联网的客户端-服务器通信。 + +消息传递是一种比共享内存或直接函数访问更安全的技术,因为接收方可以自由地拒绝或丢弃请求。例如,如果Tauri核心进程确定某个请求是恶意的,它将简单地丢弃该请求,并且不会执行相应的函数。 + +接下来,我们将更详细地解释 Tauri 的两个 IPC 原语——`事件`和`命令`。 + +## 事件 + +事件是一次性、单向的 IPC 消息,最适合用于通信生命周期事件和状态变化。与[命令](#命令)不同,事件可以由前端*和* Tauri 核心发出。 + +
+ +```d2 sketch pad=50 +shape: sequence_diagram + +Frontend: { + shape: rectangle + label: "Webview\nFrontend" +} +Core: { + shape: rectangle + label: "Core\nBackend" +} + +Frontend -> Core: "Event"{style.animated: true} +Core -> Frontend: "Event"{style.animated: true} +``` + +
在核心和 Webview 之间发送的事件。
+
+ +## 命令 + +Tauri 还提供了一种类似于[外部函数接口]的抽象,建立在IPC消息之上[^1]。主要 API `invoke` 类似于浏览器的`fetch` API,允许前端调用 Rust 函数、传递参数并接收数据。 + +由于该机制在底层使用类似 [JSON-RPC] 的协议来序列化请求和响应,因此所有参数和返回数据必须能够序列化为 JSON。 + +
+ +```d2 sketch pad=50 +shape: sequence_diagram + + +Frontend: { + label: "Webview\nFrontend" +} + +Core: { + label: "Core\nBackend" +} +InvokeHandler: { + label: "Invoke\nHandler" +} + +Frontend -> Core: "IPC Request"{style.animated: true} +Core -> InvokeHandler: "Invoke command"{style.animated: true} +InvokeHandler -> Core: "Serialize return"{style.animated: true} +Core -> Frontend: "Response"{style.animated: true} +``` + +
命令调用中涉及的 IPC 消息。
+
+ +[^1]: 由于命令在底层仍然使用消息传递,因此它们没有真实 FFI 接口所面临的安全隐患。 + +[异步消息传递]: https://en.wikipedia.org/wiki/Message_passing#Asynchronous_message_passing +[json-rpc]: https://www.jsonrpc.org +[外部函数接口]: https://en.wikipedia.org/wiki/Foreign_function_interface diff --git a/src/content/docs/zh-cn/concept/Inter-Process Communication/isolation.md b/src/content/docs/zh-cn/concept/Inter-Process Communication/isolation.md new file mode 100644 index 0000000000..27aca375f1 --- /dev/null +++ b/src/content/docs/zh-cn/concept/Inter-Process Communication/isolation.md @@ -0,0 +1,115 @@ +--- +title: 隔离模式 +i18nReady: true +--- + +**隔离模式**(Isolation Pattern)使用 JavaScript 截获并修改前端向 Tauri Core 发送的 Tauri API 消息。由隔离模式注入的 JavaScript 安全代码被称为**隔离应用程序**(Isolation Application)。 + +## 为什么这么做 + +隔离模式向开发者提供一种避免程序中前端不必要或恶意地调用 Tauri Core 的机制。这一需求源自运行在前端的不受信任内容的威胁,有大量依赖的应用经常遇到这种情形。请查看 [Security: Threat Models] 来了解应用程序可能遇到的威胁的来源。 + +隔离模式在设计时考虑的最大的威胁模型是**开发威胁**(Development Threats)。除了许多前端构建时工具所包括的数十(甚至数百)个通常是深度嵌套的依赖,一个复杂的应用也还可能捆绑大量(通常也是深度嵌套的)依赖到最终输出。 + +## 何时需要 + +Tauri 强烈推荐只要有可能就使用隔离模式。因为隔离应用程序截获来自前端的**_所有_**信息,它*始终*可以被使用。 + +Tauri 同时也强烈推荐在使用外部 Tauri API 时加强应用的安全性。作为开发者,你可以使用安全隔离应用程序尝试验证 IPC 输入,以确保它们在某些预期参数范围内。例如,你可能需要检查读取或写入文件的调用是否尝试访问应用程序预期位置之外的路径。另一个例子是确保 Tauri API 的 HTTP 获取调用仅将 Origin 标头设置为应用程序预期的值。 + +也就是说,它会拦截来自前端的**_所有_**消息,因此它甚至可以与始终在线的 API(例如 [事件] ) 配合使用。由于某些事件可能会导致你自己的 Rust 代码执行操作,因此可以对它们使用相同类型的验证技术。 + +## 如何使用 + +隔离模式的核心在于在前端和 Tauri Core 之间注入一个安全的应用程序,用于拦截和修改传入的 IPC 消息。它利用 `