Full Code of sipeed/NanoKVM-USB for AI

main 1d1dd5e9fd24 cached
200 files
408.3 KB
118.1k tokens
476 symbols
1 requests
Download .txt
Showing preview only (467K chars total). Download the full file or copy to clipboard to get everything.
Repository: sipeed/NanoKVM-USB
Branch: main
Commit: 1d1dd5e9fd24
Files: 200
Total size: 408.3 KB

Directory structure:
gitextract_n58uj4mo/

├── .github/
│   └── workflows/
│       ├── build.yml
│       ├── issue-tracker.yml
│       └── release.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── browser/
│   ├── .editorconfig
│   ├── .gitignore
│   ├── .prettierignore
│   ├── .prettierrc.yaml
│   ├── README.md
│   ├── eslint.config.js
│   ├── index.html
│   ├── package.json
│   ├── pnpm-workspace.yaml
│   ├── postcss.config.js
│   ├── src/
│   │   ├── App.tsx
│   │   ├── assets/
│   │   │   ├── index.css
│   │   │   └── keyboard.css
│   │   ├── components/
│   │   │   ├── device-modal/
│   │   │   │   ├── index.tsx
│   │   │   │   ├── serial-port.tsx
│   │   │   │   └── video.tsx
│   │   │   ├── keyboard/
│   │   │   │   └── index.tsx
│   │   │   ├── menu/
│   │   │   │   ├── audio/
│   │   │   │   │   └── index.tsx
│   │   │   │   ├── fullscreen/
│   │   │   │   │   └── index.tsx
│   │   │   │   ├── index.tsx
│   │   │   │   ├── keyboard/
│   │   │   │   │   ├── index.tsx
│   │   │   │   │   ├── paste.tsx
│   │   │   │   │   ├── shortcuts/
│   │   │   │   │   │   ├── index.tsx
│   │   │   │   │   │   ├── recorder.tsx
│   │   │   │   │   │   ├── shortcut.tsx
│   │   │   │   │   │   └── types.ts
│   │   │   │   │   └── virtual-keyboard.tsx
│   │   │   │   ├── mouse/
│   │   │   │   │   ├── direction.tsx
│   │   │   │   │   ├── index.tsx
│   │   │   │   │   ├── jiggler.tsx
│   │   │   │   │   ├── mode.tsx
│   │   │   │   │   ├── speed.tsx
│   │   │   │   │   └── style.tsx
│   │   │   │   ├── recorder/
│   │   │   │   │   └── index.tsx
│   │   │   │   ├── serial-port/
│   │   │   │   │   └── index.tsx
│   │   │   │   ├── settings/
│   │   │   │   │   ├── index.tsx
│   │   │   │   │   └── language.tsx
│   │   │   │   └── video/
│   │   │   │       ├── device.tsx
│   │   │   │       ├── index.tsx
│   │   │   │       ├── resolution.tsx
│   │   │   │       ├── rotation.tsx
│   │   │   │       └── scale.tsx
│   │   │   ├── mouse/
│   │   │   │   ├── absolute.tsx
│   │   │   │   ├── index.tsx
│   │   │   │   ├── relative.tsx
│   │   │   │   ├── touchpad.ts
│   │   │   │   └── types.ts
│   │   │   ├── ui/
│   │   │   │   ├── kbd.tsx
│   │   │   │   └── scroll-area.tsx
│   │   │   └── virtual-keyboard/
│   │   │       ├── index.tsx
│   │   │       └── keys.ts
│   │   ├── i18n/
│   │   │   ├── index.ts
│   │   │   ├── languages.ts
│   │   │   └── locales/
│   │   │       ├── be.ts
│   │   │       ├── de.ts
│   │   │       ├── en.ts
│   │   │       ├── ko.ts
│   │   │       ├── nl.ts
│   │   │       ├── pl.ts
│   │   │       ├── pt_br.ts
│   │   │       ├── ru.ts
│   │   │       ├── zh.ts
│   │   │       └── zh_tw.ts
│   │   ├── jotai/
│   │   │   ├── device.ts
│   │   │   ├── keyboard.ts
│   │   │   └── mouse.ts
│   │   ├── libs/
│   │   │   ├── browser/
│   │   │   │   └── index.ts
│   │   │   ├── device/
│   │   │   │   ├── index.ts
│   │   │   │   ├── proto.ts
│   │   │   │   ├── serial-port.ts
│   │   │   │   └── utils.ts
│   │   │   ├── keyboard/
│   │   │   │   ├── charCodes.ts
│   │   │   │   ├── keyboard.ts
│   │   │   │   └── keymap.ts
│   │   │   ├── media/
│   │   │   │   ├── camera.ts
│   │   │   │   └── permission.ts
│   │   │   ├── mouse/
│   │   │   │   └── index.ts
│   │   │   ├── mouse-jiggler/
│   │   │   │   └── index.ts
│   │   │   └── storage/
│   │   │       └── index.ts
│   │   ├── main.tsx
│   │   ├── types.ts
│   │   └── vite-env.d.ts
│   ├── tailwind.config.js
│   ├── tsconfig.app.json
│   ├── tsconfig.json
│   ├── tsconfig.node.json
│   ├── vite.config.d.ts
│   └── vite.config.ts
├── desktop/
│   ├── .editorconfig
│   ├── .gitignore
│   ├── .npmrc
│   ├── .prettierignore
│   ├── .prettierrc.yaml
│   ├── README.md
│   ├── build/
│   │   ├── entitlements.mac.plist
│   │   └── icon.icns
│   ├── dev-app-update.yml
│   ├── electron-builder.yml
│   ├── electron.vite.config.ts
│   ├── eslint.config.mjs
│   ├── notarize.js
│   ├── package.json
│   ├── src/
│   │   ├── common/
│   │   │   └── ipc-events.ts
│   │   ├── main/
│   │   │   ├── device/
│   │   │   │   ├── index.ts
│   │   │   │   ├── proto.ts
│   │   │   │   └── serial-port.ts
│   │   │   ├── events/
│   │   │   │   ├── app.ts
│   │   │   │   ├── index.ts
│   │   │   │   ├── serial-port.ts
│   │   │   │   └── updater.ts
│   │   │   └── index.ts
│   │   ├── preload/
│   │   │   ├── index.d.ts
│   │   │   └── index.ts
│   │   └── renderer/
│   │       ├── index.html
│   │       └── src/
│   │           ├── App.tsx
│   │           ├── assets/
│   │           │   └── styles/
│   │           │       ├── base.css
│   │           │       ├── keyboard.css
│   │           │       └── main.css
│   │           ├── components/
│   │           │   ├── device/
│   │           │   │   ├── connect.tsx
│   │           │   │   ├── disconnect.tsx
│   │           │   │   ├── index.tsx
│   │           │   │   ├── serial-port.tsx
│   │           │   │   └── video.tsx
│   │           │   ├── keyboard/
│   │           │   │   └── index.tsx
│   │           │   ├── menu/
│   │           │   │   ├── audio/
│   │           │   │   │   └── index.tsx
│   │           │   │   ├── index.tsx
│   │           │   │   ├── keyboard/
│   │           │   │   │   ├── index.tsx
│   │           │   │   │   ├── paste.tsx
│   │           │   │   │   ├── shortcuts/
│   │           │   │   │   │   ├── index.tsx
│   │           │   │   │   │   ├── recorder.tsx
│   │           │   │   │   │   ├── shortcut.tsx
│   │           │   │   │   │   └── types.ts
│   │           │   │   │   └── virtual-keyboard.tsx
│   │           │   │   ├── language/
│   │           │   │   │   └── index.tsx
│   │           │   │   ├── mouse/
│   │           │   │   │   ├── direction.tsx
│   │           │   │   │   ├── index.tsx
│   │           │   │   │   ├── jiggler.tsx
│   │           │   │   │   ├── mode.tsx
│   │           │   │   │   ├── speed.tsx
│   │           │   │   │   └── style.tsx
│   │           │   │   ├── recorder/
│   │           │   │   │   └── index.tsx
│   │           │   │   ├── serial-port/
│   │           │   │   │   └── index.tsx
│   │           │   │   ├── settings/
│   │           │   │   │   ├── about.tsx
│   │           │   │   │   ├── appearance.tsx
│   │           │   │   │   ├── index.tsx
│   │           │   │   │   ├── reset.tsx
│   │           │   │   │   └── update.tsx
│   │           │   │   └── video/
│   │           │   │       ├── device.tsx
│   │           │   │       ├── index.tsx
│   │           │   │       ├── resolution.tsx
│   │           │   │       └── scale.tsx
│   │           │   ├── mouse/
│   │           │   │   ├── absolute.tsx
│   │           │   │   ├── index.tsx
│   │           │   │   ├── relative.tsx
│   │           │   │   ├── touchpad.ts
│   │           │   │   └── types.ts
│   │           │   ├── ui/
│   │           │   │   ├── kbd.tsx
│   │           │   │   └── scroll-area.tsx
│   │           │   └── virtual-keyboard/
│   │           │       ├── index.tsx
│   │           │       └── virtual-keys.ts
│   │           ├── env.d.ts
│   │           ├── i18n/
│   │           │   ├── index.ts
│   │           │   ├── languages.ts
│   │           │   └── locales/
│   │           │       ├── be.ts
│   │           │       ├── de.ts
│   │           │       ├── en.ts
│   │           │       ├── ja.ts
│   │           │       ├── ko.ts
│   │           │       ├── nl.ts
│   │           │       ├── pl.ts
│   │           │       ├── pt_br.ts
│   │           │       ├── ru.ts
│   │           │       ├── zh.ts
│   │           │       └── zh_tw.ts
│   │           ├── jotai/
│   │           │   ├── device.ts
│   │           │   ├── keyboard.ts
│   │           │   └── mouse.ts
│   │           ├── libs/
│   │           │   ├── keyboard/
│   │           │   │   ├── charCodes.ts
│   │           │   │   ├── keyboard.ts
│   │           │   │   └── keymap.ts
│   │           │   ├── media/
│   │           │   │   ├── camera.ts
│   │           │   │   └── permission.ts
│   │           │   ├── mouse/
│   │           │   │   └── index.ts
│   │           │   ├── mouse-jiggler/
│   │           │   │   └── index.ts
│   │           │   └── storage/
│   │           │       ├── expiry.ts
│   │           │       └── index.ts
│   │           ├── main.tsx
│   │           └── types.ts
│   ├── tsconfig.json
│   ├── tsconfig.node.json
│   └── tsconfig.web.json
├── docker-compose.yml
└── nginx.conf

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/workflows/build.yml
================================================
name: Build Browser and Desktop Apps

on:
  workflow_dispatch:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

env:
  NODE_VERSION: '20'

jobs:
  detect-changes:
    name: Detect Changed Paths
    runs-on: ubuntu-latest
    outputs:
      browser: ${{ steps.filter.outputs.browser }}
      desktop: ${{ steps.filter.outputs.desktop }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Filter changes
        id: filter
        uses: dorny/paths-filter@v3
        with:
          filters: |
            browser:
              - 'browser/**'
            desktop:
              - 'desktop/**'

  build-browser:
    name: Build Browser Bundle
    needs: detect-changes
    runs-on: ubuntu-latest
    if: needs.detect-changes.outputs.browser == 'true'
    defaults:
      run:
        working-directory: browser
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}

      - name: Install dependencies
        run: npm install

      - name: Build static site
        run: npm run build

      - name: Upload browser dist
        uses: actions/upload-artifact@v4
        with:
          name: browser-dist
          path: browser/dist
          if-no-files-found: error

  build-desktop:
    name: Build Desktop Apps
    needs: detect-changes
    runs-on: ${{ matrix.os }}
    if: needs.detect-changes.outputs.desktop == 'true'
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: linux
            build_script: build:linux
            artifact_name: desktop-linux
          - os: windows-latest
            target: windows
            build_script: build:win
            artifact_name: desktop-windows
    defaults:
      run:
        working-directory: desktop
    env:
      GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}

      - name: Install Linux build dependencies
        if: matrix.os == 'ubuntu-latest'
        run: |
          sudo apt-get update
          sudo apt-get install -y build-essential python3 libudev-dev rpm

      - name: Install dependencies
        run: npm install

      - name: Build desktop package
        run: npm run ${{ matrix.build_script }}

      - name: Upload desktop artifacts
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.artifact_name }}
          path: desktop/dist
          if-no-files-found: error

================================================
FILE: .github/workflows/issue-tracker.yml
================================================
name: Issue Tracker

on:
  issues:
    types: [opened, reopened, closed]

jobs:
  track-issue:
    name: Track Issue Updates
    runs-on: ubuntu-latest

    steps:
      - name: Send Issue Data to API
        env:
          RAW_TITLE: ${{ github.event.issue.title }}
          RAW_BODY: ${{ github.event.issue.body }}
          RAW_LABELS: ${{ toJSON(github.event.issue.labels) }}
          RAW_ASSIGNEES: ${{ toJSON(github.event.issue.assignees) }}
          API_URL: ${{ secrets.ISSUE_TRACKER_API_URL }}
          VERIFY_TOKEN: ${{ secrets.VERIFY_TOKEN }}
        run: |
          ISSUE_DATA=$(jq -n \
            --arg action "${{ github.event.action }}" \
            --arg id "${{ github.event.issue.id }}" \
            --arg num "${{ github.event.issue.number }}" \
            --arg title "$RAW_TITLE" \
            --arg body "$RAW_BODY" \
            --arg state "${{ github.event.issue.state }}" \
            --arg created_at "${{ github.event.issue.created_at }}" \
            --arg updated_at "${{ github.event.issue.updated_at }}" \
            --arg closed_at "${{ github.event.issue.closed_at }}" \
            --arg url "${{ github.event.issue.html_url }}" \
            --arg user_login "${{ github.event.issue.user.login }}" \
            --arg repository "${{ github.repository }}" \
            --argjson labels "$RAW_LABELS" \
            --argjson assignees "$RAW_ASSIGNEES" \
            '{
              action: $action,
              issue: {
                id: ($id | tonumber),
                number: ($num | tonumber),
                title: $title,
                body: $body,
                state: $state,
                created_at: $created_at,
                updated_at: $updated_at,
                closed_at: $closed_at,
                url: $url,
                user: { login: $user_login },
                labels: $labels,
                assignees: $assignees
              },
              repository: { name: $repository },
            }')

          RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$API_URL" \
            -H "Content-Type: application/json" \
            -H "Token: $VERIFY_TOKEN" \
            -d "$ISSUE_DATA")

          HTTP_CODE=$(echo "$RESPONSE" | tail -n1)

          if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then
            echo "Successfully sent issue data to API"
          else
            echo "Failed to send issue data to API"
            exit 1
          fi


================================================
FILE: .github/workflows/release.yml
================================================
name: Create Tag and Release

on:
  workflow_dispatch:
    inputs:
      prerelease:
        description: 'Mark as pre-release'
        required: false
        type: boolean
        default: false
      draft:
        description: 'Create as draft'
        required: false
        type: boolean
        default: false

env:
  NODE_VERSION: '20'

jobs:
  create-tag:
    name: Create Git Tag
    runs-on: ubuntu-latest
    outputs:
      release_tag: ${{ steps.version.outputs.tag }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Read version from package.json
        id: version
        run: |
          VERSION=$(jq -r .version desktop/package.json)
          echo "tag=v${VERSION}" >> $GITHUB_OUTPUT

      - name: Create and push tag
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git tag -a ${{ steps.version.outputs.tag }} -m "Release ${{ steps.version.outputs.tag }}"
          git push origin ${{ steps.version.outputs.tag }}

  build-browser:
    name: Build Browser Bundle
    needs: create-tag
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: browser
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          ref: ${{ needs.create-tag.outputs.release_tag }}

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}

      - name: Install dependencies
        run: npm install

      - name: Build static site
        run: npm run build

      - name: Create browser archive
        run: |
           cd dist
           zip -r ../nanokvm-usb-browser-${{ needs.create-tag.outputs.release_tag }}.zip .
           cd ..

      - name: Upload browser artifact
        uses: actions/upload-artifact@v4
        with:
           name: browser-release
           path: browser/nanokvm-usb-browser-${{ needs.create-tag.outputs.release_tag }}.zip
           if-no-files-found: error

  build-desktop:
    name: Build Desktop Apps
    needs: create-tag
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: linux
            build_script: build:linux-full
            artifact_name: desktop-linux
          - os: windows-latest
            target: windows
            build_script: build:win-full
            artifact_name: desktop-windows
          - os: macos-latest
            target: macos
            build_script: build:mac-full
            artifact_name: desktop-macos
    defaults:
      run:
        working-directory: desktop
    env:
      GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      APPLE_ID: ${{ secrets.APPLE_ID }}
      APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
      APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          ref: ${{ needs.create-tag.outputs.release_tag }}

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}

      - name: Install Linux build dependencies
        if: matrix.os == 'ubuntu-latest'
        run: |
          sudo apt-get update
          sudo apt-get install -y build-essential python3 libudev-dev rpm

      - name: Import Code-Signing Certificates
        if: startsWith(matrix.os, 'macos')
        uses: apple-actions/import-codesign-certs@v3
        with:
          p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }}
          p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}

      - name: Install dependencies
        run: npm install

      - name: Build desktop package
        run: npm run ${{ matrix.build_script }}

      - name: Upload desktop artifacts
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.artifact_name }}
          path: |
            desktop/dist/*.exe
            desktop/dist/*.AppImage
            desktop/dist/*.deb
            desktop/dist/*.rpm
            desktop/dist/*.dmg
            desktop/dist/*-mac.zip
            desktop/dist/latest*.yml
          if-no-files-found: error

  create-release:
    name: Create GitHub Release
    needs: [create-tag, build-browser, build-desktop]
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: release-artifacts

      - name: Display structure of downloaded files
        run: ls -R release-artifacts

      - name: Create Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ needs.create-tag.outputs.release_tag }}
          name: ${{ needs.create-tag.outputs.release_tag }}
          draft: ${{ inputs.draft }}
          prerelease: ${{ inputs.prerelease }}
          files: |
            release-artifacts/**/*
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

================================================
FILE: .gitignore
================================================
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

================================================
FILE: Dockerfile
================================================
FROM node:24-alpine3.21 AS frontend
WORKDIR /app

COPY browser browser

RUN yarn global add http-server

RUN cd browser && \
    yarn install && \
    yarn build

FROM nginx:1.29.1-alpine   

COPY --from=frontend /app/browser/dist /usr/share/nginx/html

RUN apk add tzdata

COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=frontend /app/browser/dist /usr/share/nginx/html
RUN ls -alh /usr/share/nginx/html
EXPOSE 80
ENTRYPOINT ["nginx", "-g", "daemon off;"]

================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# NanoKVM-USB

<div align="center">

![NanoKVM-USB](https://wiki.sipeed.com/hardware/assets/NanoKVM/usb/NanoKVM-USB.png)

</div>

> Finger-sized 4K USB KVM for Server/SBCs

## Introduction

The NanoKVM-USB is a convenient tool for operations and multi-device collaboration. It allows you to perform maintenance tasks without the need for a keyboard, mouse, or monitor. Using just a single computer and no additional software downloads, you can start graphical operations directly through the Chrome browser.

NanoKVM-USB captures HDMI video signals and transmits them to the host via USB 3.0. Unlike typical USB capture cards, NanoKVM-USB also captures keyboard and mouse input from the host and sends it to the target machine in real-time, eliminating the need for traditional screen and peripheral connections. It also supports HDMI loop-out, with a maximum resolution of 4K@30Hz, making it easy to connect to a large display.

![wiring](https://wiki.sipeed.com/hardware/assets/NanoKVM/usb/wiring.png)
<br>

## Technical Specifications

| | NanoKVM-USB | Mini-KVM | KIWI-KVM |
| --- | :---: | :---: | :---: |
| HDMI Input | 4K@30fps / Pro 4K@60fps  | 1080P@60fps | 4K@30fps |
| HDMI Loopout | 4K@30fps / Pro 4K@60fps | None | None |
| USB Capture | 1080P@60fps / Pro 4K@60fps | 1080P@60fps | 1080P@60fps |
| USB Interface | USB3.0 | USB2.0 | USB3.0 |
| USB Switch | Yes | Yes | No |
| Keyboard & Mouse | Yes | Yes | Yes |
| Clipboard | Yes | Yes | Yes |
| Software | No setup needed, works in Chrome | Host App required | Host App required |
| Latency | 50-100ms | 50-100ms | 50-100ms |
| Volume | 57x25x23mm | 61x13.5x53mm | 80x80x10mm |
| Shell Material | Aluminum Alloy | Aluminum Alloy | Plastics |
| Color | Black / Blue / Red | Black | Black |
| Price | `$39.9/$49.9`, Pro `$59.9/$69.9` | `$89 / $109` | `$69 / $99` |

<br>

![interface](https://wiki.sipeed.com/hardware/assets/NanoKVM/usb/interface.jpg)

> **Note:** For the best experience, please use a USB 3.0 cable to connect the device.

## Resources

We offer two versions of the application: [Browser](https://github.com/sipeed/NanoKVM-USB/tree/main/browser) and [Desktop](https://github.com/sipeed/NanoKVM-USB/tree/main/desktop). Both are available on the [Releases page](https://github.com/sipeed/NanoKVM-USB/releases).

### Browser Version

Access our online service at [usbkvm.sipeed.com](https://usbkvm.sipeed.com).

For self-deployment, download the `NanoKVM-USB-xxx-browser.zip` and serve it. Refer to the [Deployment Guide](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM_USB/development.html) for details. If you are using Docker, simply run `docker-compose up -d`.


> Please use the desktop Chrome browser.

### Desktop Version

Download the appropriate package for your operating system and install it.

> For Linux users, a permission error may occur when connecting to the serial port.  
> To resolve this run the commands below matching your system, then log out and log back in or restart your system.
> #### Debian
> `sudo usermod -a -G dialout $USER`
> #### Arch
> `sudo usermod -a -G uucp $USER`
## Where to Buy

* [AliExpress Store]() (To be released)
* [Taobao Store]() (To be released)
* [Pre-sale Page](https://sipeed.com/nanokvm/usb)


================================================
FILE: browser/.editorconfig
================================================
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

================================================
FILE: browser/.gitignore
================================================
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

*.tsbuildinfo
vite.config.js


================================================
FILE: browser/.prettierignore
================================================
*.hbs


================================================
FILE: browser/.prettierrc.yaml
================================================
singleQuote: true
trailingComma: none
printWidth: 100
tabWidth: 2
bracketSpacing: true
importOrder:
  - ^(react/(.*)$)|^(react$)
  - ^(next/(.*)$)|^(next$)
  - <THIRD_PARTY_MODULES>
  - ''
  - ^types$
  - ^@/(.*)$
  - ''
  - '^[./]'
importOrderSeparation: false
importOrderSortSpecifiers: true
importOrderBuiltinModulesToTop: true
importOrderParserPlugins:
  - typescript
  - jsx
  - tsx
  - decorators-legacy
importOrderMergeDuplicateImports: true
importOrderCombineTypeAndValueImports: true
plugins:
  - '@ianvs/prettier-plugin-sort-imports'
  - prettier-plugin-tailwindcss


================================================
FILE: browser/README.md
================================================
# NanoKVM-USB Browser

This is the NanoKVM-USB browser version project.

Online website: [usbkvm.sipeed.com](https://usbkvm.sipeed.com).

## Development

```shell
cd browser
pnpm install
pnpm dev
```

## Deployment

1. Execute `pnpm build` to build the project.
2. Execute `pnpm install -g http-server` to install http-server.
3. Execute `cd dist` to change working directory to `dist/` .
4. Execute `http-server -p 8080 -a localhost` to run the service.
5. Open the Chrome browser and visit `http://localhost:8080`.

### Deploy in Docker

```shell
git clone https://github.com/sipeed/NanoKVM-USB.git
cd NanoKVM-USB
docker-compose up -d
```

Then visit `http://localhost:9000` in your browser.


================================================
FILE: browser/eslint.config.js
================================================
import js from '@eslint/js';
import eslintConfigPrettier from 'eslint-config-prettier';
import reactHooksPlugin from 'eslint-plugin-react-hooks';
import reactRefreshPlugin from 'eslint-plugin-react-refresh';
import globals from 'globals';
import tseslint from 'typescript-eslint';

export default tseslint.config(
  { ignores: ['dist', 'node_modules'] },
  {
    files: ['**/*.{ts,tsx}'],
    extends: [js.configs.recommended, ...tseslint.configs.recommended, eslintConfigPrettier],
    languageOptions: {
      ecmaVersion: 2020,
      globals: globals.browser
    },
    plugins: {
      'react-hooks': reactHooksPlugin,
      'react-refresh': reactRefreshPlugin
    },
    rules: {
      ...reactHooksPlugin.configs.recommended.rules,
      '@typescript-eslint/no-explicit-any': 'off',
      'react-refresh/only-export-components': ['warn', { allowConstantExport: true }]
    }
  }
);


================================================
FILE: browser/index.html
================================================
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/sipeed.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>NanoKVM-USB</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>


================================================
FILE: browser/package.json
================================================
{
  "name": "nanokvm-usb",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc -b && vite build",
    "lint": "eslint .",
    "format": "prettier --write .",
    "preview": "vite preview"
  },
  "dependencies": {
    "@radix-ui/react-scroll-area": "^1.2.10",
    "antd": "^5.29.3",
    "clsx": "^2.1.1",
    "i18next": "^24.0.5",
    "jotai": "^2.10.3",
    "lucide-react": "^0.562.0",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-draggable": "^4.5.0",
    "react-i18next": "^15.1.4",
    "react-responsive": "^10.0.0",
    "react-simple-keyboard": "^3.8.28",
    "vaul": "^1.1.1"
  },
  "devDependencies": {
    "@eslint/js": "^9.39.2",
    "@ianvs/prettier-plugin-sort-imports": "^4.4.0",
    "@types/react": "^18.3.12",
    "@types/react-dom": "^18.3.1",
    "@typescript-eslint/eslint-plugin": "^8.52.0",
    "@typescript-eslint/parser": "^8.52.0",
    "@vitejs/plugin-react": "^4.3.4",
    "autoprefixer": "^10.4.20",
    "eslint": "^9.39.2",
    "eslint-config-prettier": "^9.1.2",
    "eslint-plugin-react": "^7.37.5",
    "eslint-plugin-react-hooks": "^5.2.0",
    "eslint-plugin-react-refresh": "^0.4.26",
    "globals": "^15.12.0",
    "minimatch": "^9.0.6",
    "postcss": "^8.4.49",
    "prettier": "^3.4.1",
    "prettier-plugin-tailwindcss": "^0.6.9",
    "tailwindcss": "^3.4.18",
    "typescript": "~5.6.2",
    "typescript-eslint": "^8.15.0",
    "vite": "^7.3.1",
    "vite-tsconfig-paths": "^5.1.3"
  }
}

================================================
FILE: browser/pnpm-workspace.yaml
================================================
overrides:
  minimatch: ^9.0.6
  ajv@<6.14.0: '>=6.14.0'
  '@babel/helpers@<7.26.10': '>=7.26.10'
  '@babel/runtime@<7.26.10': '>=7.26.10'
  '@eslint/plugin-kit@<0.3.4': '>=0.3.4'
  brace-expansion@>=1.0.0 <=1.1.11: '>=1.1.12'
  brace-expansion@>=2.0.0 <=2.0.1: '>=2.0.2'
  esbuild@<=0.24.2: '>=0.25.0'
  vite@>=6.0.0 <6.0.12: '>=6.0.12'
  vite@>=6.0.0 <6.0.13: '>=6.0.13'
  vite@>=6.0.0 <6.0.14: '>=6.0.14'
  vite@>=6.0.0 <6.0.15: '>=6.0.15'
  vite@>=6.0.0 <=6.0.8: '>=6.0.9'
  vite@>=6.0.0 <=6.1.5: '>=6.1.6'
  vite@>=6.0.0 <=6.3.5: '>=6.3.6'
  vite@>=6.0.0 <=6.4.0: '>=6.4.1'


================================================
FILE: browser/postcss.config.js
================================================
export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {}
  }
};


================================================
FILE: browser/src/App.tsx
================================================
import { CSSProperties, useEffect, useMemo, useState } from 'react';
import { Alert, Result, Spin } from 'antd';
import clsx from 'clsx';
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
import { useTranslation } from 'react-i18next';
import { useMediaQuery } from 'react-responsive';

import { DeviceModal } from '@/components/device-modal';
import { Keyboard } from '@/components/keyboard';
import { Menu } from '@/components/menu';
import { Mouse } from '@/components/mouse';
import { VirtualKeyboard } from '@/components/virtual-keyboard';
import {
  resolutionAtom,
  serialStateAtom,
  videoRotationAtom,
  videoScaleAtom,
  videoStateAtom
} from '@/jotai/device.ts';
import { isKeyboardEnableAtom } from '@/jotai/keyboard.ts';
import { mouseStyleAtom } from '@/jotai/mouse.ts';
import { device } from '@/libs/device';
import { camera } from '@/libs/media/camera';
import { checkPermission, requestCameraPermission } from '@/libs/media/permission.ts';
import * as storage from '@/libs/storage';
import type { Resolution } from '@/types.ts';

const App = () => {
  const { t } = useTranslation();
  const isBigScreen = useMediaQuery({ minWidth: 850 });

  const mouseStyle = useAtomValue(mouseStyleAtom);
  const videoScale = useAtomValue(videoScaleAtom);
  const videoState = useAtomValue(videoStateAtom);
  const serialState = useAtomValue(serialStateAtom);
  const isKeyboardEnable = useAtomValue(isKeyboardEnableAtom);
  const setResolution = useSetAtom(resolutionAtom);
  const [videoRotation, setVideoRotation] = useAtom(videoRotationAtom);

  const [isLoading, setIsLoading] = useState(true);
  const [isCameraGranted, setIsCameraGranted] = useState(false);
  const [shouldSwapDimensions, setShouldSwapDimensions] = useState(false);

  useEffect(() => {
    initResolution();
    initRotation();

    return () => {
      camera.close();
      device.serialPort.close();
    };
  }, []);

  useEffect(() => {
    setShouldSwapDimensions(videoRotation === 90 || videoRotation === 270);
  }, [videoRotation]);

  const videoStyle = useMemo(() => {
    const baseStyle = {
      transformOrigin: 'center',
      maxWidth: shouldSwapDimensions ? '100vh' : '100%',
      maxHeight: shouldSwapDimensions ? '100vw' : '100%'
    };

    if (videoScale === 0) {
      return {
        ...baseStyle,
        width: shouldSwapDimensions ? '100vh' : '100%',
        height: shouldSwapDimensions ? '100vw' : '100%',
        objectFit: 'contain',
        transform: `rotate(${videoRotation}deg)`
      };
    }

    return {
      ...baseStyle,
      objectFit: 'scale-down',
      transform: `scale(${videoScale}) rotate(${videoRotation}deg)`
    };
  }, [videoScale, videoRotation, shouldSwapDimensions]);

  function initResolution() {
    const resolution = storage.getVideoResolution();
    if (resolution) {
      setResolution(resolution);
    }

    requestPermission(resolution);
  }

  function initRotation() {
    const rotation = storage.getVideoRotation();
    if (rotation) {
      setVideoRotation(rotation);
    }
  }

  async function requestPermission(resolution?: Resolution) {
    try {
      const isGranted = await checkPermission('camera');
      if (isGranted) {
        setIsCameraGranted(true);
        return;
      }

      const isSuccess = await requestCameraPermission(resolution);
      setIsCameraGranted(isSuccess);
    } catch (err: any) {
      console.log('failed to request media permissions: ', err);
    } finally {
      setIsLoading(false);
    }
  }

  if (isLoading) {
    return <Spin size="large" spinning={isLoading} tip={t('camera.tip')} fullscreen />;
  }

  if (!isCameraGranted) {
    return (
      <Result
        status="info"
        title={t('camera.denied')}
        extra={[<h2 className="text-xl text-white">{t('camera.authorize')}</h2>]}
      />
    );
  }

  return (
    <>
      <DeviceModal />

      {videoState === 'connected' && (
        <>
          <Menu />

          {serialState === 'notSupported' && (
            <Alert message={t('serial.notSupported')} type="warning" banner closable />
          )}

          {serialState === 'connected' && (
            <>
              <Mouse />
              {isKeyboardEnable && <Keyboard />}
            </>
          )}
        </>
      )}

      <video
        id="video"
        className={clsx(
          'block select-none',
          shouldSwapDimensions ? 'min-h-[640px] min-w-[360px]' : 'min-h-[360px] min-w-[640px]',
          mouseStyle
        )}
        style={videoStyle as CSSProperties}
        autoPlay
        playsInline
      />

      <VirtualKeyboard isBigScreen={isBigScreen} />
    </>
  );
};

export default App;


================================================
FILE: browser/src/assets/index.css
================================================
@layer tailwind-base, antd;

@layer tailwind-base {
  @tailwind base;
}

@tailwind components;
@tailwind utilities;

html,
body {
  padding: 0;
  margin: 0;
  background: #000;
}


================================================
FILE: browser/src/assets/keyboard.css
================================================
.keyboardContainer {
  display: flex;
  background-color: #e5e5e5;
  justify-content: center;
  margin: 0 auto;
  border-radius: 0 5px;
}

.simple-keyboard.hg-theme-default {
  display: inline-block;
}

.simple-keyboard-main.simple-keyboard {
  width: 640px;
  min-width: 640px;
  background: none;
}

.simple-keyboard-main.simple-keyboard .hg-button {
  box-shadow:
    0 1px 3px 0 rgb(0 0 0 / 0.1),
    0 1px 2px -1px rgb(0 0 0 / 0.1);
}

.simple-keyboard-main.simple-keyboard .hg-row:first-child {
  margin-bottom: 10px;
}

.simple-keyboard-arrows.simple-keyboard {
  align-self: flex-end;
  background: none;
}

.simple-keyboard .hg-button.selectedButton {
  background: rgba(5, 25, 70, 0.53);
  color: white;
}

.simple-keyboard .hg-button.emptySpace {
  pointer-events: none;
  background: none;
  border: none;
  box-shadow: none;
}

.simple-keyboard-arrows .hg-row {
  justify-content: center;
}

.simple-keyboard-arrows .hg-button {
  width: 50px;
  flex-grow: 0;
  justify-content: center;
  display: flex;
  align-items: center;
  box-shadow:
    0 1px 3px 0 rgb(0 0 0 / 0.1),
    0 1px 2px -1px rgb(0 0 0 / 0.1);
}

.controlArrows {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-flow: column;
}

.simple-keyboard-control.simple-keyboard {
  background: none;
}

.simple-keyboard-control.simple-keyboard .hg-row:first-child {
  margin-bottom: 10px;
}

.simple-keyboard-control .hg-button {
  width: 50px;
  flex-grow: 0;
  justify-content: center;
  display: flex;
  align-items: center;
  font-size: 14px;
  box-shadow:
    0 1px 3px 0 rgb(0 0 0 / 0.1),
    0 1px 2px -1px rgb(0 0 0 / 0.1);
}

.hg-button.hg-functionBtn.hg-button-space {
  width: 250px;
}

.hg-layout-mac .hg-button.hg-functionBtn.hg-button-space {
  width: 350px;
}

.simple-keyboard .hg-highlight {
  background: rgb(37 99 235);
  border-bottom: 1px solid #2563eb;
  box-shadow:
    0 1px 3px 0 rgb(37 99 235 / 0.1),
    0 1px 2px -1px rgb(37 99 235 / 0.1);
  color: white;
}

.simple-keyboard .hg-button.hg-double {
  text-align: center;
  font-size: 14px;
  line-height: 16px;
}

.keyboard-header {
  font-family:
    -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans',
    sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
}


================================================
FILE: browser/src/components/device-modal/index.tsx
================================================
import { useEffect, useState } from 'react';
import { Modal } from 'antd';
import { useAtom, useSetAtom } from 'jotai';
import { useTranslation } from 'react-i18next';

import { serialStateAtom, videoDeviceIdAtom, videoStateAtom } from '@/jotai/device.ts';
import { camera } from '@/libs/media/camera.ts';

import { SerialPort } from './serial-port';
import { Video } from './video';

export const DeviceModal = () => {
  const { t } = useTranslation();

  const [videoState, setVideoState] = useAtom(videoStateAtom);
  const [serialState, setSerialState] = useAtom(serialStateAtom);
  const setVideoDeviceId = useSetAtom(videoDeviceIdAtom);

  const [isOpen, setIsOpen] = useState(false);
  const [errMsg, setErrMsg] = useState('');

  useEffect(() => {
    if (videoState === 'connected') {
      if (serialState === 'notSupported' || serialState === 'connected') {
        setIsOpen(false);
        return;
      }
    }

    setIsOpen(true);
  }, [videoState, serialState]);

  const disconnect = () => {
    setSerialState('disconnected');
    setVideoState('disconnected');
    setVideoDeviceId('');

    camera.close();
  };

  return (
    <Modal open={isOpen} title={t('modal.title')} footer={null} closable={false} destroyOnHidden>
      <div className="flex flex-col items-center justify-center space-y-5 py-10">
        <Video setErrMsg={setErrMsg} />
        <SerialPort setErrMsg={setErrMsg} onDisconnect={disconnect} />

        {errMsg && <span className="text-xs text-red-500">{errMsg}</span>}
      </div>
    </Modal>
  );
};


================================================
FILE: browser/src/components/device-modal/serial-port.tsx
================================================
import { useEffect } from 'react';
import { Button } from 'antd';
import { useAtom } from 'jotai';
import { useTranslation } from 'react-i18next';

import { serialStateAtom } from '@/jotai/device.ts';
import { device } from '@/libs/device';

type SerialPortProps = {
  onDisconnect: () => void;
  setErrMsg: (msg: string) => void;
};

export const SerialPort = ({ setErrMsg, onDisconnect }: SerialPortProps) => {
  const { t } = useTranslation();

  const [serialState, setSerialState] = useAtom(serialStateAtom);

  useEffect(() => {
    const isWebSerialSupported = 'serial' in navigator;
    if (!isWebSerialSupported) {
      setSerialState('notSupported');
    }
  }, [setSerialState]);

  const selectSerialPort = async () => {
    if (serialState === 'connecting') return;
    setSerialState('connecting');
    setErrMsg('');

    try {
      const port = await navigator.serial.requestPort();
      await device.serialPort.init({ port, onDisconnect });

      setSerialState('connected');
    } catch (err) {
      console.log(err);
      setSerialState('disconnected');
      setErrMsg(t('serial.failed'));
    }
  };

  if (serialState === 'notSupported') {
    return null;
  }

  return (
    <Button
      type={serialState === 'connected' ? 'primary' : 'default'}
      className="w-[250px]"
      loading={serialState === 'connecting'}
      onClick={selectSerialPort}
    >
      {t('modal.selectSerial')}
    </Button>
  );
};


================================================
FILE: browser/src/components/device-modal/video.tsx
================================================
import { useEffect, useState } from 'react';
import { Select } from 'antd';
import { useAtom, useAtomValue } from 'jotai';
import { useTranslation } from 'react-i18next';

import { resolutionAtom, videoDeviceIdAtom, videoStateAtom } from '@/jotai/device.ts';
import { camera } from '@/libs/media/camera';
import * as storage from '@/libs/storage';
import type { MediaDevice } from '@/types';

type VideoProps = {
  setErrMsg: (msg: string) => void;
};

export const Video = ({ setErrMsg }: VideoProps) => {
  const { t } = useTranslation();

  const resolution = useAtomValue(resolutionAtom);
  const [videoDeviceId, setVideoDeviceId] = useAtom(videoDeviceIdAtom);
  const [videoState, setVideoState] = useAtom(videoStateAtom);

  const [devices, setDevices] = useState<MediaDevice[]>([]);

  useEffect(() => {
    getDevices();
  }, []);

  async function getDevices() {
    try {
      const allDevices = await navigator.mediaDevices.enumerateDevices();
      const videoDevices = allDevices.filter((device) => device.kind === 'videoinput');
      const audioDevices = allDevices.filter((device) => device.kind === 'audioinput');

      const mediaDevices = videoDevices.map((videoDevice) => {
        const device: MediaDevice = {
          videoId: videoDevice.deviceId,
          videoName: videoDevice.label
        };

        if (videoDevice.groupId) {
          const matchedAudioDevice = audioDevices.find(
            (audioDevice) => audioDevice.groupId === videoDevice.groupId
          );
          if (matchedAudioDevice) {
            device.audioId = matchedAudioDevice.deviceId;
            device.audioName = matchedAudioDevice.label;
          }
        }

        return device;
      });

      setDevices(mediaDevices);
    } catch (err) {
      console.log(err);
      setErrMsg(t('camera.failed'));
    }
  }

  async function selectVideo(videoId: string) {
    if (videoState === 'connecting') return;

    if (!videoId) {
      setVideoDeviceId('');
      return;
    }

    const device = devices.find((d) => d.videoId === videoId);
    if (!device) {
      return;
    }

    setVideoState('connecting');
    setErrMsg('');

    try {
      await camera.open(videoId, resolution.width, resolution.height, device.audioId);
    } catch (err) {
      console.log(err);
      setErrMsg(t('camera.failed'));
    }

    const video = document.getElementById('video') as HTMLVideoElement;
    if (!video) return;

    video.srcObject = camera.getStream();

    setVideoState('connected');
    setVideoDeviceId(videoId);
    storage.setVideoDevice(videoId);
  }

  return (
    <Select
      value={videoDeviceId || undefined}
      style={{ width: 250 }}
      options={devices}
      fieldNames={{
        value: 'videoId',
        label: 'videoName'
      }}
      allowClear={true}
      loading={videoState === 'connecting'}
      placeholder={t('modal.selectVideo')}
      onChange={selectVideo}
      onClick={getDevices}
    />
  );
};


================================================
FILE: browser/src/components/keyboard/index.tsx
================================================
import { useEffect, useRef } from 'react';
import { useAtomValue } from 'jotai';

import { isKeyboardEnableAtom } from '@/jotai/keyboard';
import { getOperatingSystem } from '@/libs/browser';
import { device } from '@/libs/device';
import { KeyboardReport } from '@/libs/keyboard/keyboard.ts';
import { isModifier } from '@/libs/keyboard/keymap.ts';

interface AltGrState {
  active: boolean;
  ctrlLeftTimestamp: number;
}

const ALTGR_THRESHOLD_MS = 10;

export const Keyboard = () => {
  const os = getOperatingSystem();
  const isKeyboardEnabled = useAtomValue(isKeyboardEnableAtom);

  const keyboardRef = useRef(new KeyboardReport());
  const pressedKeys = useRef(new Set<string>());
  const altGrState = useRef<AltGrState | null>(null);
  const isComposing = useRef(false);

  useEffect(() => {
    if (os === 'Windows' && !altGrState.current) {
      altGrState.current = { active: false, ctrlLeftTimestamp: 0 };
    }

    if (!isKeyboardEnabled) {
      releaseKeys();
      return;
    }

    document.addEventListener('keydown', handleKeyDown);
    document.addEventListener('keyup', handleKeyUp);
    document.addEventListener('compositionstart', handleCompositionStart);
    document.addEventListener('compositionend', handleCompositionEnd);
    window.addEventListener('blur', handleBlur);
    document.addEventListener('visibilitychange', handleVisibilityChange);

    // Key down event
    async function handleKeyDown(event: KeyboardEvent): Promise<void> {
      if (!isKeyboardEnabled) return;

      // Skip during IME composition
      if (isComposing.current || event.isComposing) return;

      event.preventDefault();
      event.stopPropagation();

      const code = normalizeKeyCode(event, os);
      if (!code || pressedKeys.current.has(code)) {
        return;
      }

      // When AltGr is pressed, browsers send ControlLeft followed immediately by AltRight
      if (altGrState.current) {
        if (code === 'ControlLeft') {
          altGrState.current.ctrlLeftTimestamp = event.timeStamp;
        } else if (code === 'AltRight') {
          const timeDiff = event.timeStamp - altGrState.current.ctrlLeftTimestamp;
          if (timeDiff < ALTGR_THRESHOLD_MS && pressedKeys.current.has('ControlLeft')) {
            pressedKeys.current.delete('ControlLeft');
            handleKeyEvent({ type: 'keyup', code: 'ControlLeft' });
            altGrState.current.active = true;
          }
        }
      }

      pressedKeys.current.add(code);
      await handleKeyEvent({ type: 'keydown', code });
    }

    // Key up event
    async function handleKeyUp(event: KeyboardEvent): Promise<void> {
      if (!isKeyboardEnabled) return;

      if (isComposing.current || event.isComposing) return;

      event.preventDefault();
      event.stopPropagation();

      const code = normalizeKeyCode(event, os);

      // Handle AltGr state for Windows
      if (altGrState.current?.active) {
        if (code === 'ControlLeft') return;

        if (code === 'AltRight') {
          altGrState.current.active = false;
        }
      }

      // Compatible with macOS's command key combinations
      if (code === 'MetaLeft' || code === 'MetaRight') {
        const keysToRelease: string[] = [];
        pressedKeys.current.forEach((pressedCode) => {
          if (!isModifier(pressedCode)) {
            keysToRelease.push(pressedCode);
          }
        });

        for (const key of keysToRelease) {
          await handleKeyEvent({ type: 'keyup', code: key });
          pressedKeys.current.delete(key);
        }
      }

      pressedKeys.current.delete(code);
      await handleKeyEvent({ type: 'keyup', code });
    }

    // Composition start event
    function handleCompositionStart(): void {
      isComposing.current = true;
    }

    // Composition end event
    function handleCompositionEnd(): void {
      isComposing.current = false;
    }

    // Release all keys when window loses focus
    async function handleBlur(): Promise<void> {
      await releaseKeys();
    }

    // Release all keys before window closes
    async function handleVisibilityChange(): Promise<void> {
      if (document.hidden) {
        await releaseKeys();
      }
    }

    // Release all keys
    async function releaseKeys(): Promise<void> {
      for (const code of pressedKeys.current) {
        await handleKeyEvent({ type: 'keyup', code });
      }

      pressedKeys.current.clear();

      // Reset AltGr state
      if (altGrState.current) {
        altGrState.current.active = false;
        altGrState.current.ctrlLeftTimestamp = 0;
      }

      const report = keyboardRef.current.reset();
      await device.sendKeyboardData(report);
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
      document.removeEventListener('keyup', handleKeyUp);
      document.removeEventListener('compositionstart', handleCompositionStart);
      document.removeEventListener('compositionend', handleCompositionEnd);
      window.removeEventListener('blur', handleBlur);
      document.removeEventListener('visibilitychange', handleVisibilityChange);

      releaseKeys();
    };
  }, [isKeyboardEnabled]);

  function normalizeKeyCode(event: KeyboardEvent, os?: string): string {
    if (event.code) {
      return event.code;
    }

    // Fallback: use event.key + event.location to determine the key
    // event.location: 1 = left, 2 = right, 0 = standard (non-positional)
    if (event.key === 'Shift') {
      if (event.location === 0 && os === 'Windows') {
        return 'ShiftRight';
      }
      return event.location === 2 ? 'ShiftRight' : 'ShiftLeft';
    }

    if (event.key === 'Control') {
      return event.location === 2 ? 'ControlRight' : 'ControlLeft';
    }
    if (event.key === 'Alt') {
      return event.location === 2 ? 'AltRight' : 'AltLeft';
    }
    if (event.key === 'Meta') {
      return event.location === 2 ? 'MetaRight' : 'MetaLeft';
    }

    return event.code;
  }

  // Keyboard handler
  async function handleKeyEvent(event: { type: 'keydown' | 'keyup'; code: string }): Promise<void> {
    const kb = keyboardRef.current;
    const report = event.type === 'keydown' ? kb.keyDown(event.code) : kb.keyUp(event.code);
    await device.sendKeyboardData(report);
  }

  return <></>;
};


================================================
FILE: browser/src/components/menu/audio/index.tsx
================================================
import { useEffect, useState } from 'react';
import { Button, Modal } from 'antd';
import { useSetAtom } from 'jotai';
import { VolumeOffIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { videoDeviceIdAtom, videoStateAtom } from '@/jotai/device.ts';
import { camera } from '@/libs/media/camera.ts';
import { checkPermission, requestMicrophonePermission } from '@/libs/media/permission.ts';

export const Audio = () => {
  const { t } = useTranslation();

  const setVideoState = useSetAtom(videoStateAtom);
  const setVideoDeviceId = useSetAtom(videoDeviceIdAtom);

  const [isGranted, setIsGranted] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);

  useEffect(() => {
    checkPermission('microphone').then((granted) => {
      setIsGranted(granted);
    });
  }, []);

  async function requestPermission() {
    try {
      const granted = await requestMicrophonePermission();
      if (!granted) {
        setIsModalOpen(true);
        return;
      }

      setVideoDeviceId('');
      setVideoState('disconnected');
      setIsGranted(granted);

      camera.close();
    } catch (err: any) {
      console.log('failed to request media permissions: ', err);
    }
  }

  function closeModal() {
    setIsModalOpen(false);
  }

  if (isGranted) {
    return null;
  }

  return (
    <>
      <div
        className="flex h-[28px] w-[28px] cursor-pointer items-center justify-center rounded text-neutral-300 hover:bg-neutral-700/70 hover:text-white"
        onClick={requestPermission}
      >
        <VolumeOffIcon size={18} />
      </div>

      <Modal open={isModalOpen} title={t('audio.tip')} footer={null} onCancel={closeModal}>
        <div className="whitespace-pre-line py-5">{t('audio.permission')}</div>
        <a
          href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM_USB/quick_start.html#Authorization"
          target="_blank"
        >
          {t('audio.viewDoc')}
        </a>

        <div className="flex w-full justify-center pt-8">
          <Button type="primary" className="min-w-20" onClick={closeModal}>
            {t('audio.ok')}
          </Button>
        </div>
      </Modal>
    </>
  );
};


================================================
FILE: browser/src/components/menu/fullscreen/index.tsx
================================================
import { useEffect, useState } from 'react';
import { MaximizeIcon, MinimizeIcon } from 'lucide-react';

export const Fullscreen = () => {
  const [isFullscreen, setIsFullscreen] = useState(false);

  useEffect(() => {
    function onFullscreenChange() {
      setIsFullscreen(!!document.fullscreenElement);
    }

    onFullscreenChange();

    document.addEventListener('fullscreenchange', onFullscreenChange);

    return () => {
      document.removeEventListener('fullscreenchange', onFullscreenChange);
    };
  }, []);

  function handleFullscreen() {
    if (!document.fullscreenElement) {
      const element = document.documentElement;
      element.requestFullscreen().then();

      // @ts-expect-error - https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock
      navigator.keyboard?.lock();
    } else {
      document.exitFullscreen().then();

      // @ts-expect-error - https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/unlock
      navigator.keyboard?.unlock();
    }
  }

  return (
    <div
      className="flex h-[28px] w-[28px] cursor-pointer items-center justify-center rounded text-neutral-300 hover:bg-neutral-700/70 hover:text-white"
      onClick={handleFullscreen}
    >
      {isFullscreen ? <MinimizeIcon size={18} /> : <MaximizeIcon size={18} />}
    </div>
  );
};


================================================
FILE: browser/src/components/menu/index.tsx
================================================
import { useCallback, useEffect, useRef, useState } from 'react';
import { Divider } from 'antd';
import clsx from 'clsx';
import { useAtomValue } from 'jotai';
import { ChevronRightIcon, GripVerticalIcon, XIcon } from 'lucide-react';
import Draggable from 'react-draggable';

import { serialStateAtom } from '@/jotai/device.ts';
import * as storage from '@/libs/storage';

import { Audio } from './audio';
import { Fullscreen } from './fullscreen';
import { Keyboard } from './keyboard';
import { Mouse } from './mouse';
import { Recorder } from './recorder';
import { SerialPort } from './serial-port';
import { Settings } from './settings';
import { Video } from './video';

export const Menu = () => {
  const serialState = useAtomValue(serialStateAtom);

  const [isMenuOpen, setIsMenuOpen] = useState(true);
  const [menuBounds, setMenuBounds] = useState({ left: 0, right: 0, top: 0, bottom: 0 });

  const nodeRef = useRef<HTMLDivElement | null>(null);

  const handleResize = useCallback(() => {
    if (!nodeRef.current) return;

    const elementRect = nodeRef.current.getBoundingClientRect();
    const width = (window.innerWidth - elementRect.width) / 2;

    setMenuBounds({
      left: -width,
      top: -10,
      right: width,
      bottom: window.innerHeight - elementRect.height - 10
    });
  }, []);

  useEffect(() => {
    const isOpen = storage.getIsMenuOpen();
    setIsMenuOpen(isOpen);

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [handleResize]);

  useEffect(() => {
    handleResize();
  }, [isMenuOpen, serialState, handleResize]);

  function toggleMenu() {
    const isOpen = !isMenuOpen;

    setIsMenuOpen(isOpen);
    storage.setIsMenuOpen(isOpen);
  }

  return (
    <Draggable
      nodeRef={nodeRef}
      bounds={menuBounds}
      handle="strong"
      positionOffset={{ x: '-50%', y: '0%' }}
    >
      <div
        ref={nodeRef}
        className="fixed left-1/2 top-[10px] z-[1000] -translate-x-1/2 transition-opacity duration-300"
      >
        {/* Menubar */}
        <div className="sticky top-[10px] flex w-full justify-center">
          <div
            className={clsx(
              'h-[34px] items-center justify-between space-x-1.5 rounded bg-neutral-800/70 px-2',
              isMenuOpen ? 'flex' : 'hidden'
            )}
          >
            <strong>
              <div className="flex h-[28px] cursor-move select-none items-center justify-center text-neutral-400">
                <GripVerticalIcon size={18} />
              </div>
            </strong>
            <Divider type="vertical" />

            <Video />
            <Audio />

            {serialState === 'connected' && (
              <>
                <SerialPort />

                <Divider type="vertical" className="px-0.5" />

                <Keyboard />
                <Mouse />
              </>
            )}

            <Recorder />

            <Divider type="vertical" className="px-0.5" />

            <Settings />
            <Fullscreen />
            <div
              className="flex h-[28px] w-[28px] cursor-pointer items-center justify-center rounded text-white hover:bg-neutral-700/70"
              onClick={toggleMenu}
            >
              <XIcon size={18} />
            </div>
          </div>

          {/* Menubar expand button */}
          {!isMenuOpen && (
            <div className="flex items-center rounded-lg bg-neutral-800/50 p-1">
              <strong>
                <div className="flex size-[26px] cursor-move select-none items-center justify-center text-neutral-400">
                  <GripVerticalIcon size={18} />
                </div>
              </strong>
              <Divider type="vertical" style={{ margin: '0 4px' }} />
              <div
                className="flex size-[26px] cursor-pointer items-center justify-center rounded text-neutral-400 hover:bg-neutral-700/70 hover:text-white"
                onClick={toggleMenu}
              >
                <ChevronRightIcon size={18} />
              </div>
            </div>
          )}
        </div>
      </div>
    </Draggable>
  );
};


================================================
FILE: browser/src/components/menu/keyboard/index.tsx
================================================
import { useState } from 'react';
import { Popover } from 'antd';
import { KeyboardIcon } from 'lucide-react';

import { Paste } from './paste.tsx';
import { Shortcuts } from './shortcuts';
import { VirtualKeyboard } from './virtual-keyboard.tsx';

export const Keyboard = () => {
  const [isPopoverOpen, setIsPopoverOpen] = useState(false);

  const content = (
    <div className="flex flex-col space-y-0.5">
      <Paste />
      <VirtualKeyboard />
      <Shortcuts />
    </div>
  );

  return (
    <Popover
      content={content}
      placement="bottomLeft"
      trigger="click"
      arrow={false}
      open={isPopoverOpen}
      onOpenChange={setIsPopoverOpen}
    >
      <div className="flex h-[28px] w-[28px] cursor-pointer items-center justify-center rounded text-neutral-300 hover:bg-neutral-700/70 hover:text-white">
        <KeyboardIcon size={18} />
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/keyboard/paste.tsx
================================================
import { useState } from 'react';
import { ClipboardIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { device } from '@/libs/device';
import { CharCodes, ShiftChars } from '@/libs/keyboard/charCodes.ts';
import { getModifierBit } from '@/libs/keyboard/keymap.ts';

export const Paste = () => {
  const { t } = useTranslation();
  const [isLoading, setIsLoading] = useState(false);

  async function paste(): Promise<void> {
    if (isLoading) return;
    setIsLoading(true);

    try {
      const text = await navigator.clipboard.readText();
      if (!text) return;

      for (const char of text) {
        const ascii = char.charCodeAt(0);

        const code = CharCodes[ascii];
        if (!code) continue;

        let modifier = 0;
        if ((ascii >= 65 && ascii <= 90) || ShiftChars[ascii]) {
          modifier |= getModifierBit('ShiftLeft');
        }

        await send(modifier, code);
        await new Promise((r) => setTimeout(r, 50));
        await send(0, 0);
      }
    } catch (e) {
      console.log(e);
    } finally {
      setIsLoading(false);
    }
  }

  async function send(modifier: number, code: number): Promise<void> {
    const keys = [modifier, 0, code, 0, 0, 0, 0, 0];
    await device.sendKeyboardData(keys);
  }

  return (
    <div
      className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50"
      onClick={paste}
    >
      <ClipboardIcon size={16} />
      <span>{t('keyboard.paste')}</span>
    </div>
  );
};


================================================
FILE: browser/src/components/menu/keyboard/shortcuts/index.tsx
================================================
import { useEffect, useState } from 'react';
import { Divider, Popover } from 'antd';
import { CommandIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { ScrollArea } from '@/components/ui/scroll-area';
import * as storage from '@/libs/storage';

import { Recorder } from './recorder.tsx';
import { Shortcut } from './shortcut.tsx';
import type { Shortcut as ShortcutInterface } from './types.ts';

export const Shortcuts = () => {
  const { t } = useTranslation();

  const [isOpen, setIsOpen] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const [customShortcuts, setCustomShortcuts] = useState<ShortcutInterface[]>([]);

  const defaultShortcuts: ShortcutInterface[] = [
    {
      keys: [
        { code: 'MetaLeft', label: 'Win' },
        { code: 'Tab', label: 'Tab' }
      ]
    },
    {
      keys: [
        { code: 'ControlLeft', label: 'Ctrl' },
        { code: 'AltLeft', label: 'Alt' },
        { code: 'Delete', label: '⌫' }
      ]
    }
  ];

  useEffect(() => {
    const shortcuts = storage.getShortcuts();
    if (!shortcuts) return;
    setCustomShortcuts(JSON.parse(shortcuts));
  }, []);

  function addShortcut(shortcut: ShortcutInterface): void {
    const shortcuts = [...customShortcuts, shortcut];
    setCustomShortcuts(shortcuts);
    storage.setShortcuts(JSON.stringify(shortcuts));
  }

  function delShortcut(index: number): void {
    const shortcuts = customShortcuts.filter((_, i) => i !== index);
    setCustomShortcuts(shortcuts);
    storage.setShortcuts(JSON.stringify(shortcuts));
  }

  function handleOpenChange(open: boolean): void {
    if (open) {
      setIsOpen(true);
      return;
    }
    if (isRecording) {
      return;
    }
    setIsOpen(false);
  }

  const content = (
    <ScrollArea className="max-w-[400px] [&>[data-radix-scroll-area-viewport]]:max-h-[350px]">
      {/* custom shortcuts */}
      {customShortcuts.length > 0 && (
        <>
          {customShortcuts.map((shortcut, index) => (
            <Shortcut key={index} shortcut={shortcut}></Shortcut>
          ))}

          <Divider style={{ margin: '5px 0 5px 0' }} />
        </>
      )}

      {/*  default shortcuts */}
      {defaultShortcuts.map((shortcut, index) => (
        <Shortcut key={index} shortcut={shortcut}></Shortcut>
      ))}

      <Divider style={{ margin: '5px 0 5px 0' }} />

      <Recorder
        shortcuts={customShortcuts}
        addShortcut={addShortcut}
        delShortcut={delShortcut}
        setIsRecording={setIsRecording}
      />
    </ScrollArea>
  );

  return (
    <Popover
      content={content}
      trigger="hover"
      placement="rightTop"
      align={{ offset: [14, 0] }}
      open={isOpen}
      onOpenChange={handleOpenChange}
      arrow={false}
    >
      <div className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50">
        <CommandIcon size={16} />
        <span>{t('keyboard.shortcut.title')}</span>
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/keyboard/shortcuts/recorder.tsx
================================================
import { useEffect, useRef, useState } from 'react';
import { Button, Divider, Input, InputRef, Modal } from 'antd';
import { useSetAtom } from 'jotai';
import { KeyboardIcon, Trash2Icon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { Kbd, KbdGroup } from '@/components/ui/kbd.tsx';
import { ScrollArea } from '@/components/ui/scroll-area.tsx';
import { isKeyboardEnableAtom } from '@/jotai/keyboard.ts';
import { isModifier } from '@/libs/keyboard/keymap.ts';

import { KeyInfo, Shortcut } from './types.ts';

const MAX_KEYS = 6;

const SpecialKeyMap: Record<string, string> = {
  Space: 'Space',
  Backspace: '⌫',
  Enter: '↵',
  Tab: 'Tab',
  CapsLock: 'Caps',
  Escape: 'Esc',
  ArrowUp: '↑',
  ArrowDown: '↓',
  ArrowLeft: '←',
  ArrowRight: '→',
  Delete: 'Del',
  Insert: 'Ins',
  Home: 'Home',
  End: 'End',
  PageUp: 'PgUp',
  PageDown: 'PgDn'
};

const PunctuationMap: Record<string, string> = {
  Minus: '-',
  Equal: '=',
  BracketLeft: '[',
  BracketRight: ']',
  Backslash: '\\',
  Semicolon: ';',
  Quote: "'",
  Backquote: '`',
  Comma: ',',
  Period: '.',
  Slash: '/'
};

interface RecorderProps {
  shortcuts: Shortcut[];
  addShortcut: (shortcut: Shortcut) => void;
  delShortcut: (index: number) => void;
  setIsRecording: (isRecording: boolean) => void;
}

export const Recorder = ({
  shortcuts,
  addShortcut,
  delShortcut,
  setIsRecording
}: RecorderProps) => {
  const { t } = useTranslation();
  const setIsKeyboardEnable = useSetAtom(isKeyboardEnableAtom);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isFocused, setIsFocused] = useState(false);
  const [shortcutLabel, setShortcutLabel] = useState('');

  const inputRef = useRef<InputRef | null>(null);
  const recordedKeysRef = useRef<KeyInfo[]>([]);

  useEffect(() => {
    setIsKeyboardEnable(!isModalOpen);
    setIsRecording(isModalOpen);

    if (!isModalOpen) return;

    const timer = setTimeout(() => {
      inputRef.current?.focus();
    }, 100);

    return () => {
      clearTimeout(timer);
    };
  }, [isModalOpen]);

  useEffect(() => {
    if (!isFocused) return;

    const handleKeyDown = (event: KeyboardEvent): void => {
      event.preventDefault();
      event.stopPropagation();

      const { key, code } = event;

      const isRecorded = recordedKeysRef.current.some((k) => k.code === code);
      if (isRecorded) return;

      if (recordedKeysRef.current.length >= MAX_KEYS) return;

      const keyInfo: KeyInfo = {
        code: code,
        label: formatKeyDisplay(key, code)
      };

      setShortcutLabel((prev) => (prev ? `${prev} + ${keyInfo.label}` : keyInfo.label));
      recordedKeysRef.current.push(keyInfo);
    };

    window.addEventListener('keydown', handleKeyDown);

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [isFocused]);

  const formatKeyDisplay = (key: string, code: string): string => {
    if (isModifier(code)) {
      if (code.startsWith('Control')) {
        return 'Ctrl';
      }
      if (code.startsWith('Shift')) {
        return 'Shift';
      }
      if (code.startsWith('Alt')) {
        return 'Alt';
      }
      if (code.startsWith('Meta')) {
        return 'Win';
      }
    }

    if (code.startsWith('Digit')) {
      return code.replace('Digit', '');
    }
    if (code.startsWith('Key')) {
      return code.replace('Key', '');
    }
    if (code.startsWith('Numpad')) {
      const numpadKey = code.replace('Numpad', '');
      return `Num${numpadKey}`;
    }
    if (code.startsWith('F') && /^F\d+$/.test(code)) {
      return code; // F1, F2, etc.
    }

    if (SpecialKeyMap[code]) {
      return SpecialKeyMap[code];
    }
    if (PunctuationMap[code]) {
      return PunctuationMap[code];
    }

    return key.toUpperCase();
  };

  function saveShortcut() {
    if (recordedKeysRef.current.length > 0) {
      addShortcut({ keys: recordedKeysRef.current });
    }

    clearShortcut();
  }

  function clearShortcut() {
    setShortcutLabel('');
    recordedKeysRef.current = [];
  }

  function closeModal() {
    clearShortcut();
    setIsModalOpen(false);
  }

  function toggleFullscreen() {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen();
      // @ts-expect-error - https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock
      navigator.keyboard?.lock();
    } else {
      document.exitFullscreen();
      // @ts-expect-error - https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/unlock
      navigator.keyboard?.unlock();
    }
  }

  return (
    <>
      <div
        className="flex h-[30px] cursor-pointer items-center space-x-1 rounded px-3 text-neutral-300 hover:bg-neutral-700/60"
        onClick={() => setIsModalOpen(true)}
      >
        <span>{t('keyboard.shortcut.custom')}</span>
      </div>

      <Modal
        width={500}
        title={t('keyboard.shortcut.title')}
        keyboard={false}
        footer={null}
        open={isModalOpen}
        onCancel={closeModal}
      >
        <div>
          <span className="text-neutral-500">{t('keyboard.shortcut.captureTips')}</span>
          <a className="px-1 text-blue-500/80" onClick={toggleFullscreen}>
            {t('keyboard.shortcut.enterFullScreen')}
          </a>
        </div>

        <div className="flex items-center space-x-0.5 py-6">
          <Input
            ref={inputRef}
            placeholder={t('keyboard.shortcut.capture')}
            prefix={<KeyboardIcon size={16} className="text-neutral-500" />}
            value={shortcutLabel}
            onFocus={() => setIsFocused(true)}
            onBlur={() => setIsFocused(false)}
          />

          <Button onClick={clearShortcut}>{t('keyboard.shortcut.clear')}</Button>
        </div>

        <div className="flex w-full justify-center pb-3">
          <Button type="primary" className="min-w-24" onClick={saveShortcut}>
            {t('keyboard.shortcut.save')}
          </Button>
        </div>

        {shortcuts.length > 0 && (
          <>
            <Divider />

            <ScrollArea className="[&>[data-radix-scroll-area-viewport]]:max-h-[300px]">
              {shortcuts.map((shortcut, index) => (
                <div
                  key={index}
                  className="flex items-center justify-between rounded p-2 hover:bg-neutral-700/50"
                >
                  <div className="flex items-center space-x-1">
                    {shortcut.keys.map((key, index) => (
                      <KbdGroup key={index}>
                        <Kbd>{key.label}</Kbd>
                      </KbdGroup>
                    ))}
                  </div>

                  <div
                    className="flex size-[20px] cursor-pointer items-center justify-center rounded-sm text-neutral-500 hover:text-red-500"
                    onClick={() => delShortcut(index)}
                  >
                    <Trash2Icon size={16} />
                  </div>
                </div>
              ))}
            </ScrollArea>
          </>
        )}
      </Modal>
    </>
  );
};


================================================
FILE: browser/src/components/menu/keyboard/shortcuts/shortcut.tsx
================================================
import { useState } from 'react';

import { Kbd, KbdGroup } from '@/components/ui/kbd.tsx';
import { device } from '@/libs/device';
import { KeyboardReport } from '@/libs/keyboard/keyboard.ts';

import type { Shortcut as ShortcutInterface } from './types.ts';

type ShortcutProps = {
  shortcut: ShortcutInterface;
};

export const Shortcut = ({ shortcut }: ShortcutProps) => {
  const [isLoading, setIsLoading] = useState(false);

  async function handleClick(): Promise<void> {
    if (isLoading) return;
    setIsLoading(true);

    try {
      await sendShortcut();
    } catch (err) {
      console.log(err);
    } finally {
      setIsLoading(false);
    }
  }

  async function sendShortcut(): Promise<void> {
    const keyboard = new KeyboardReport();

    for (const key of shortcut.keys) {
      const report = keyboard.keyDown(key.code);
      await device.sendKeyboardData(report);
    }

    const report = keyboard.reset();
    await device.sendKeyboardData(report);
  }

  return (
    <div
      className="flex h-[32px] w-full cursor-pointer items-center space-x-1 rounded px-3 hover:bg-neutral-700/30"
      onClick={handleClick}
    >
      {shortcut.keys.map((key, index) => (
        <KbdGroup key={index}>
          <Kbd>{key.label}</Kbd>
        </KbdGroup>
      ))}
    </div>
  );
};


================================================
FILE: browser/src/components/menu/keyboard/shortcuts/types.ts
================================================
export interface KeyInfo {
  code: string;
  label: string;
}

export interface Shortcut {
  keys: KeyInfo[];
}


================================================
FILE: browser/src/components/menu/keyboard/virtual-keyboard.tsx
================================================
import { useSetAtom } from 'jotai';
import { KeyboardIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { isKeyboardOpenAtom } from '@/jotai/keyboard.ts';

export const VirtualKeyboard = () => {
  const { t } = useTranslation();
  const setIsKeyboardOpen = useSetAtom(isKeyboardOpenAtom);

  function toggleKeyboard() {
    setIsKeyboardOpen((isKeyboardOpen) => !isKeyboardOpen);
  }

  return (
    <div
      className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50"
      onClick={toggleKeyboard}
    >
      <KeyboardIcon size={16} />
      <span>{t('keyboard.virtualKeyboard')}</span>
    </div>
  );
};


================================================
FILE: browser/src/components/menu/mouse/direction.tsx
================================================
import { ReactElement } from 'react';
import { Popover } from 'antd';
import clsx from 'clsx';
import { useAtom } from 'jotai';
import { ArrowDownUpIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { scrollDirectionAtom } from '@/jotai/mouse.ts';
import * as storage from '@/libs/storage';

export const Direction = (): ReactElement => {
  const { t } = useTranslation();

  const [scrollDirection, setScrollDirection] = useAtom(scrollDirectionAtom);

  const directions = [
    { name: t('mouse.scrollUp'), value: '-1' },
    { name: t('mouse.scrollDown'), value: '1' }
  ];

  function update(direction: string): void {
    const value = Number(direction);

    setScrollDirection(value);
    storage.setMouseScrollDirection(value);
  }

  const content = (
    <>
      {directions.map((direction) => (
        <div
          key={direction.value}
          className={clsx(
            'my-1 flex cursor-pointer items-center space-x-1 rounded py-1 pl-2 pr-5 hover:bg-neutral-700/50',
            direction.value === scrollDirection.toString() ? 'text-blue-500' : 'text-neutral-300'
          )}
          onClick={() => update(direction.value)}
        >
          {direction.name}
        </div>
      ))}
    </>
  );

  return (
    <Popover content={content} placement="rightTop" arrow={false} align={{ offset: [13, 0] }}>
      <div className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50">
        <ArrowDownUpIcon size={16} />
        <span>{t('mouse.direction')}</span>
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/mouse/index.tsx
================================================
import { useEffect, useState } from 'react';
import { Divider, Popover } from 'antd';
import { useAtom, useSetAtom } from 'jotai';
import { MouseIcon } from 'lucide-react';

import {
  mouseJigglerModeAtom,
  mouseModeAtom,
  mouseStyleAtom,
  scrollDirectionAtom,
  scrollIntervalAtom
} from '@/jotai/mouse.ts';
import { mouseJiggler } from '@/libs/mouse-jiggler';
import * as storage from '@/libs/storage';

import { Direction } from './direction.tsx';
import { Jiggler } from './jiggler.tsx';
import { Mode } from './mode.tsx';
import { Speed } from './speed.tsx';
import { Style } from './style.tsx';

export const Mouse = () => {
  const [mouseStyle, setMouseStyle] = useAtom(mouseStyleAtom);
  const [mouseMode, setMouseMode] = useAtom(mouseModeAtom);
  const setScrollDirection = useSetAtom(scrollDirectionAtom);
  const setScrollInterval = useSetAtom(scrollIntervalAtom);
  const setMouseJigglerMode = useSetAtom(mouseJigglerModeAtom);

  const [isPopoverOpen, setIsPopoverOpen] = useState(false);

  useEffect(() => {
    initMouse();
  }, []);

  function initMouse() {
    const style = storage.getMouseStyle();
    if (style && style !== mouseStyle) {
      setMouseStyle(style);
    }

    const mode = storage.getMouseMode();
    if (mode && mode !== mouseMode) {
      setMouseMode(mode);
    }

    const direction = storage.getMouseScrollDirection();
    if (direction) {
      setScrollDirection(direction > 0 ? 1 : -1);
    }

    const interval = storage.getMouseScrollInterval();
    if (interval) {
      setScrollInterval(interval);
    }

    const jiggler = storage.getMouseJigglerMode();
    mouseJiggler.setMode(jiggler);
    setMouseJigglerMode(jiggler);
  }

  const content = (
    <div className="flex flex-col space-y-0.5">
      <Style />
      <Mode />
      <Direction />
      <Speed />

      <Divider style={{ margin: '5px 0 5px 0' }} />
      <Jiggler />
    </div>
  );

  return (
    <Popover
      content={content}
      placement="bottomLeft"
      trigger="click"
      arrow={false}
      open={isPopoverOpen}
      onOpenChange={setIsPopoverOpen}
    >
      <div className="flex h-[28px] w-[28px] cursor-pointer items-center justify-center rounded text-neutral-300 hover:bg-neutral-700/70 hover:text-white">
        <MouseIcon size={18} />
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/mouse/jiggler.tsx
================================================
import { useEffect } from 'react';
import { Popover } from 'antd';
import clsx from 'clsx';
import { useAtom } from 'jotai';
import { MousePointerClickIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { mouseJigglerModeAtom } from '@/jotai/mouse.ts';
import { mouseJiggler } from '@/libs/mouse-jiggler';
import * as storage from '@/libs/storage';

export const Jiggler = () => {
  const { t } = useTranslation();
  const [jigglerMode, setJigglerMode] = useAtom(mouseJigglerModeAtom);

  const mouseJigglerModes: { name: string; value: 'enable' | 'disable' }[] = [
    { name: t('mouse.jiggler.enable'), value: 'enable' },
    { name: t('mouse.jiggler.disable'), value: 'disable' }
  ];

  function update(mode: 'enable' | 'disable'): void {
    storage.setMouseJigglerMode(mode);
    setJigglerMode(mode);
  }

  useEffect(() => {
    mouseJiggler.setMode(jigglerMode);
  }, [jigglerMode]);

  const content = (
    <>
      {mouseJigglerModes.map((mode) => (
        <div
          key={mode.value}
          className={clsx(
            'my-1 flex cursor-pointer items-center space-x-1 rounded py-1 pl-2 pr-5 hover:bg-neutral-700/50',
            mode.value === jigglerMode ? 'text-blue-500' : 'text-neutral-300'
          )}
          onClick={() => update(mode.value)}
        >
          {mode.name}
        </div>
      ))}
    </>
  );

  return (
    <Popover content={content} placement="rightTop" arrow={false} align={{ offset: [13, 0] }}>
      <div className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50">
        <MousePointerClickIcon size={16} />
        <span>{t('mouse.jiggler.title')}</span>
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/mouse/mode.tsx
================================================
import { Popover } from 'antd';
import clsx from 'clsx';
import { useAtom } from 'jotai';
import { SquareMousePointerIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { mouseModeAtom } from '@/jotai/mouse.ts';
import * as storage from '@/libs/storage';

export const Mode = () => {
  const { t } = useTranslation();
  const [mouseMode, setMouseMode] = useAtom(mouseModeAtom);

  const mouseModes = [
    { name: t('mouse.absolute'), value: 'absolute' },
    { name: t('mouse.relative'), value: 'relative' }
  ];

  function update(mode: string) {
    setMouseMode(mode);
    storage.setMouseMode(mode);
  }

  const content = (
    <>
      {mouseModes.map((mode) => (
        <div
          key={mode.value}
          className={clsx(
            'my-1 flex cursor-pointer items-center space-x-1 rounded py-1 pl-2 pr-5 hover:bg-neutral-700/50',
            mode.value === mouseMode ? 'text-blue-500' : 'text-neutral-300'
          )}
          onClick={() => update(mode.value)}
        >
          {mode.name}
        </div>
      ))}
    </>
  );

  return (
    <Popover content={content} placement="rightTop" arrow={false} align={{ offset: [13, 0] }}>
      <div className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50">
        <SquareMousePointerIcon size={16} />
        <span>{t('mouse.mode')}</span>
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/mouse/speed.tsx
================================================
import { ReactElement, useEffect, useState } from 'react';
import { Popover, Slider } from 'antd';
import { useAtom } from 'jotai';
import { GaugeIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { scrollIntervalAtom } from '@/jotai/mouse.ts';
import * as storage from '@/libs/storage';

const MAX_INTERVAL = 300;

export const Speed = (): ReactElement => {
  const { t } = useTranslation();

  const [scrollInterval, setScrollInterval] = useAtom(scrollIntervalAtom);

  const [currentSpeed, setCurrentSpeed] = useState(100);

  useEffect(() => {
    const speed = interval2Speed(scrollInterval);
    setCurrentSpeed(speed);
  }, [scrollInterval]);

  function update(speed: number): void {
    const interval = speed2Interval(speed);
    setScrollInterval(interval);
    storage.setMouseScrollInterval(interval);
  }

  function interval2Speed(interval: number) {
    if (interval === MAX_INTERVAL) {
      return 0;
    }
    return ((MAX_INTERVAL - interval) * 100) / MAX_INTERVAL;
  }

  function speed2Interval(speed: number) {
    return MAX_INTERVAL - speed * (MAX_INTERVAL / 100);
  }

  const content = (
    <div className="h-[150px] w-[60px] py-3">
      <Slider
        vertical
        marks={{
          0: <span>{t('mouse.slow')}</span>,
          100: <span>{t('mouse.fast')}</span>
        }}
        range={false}
        included={false}
        step={10}
        defaultValue={currentSpeed}
        onChange={update}
      />
    </div>
  );

  return (
    <Popover content={content} placement="rightTop" arrow={false} align={{ offset: [13, 0] }}>
      <div className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50">
        <GaugeIcon size={16} />
        <span>{t('mouse.speed')}</span>
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/mouse/style.tsx
================================================
import { Popover } from 'antd';
import clsx from 'clsx';
import { useAtom } from 'jotai';
import { EyeOffIcon, HandIcon, MousePointerIcon, PlusIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { mouseStyleAtom } from '@/jotai/mouse.ts';
import * as storage from '@/libs/storage';

export const Style = () => {
  const { t } = useTranslation();

  const [mouseStyle, setMouseStyle] = useAtom(mouseStyleAtom);

  function updateStyle(style: string) {
    setMouseStyle(style);
    storage.setMouseStyle(style);
  }

  const mouseStyles = [
    {
      name: t('mouse.cursor.pointer'),
      icon: <MousePointerIcon size={14} />,
      value: 'cursor-default'
    },
    { name: t('mouse.cursor.grab'), icon: <HandIcon size={14} />, value: 'cursor-grab' },
    { name: t('mouse.cursor.cell'), icon: <PlusIcon size={14} />, value: 'cursor-cell' },
    { name: t('mouse.cursor.hide'), icon: <EyeOffIcon size={14} />, value: 'cursor-none' }
  ];

  const content = (
    <>
      {mouseStyles.map((style) => (
        <div
          key={style.value}
          className={clsx(
            'flex cursor-pointer select-none items-center space-x-1 rounded py-1 pl-3 pr-5 hover:bg-neutral-700/50',
            style.value === mouseStyle ? 'text-blue-500' : 'text-neutral-300'
          )}
          onClick={() => updateStyle(style.value)}
        >
          <div className="flex h-[14px] w-[20px] items-end">{style.icon}</div>
          <span>{style.name}</span>
        </div>
      ))}
    </>
  );

  return (
    <Popover content={content} placement="rightTop" arrow={false} align={{ offset: [13, 0] }}>
      <div className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50">
        <MousePointerIcon size={16} />
        <span className="select-none text-sm">{t('mouse.cursor.title')}</span>
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/recorder/index.tsx
================================================
import { useEffect, useRef, useState } from 'react';
import { Video } from 'lucide-react';

import { camera } from '@/libs/media/camera';

export const Recorder = () => {
  const [isRecording, setIsRecording] = useState(false);
  const [elapsedMs, setElapsedMs] = useState(0);

  const mediaRecorderRef = useRef<MediaRecorder>();
  const fileWritableRef = useRef<FileSystemWritableFileStream | null>(null);
  const timerRef = useRef<number | null>(null);
  const startTimeRef = useRef<number>(0);

  const stopTimer = () => {
    if (timerRef.current !== null) {
      window.clearInterval(timerRef.current);
      timerRef.current = null;
    }
  };

  const startTimer = () => {
    stopTimer();
    startTimeRef.current = Date.now();
    setElapsedMs(0);
    timerRef.current = window.setInterval(() => {
      setElapsedMs(Date.now() - startTimeRef.current);
    }, 1000);
  };

  useEffect(() => {
    return () => {
      stopTimer();
    };
  }, []);

  const formatElapsed = (ms: number) => {
    const totalSeconds = Math.floor(ms / 1000);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;
    return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  };

  const handleStartRecording = async () => {
    const stream = camera.getStream();
    if (!stream) {
      return;
    }

    try {
      const handle = await (window as any).showSaveFilePicker({
        suggestedName: `recording-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.webm`,
        types: [
          {
            description: 'Sipeed NanoKVM-USB Recorder',
            accept: { 'video/webm': ['.webm'] }
          }
        ]
      });

      fileWritableRef.current = await handle.createWritable();

      const recorder = new MediaRecorder(stream, {
        mimeType: 'video/webm'
      });

      recorder.ondataavailable = async (event) => {
        if (event.data && event.data.size > 0) {
          if (fileWritableRef.current) {
            await fileWritableRef.current.write(event.data);
          } else {
            recorder.stop();
          }
        }
      };

      recorder.onstop = async () => {
        if (fileWritableRef.current) {
          await fileWritableRef.current.close();
          fileWritableRef.current = null;
        }
        stopTimer();
        setElapsedMs(0);
        setIsRecording(false);
      };

      recorder.start(1000);
      mediaRecorderRef.current = recorder;
      setIsRecording(true);
      startTimer();
    } catch (err) {
      console.error(err);
    }
  };

  const handleStopRecording = () => {
    const recorder = mediaRecorderRef.current;
    if (recorder && recorder.state !== 'inactive') {
      recorder.stop();
      stopTimer();
      setElapsedMs(0);
      setIsRecording(false);
    }
  };

  if (isRecording) {
    return (
      <div
        className="flex h-[28px] min-w-[28px] cursor-pointer items-center justify-center space-x-1 rounded px-1 text-white hover:bg-neutral-700/70"
        onClick={handleStopRecording}
      >
        <Video className="animate-pulse text-red-400" size={18} />
        <span className="text-xs text-red-300">{formatElapsed(elapsedMs)}</span>
      </div>
    );
  }

  return (
    <div
      className="flex h-[28px] w-[28px] cursor-pointer items-center justify-center rounded text-neutral-300 hover:bg-neutral-700/70 hover:text-white"
      onClick={handleStartRecording}
    >
      <Video size={18} />
    </div>
  );
};


================================================
FILE: browser/src/components/menu/serial-port/index.tsx
================================================
import { useState } from 'react';
import { CpuIcon, Loader2Icon } from 'lucide-react';

import { device } from '@/libs/device';

export const SerialPort = () => {
  const [isLoading, setIsLoading] = useState(false);

  async function selectSerial() {
    if (isLoading) return;
    setIsLoading(true);

    try {
      const port = await navigator.serial.requestPort();
      await device.serialPort.init({ port });
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <div className="flex items-center justify-center text-neutral-300" onClick={selectSerial}>
      <div className="flex h-[28px] w-[28px] cursor-pointer items-center justify-center rounded text-neutral-300 hover:bg-neutral-700/70 hover:text-white">
        {isLoading ? <Loader2Icon className="animate-spin" size={18} /> : <CpuIcon size={18} />}
      </div>
    </div>
  );
};


================================================
FILE: browser/src/components/menu/settings/index.tsx
================================================
import { Popover } from 'antd';
import { BookIcon, DownloadIcon, SettingsIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { Language } from './language.tsx';

export const Settings = () => {
  const { t } = useTranslation();

  function openPage(url: string) {
    window.open(url, '_blank');
  }

  const content = (
    <div className="flex flex-col space-y-0.5">
      <Language />

      <div
        className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50"
        onClick={() => openPage('https://wiki.sipeed.com/nanokvmusb')}
      >
        <BookIcon size={16} />
        <span>{t('settings.document')}</span>
      </div>

      <div
        className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50"
        onClick={() => openPage('https://github.com/sipeed/NanoKVM-USB/releases')}
      >
        <DownloadIcon size={16} />
        <span>{t('settings.download')}</span>
      </div>
    </div>
  );

  return (
    <Popover content={content} placement="bottomLeft" trigger="click" arrow={false}>
      <div className="flex h-[28px] w-[28px] cursor-pointer items-center justify-center rounded text-neutral-300 hover:bg-neutral-700/50 hover:text-white">
        <SettingsIcon size={18} />
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/settings/language.tsx
================================================
import { Popover } from 'antd';
import clsx from 'clsx';
import { LanguagesIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import languages from '@/i18n/languages.ts';
import { setLanguage } from '@/libs/storage';

export const Language = () => {
  const { t, i18n } = useTranslation();

  function changeLanguage(lng: string) {
    if (i18n.language === lng) return;

    i18n.changeLanguage(lng);
    setLanguage(lng);
  }

  const content = (
    <>
      {languages.map((lng) => (
        <div
          key={lng.key}
          className={clsx(
            'flex cursor-pointer select-none items-center space-x-1 rounded px-5 py-1',
            i18n.language === lng.key ? 'text-blue-500' : 'text-white hover:bg-neutral-700'
          )}
          onClick={() => changeLanguage(lng.key)}
        >
          {lng.name}
        </div>
      ))}
    </>
  );

  return (
    <Popover content={content} placement="rightTop">
      <div className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50">
        <LanguagesIcon size={16} />
        <span>{t('settings.language')}</span>
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/video/device.tsx
================================================
import { useEffect, useState } from 'react';
import { Popover } from 'antd';
import clsx from 'clsx';
import { useAtom, useAtomValue } from 'jotai';
import { VideoIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { resolutionAtom, videoDeviceIdAtom } from '@/jotai/device.ts';
import { camera } from '@/libs/media/camera';
import * as storage from '@/libs/storage';
import type { MediaDevice } from '@/types';

export const Device = () => {
  const { t } = useTranslation();

  const resolution = useAtomValue(resolutionAtom);
  const [videoDeviceId, setVideoDeviceId] = useAtom(videoDeviceIdAtom);

  const [devices, setDevices] = useState<MediaDevice[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    getDevices();
  }, []);

  async function getDevices() {
    try {
      const allDevices = await navigator.mediaDevices.enumerateDevices();
      const videoDevices = allDevices.filter((device) => device.kind === 'videoinput');
      const audioDevices = allDevices.filter((device) => device.kind === 'audioinput');

      const mediaDevices = videoDevices.map((videoDevice) => {
        const device: MediaDevice = {
          videoId: videoDevice.deviceId,
          videoName: videoDevice.label
        };

        if (videoDevice.groupId) {
          const matchedAudioDevice = audioDevices.find(
            (audioDevice) => audioDevice.groupId === videoDevice.groupId
          );
          if (matchedAudioDevice) {
            device.audioId = matchedAudioDevice.deviceId;
            device.audioName = matchedAudioDevice.label;
          }
        }

        return device;
      });

      setDevices(mediaDevices);
    } catch (err) {
      console.log(err);
    }
  }

  async function selectDevice(device: MediaDevice) {
    if (isLoading) return;
    setIsLoading(true);

    try {
      await camera.open(device.videoId, resolution.width, resolution.height, device.audioId);

      const video = document.getElementById('video') as HTMLVideoElement;
      if (!video) return;
      video.srcObject = camera.getStream();

      setVideoDeviceId(device.videoId);
      storage.setVideoDevice(device.videoId);
    } finally {
      setIsLoading(false);
    }
  }

  const content = (
    <>
      {devices.map((device) => (
        <div
          key={device.videoId}
          className={clsx(
            'max-w-[320px] cursor-pointer truncate rounded px-2 py-1.5 hover:bg-neutral-700/60',
            device.videoId === videoDeviceId ? 'text-blue-500' : 'text-white'
          )}
          onClick={() => selectDevice(device)}
        >
          {device.videoName}
        </div>
      ))}
    </>
  );

  return (
    <Popover content={content} placement="rightTop" arrow={false} align={{ offset: [13, 0] }}>
      <div className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50">
        <VideoIcon size={16} />
        <span className="select-none text-sm">{t('video.device')}</span>
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/video/index.tsx
================================================
import { Popover } from 'antd';
import { MonitorIcon } from 'lucide-react';

import { Device } from './device.tsx';
import { Resolution } from './resolution.tsx';
import { Rotation } from './rotation.tsx';
import { Scale } from './scale.tsx';

export const Video = () => {
  const content = (
    <div className="flex flex-col space-y-0.5">
      <Resolution />
      <Rotation />
      <Scale />
      <Device />
    </div>
  );

  return (
    <Popover content={content} placement="bottomLeft" trigger="click" arrow={false}>
      <div className="flex h-[28px] w-[28px] cursor-pointer items-center justify-center rounded text-neutral-300 hover:bg-neutral-700/70 hover:text-white">
        <MonitorIcon size={18} />
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/video/resolution.tsx
================================================
import { useEffect, useState } from 'react';
import { Button, Divider, InputNumber, Modal, Popover } from 'antd';
import clsx from 'clsx';
import { useAtom, useSetAtom } from 'jotai';
import { MonitorIcon, Trash2Icon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { resolutionAtom } from '@/jotai/device.ts';
import { isKeyboardEnableAtom } from '@/jotai/keyboard.ts';
import { camera } from '@/libs/media/camera.ts';
import * as storage from '@/libs/storage';
import type { Resolution as VideoResolution } from '@/types';

export const Resolution = () => {
  const { t } = useTranslation();
  const setIsKeyboardEnable = useSetAtom(isKeyboardEnableAtom);
  const [resolution, setResolution] = useAtom(resolutionAtom);

  const [isOpen, setIsOpen] = useState(false);
  const [width, setWidth] = useState(0);
  const [height, setHeight] = useState(0);
  const [customResolutions, setCustomResolutions] = useState<VideoResolution[]>([]);

  const resolutions: VideoResolution[] = [
    { width: 3840, height: 2160 },
    { width: 2560, height: 1440 },
    { width: 1920, height: 1080 },
    { width: 1280, height: 720 },
    { width: 800, height: 600 },
    { width: 640, height: 480 }
  ];

  useEffect(() => {
    const resolutions = storage.getCustomResolutions();
    if (resolutions) {
      setCustomResolutions(resolutions);
    }
  }, []);

  useEffect(() => {
    setIsKeyboardEnable(!isOpen);
  }, [isOpen]);

  function showModal() {
    setWidth(0);
    setHeight(0);
    setIsOpen(true);
  }

  function submit() {
    if (!width || !height || (width === resolution.width && height === resolution.height)) {
      setIsOpen(false);
      return;
    }

    let isExist = resolutions.some((r) => r.width === width && r.height === height);
    if (isExist) return;
    isExist = customResolutions.some((r) => r.width === width && r.height === height);
    if (isExist) return;

    setCustomResolutions([...customResolutions, { width, height }]);
    storage.setCustomResolution(width, height);

    updateResolution(width, height);
  }

  async function updateResolution(w: number, h: number) {
    try {
      await camera.updateResolution(w, h);
    } catch (err) {
      console.log(err);
      return;
    }

    const video = document.getElementById('video') as HTMLVideoElement;
    if (!video) return;
    video.srcObject = camera.getStream();

    setResolution({ width: w, height: h });
    storage.setVideoResolution(w, h);
    setIsOpen(false);
  }

  function removeCustomResolution(e: any) {
    e.stopPropagation();

    const isExist = customResolutions.some(
      (r) => r.width === resolution.width && r.height === resolution.height
    );
    if (isExist) {
      updateResolution(1920, 1080);
    }

    setCustomResolutions([]);
    storage.removeCustomResolutions();
  }

  const content = (
    <>
      {/* resolution list */}
      {resolutions.map((res) => (
        <div
          key={res.width}
          className={clsx(
            'flex cursor-pointer select-none items-center space-x-1 rounded px-4 py-1.5 hover:bg-neutral-700/60',
            resolution.width === res.width && resolution.height === res.height
              ? 'text-blue-500'
              : 'text-white'
          )}
          onClick={() => updateResolution(res.width, res.height)}
        >
          <span className="flex w-[32px]">{res.width}</span>
          <span>x</span>
          <span className="w-[32px]">{res.height}</span>
        </div>
      ))}

      <Divider style={{ margin: '5px 0 5px 0' }} />

      {/* custom resolution */}
      <div
        className="flex cursor-pointer select-none items-center justify-between space-x-3 rounded px-4 py-1.5 text-sm hover:bg-neutral-700/60"
        onClick={showModal}
      >
        <span>{t('video.customResolution')}</span>
        {customResolutions.length > 0 && (
          <span className="hover:text-red-500" onClick={removeCustomResolution}>
            <Trash2Icon size={14} />
          </span>
        )}
      </div>

      {customResolutions.map((res) => (
        <div
          key={res.width}
          className={clsx(
            'flex cursor-pointer select-none items-center space-x-1 rounded px-4 py-1.5 hover:bg-neutral-700/60',
            resolution.width === res.width && resolution.height === res.height
              ? 'text-blue-500'
              : 'text-white'
          )}
          onClick={() => updateResolution(res.width, res.height)}
        >
          <span className="flex w-[32px]">{res.width}</span>
          <span>x</span>
          <span className="w-[32px]">{res.height}</span>
        </div>
      ))}
    </>
  );

  return (
    <>
      <Popover content={content} placement="rightTop" arrow={false} align={{ offset: [13, 0] }}>
        <div className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50">
          <MonitorIcon size={16} />
          <span className="select-none text-sm">{t('video.resolution')}</span>
        </div>
      </Popover>

      <Modal
        open={isOpen}
        title={t('video.custom.title')}
        footer={null}
        closable={false}
        destroyOnHidden
      >
        <div className="flex flex-col items-center justify-center space-y-5 py-10">
          <div className="flex items-center space-x-5">
            <span className="text-sm">{t('video.custom.width')}</span>
            <InputNumber
              min={1}
              controls={false}
              defaultValue={resolution.width}
              onChange={(value) => setWidth(value || 0)}
            />
          </div>

          <div className="flex items-center space-x-5">
            <span className="text-sm">{t('video.custom.height')}</span>
            <InputNumber
              min={1}
              controls={false}
              defaultValue={resolution.height}
              onChange={(value) => setHeight(value || 0)}
            />
          </div>

          <div className="flex space-x-5">
            <Button type="primary" className="w-20" onClick={submit}>
              {t('video.custom.confirm')}
            </Button>
            <Button type="default" className="w-20" onClick={() => setIsOpen(false)}>
              {t('video.custom.cancel')}
            </Button>
          </div>
        </div>
      </Modal>
    </>
  );
};


================================================
FILE: browser/src/components/menu/video/rotation.tsx
================================================
import { ReactElement } from 'react';
import { Popover } from 'antd';
import clsx from 'clsx';
import { useAtom } from 'jotai';
import { RatioIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { videoRotationAtom } from '@/jotai/device.ts';
import * as storage from '@/libs/storage';
import { Rotation as VideoRotation } from '@/types.ts';

const RotationList: { label: string; value: VideoRotation }[] = [
  { label: '0°', value: 0 },
  { label: '90°', value: 90 },
  { label: '180°', value: 180 },
  { label: '270°', value: 270 }
];

export const Rotation = (): ReactElement => {
  const { t } = useTranslation();

  const [videoRotation, setVideoRotation] = useAtom(videoRotationAtom);

  function updateRotation(rotation: VideoRotation): void {
    setVideoRotation(rotation);
    storage.setVideoRotation(rotation);
  }

  const content = (
    <>
      {RotationList.map((item) => (
        <div
          key={item.value}
          className={clsx(
            'flex cursor-pointer select-none items-center space-x-0.5 rounded px-5 py-1.5 hover:bg-neutral-700/60',
            item.value === videoRotation ? 'text-blue-500' : 'text-white'
          )}
          onClick={() => updateRotation(item.value)}
        >
          <span>{item.label}</span>
        </div>
      ))}
    </>
  );

  return (
    <Popover content={content} placement="rightTop" arrow={false} align={{ offset: [13, 0] }}>
      <div className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50">
        <div className="flex size-[18px] items-center justify-center">
          <RatioIcon size={16} />
        </div>
        <span>{t('video.rotation')}</span>
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/menu/video/scale.tsx
================================================
import { ReactElement, useEffect } from 'react';
import { Popover } from 'antd';
import clsx from 'clsx';
import { useAtom } from 'jotai';
import { PercentIcon, ScalingIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { videoScaleAtom } from '@/jotai/device.ts';
import * as storage from '@/libs/storage';

export const Scale = (): ReactElement => {
  const { t } = useTranslation();

  const [videoScale, setVideoScale] = useAtom(videoScaleAtom);

  const ScaleList = [
    { label: t('video.auto'), value: 0 },
    { label: '200', value: 2 },
    { label: '150', value: 1.5 },
    { label: '100', value: 1 },
    { label: '75', value: 0.75 },
    { label: '50', value: 0.5 }
  ];

  useEffect(() => {
    const scale = storage.getVideoScale();
    if (scale) {
      setVideoScale(scale);
    }
  }, []);

  async function updateScale(scale: number): Promise<void> {
    setVideoScale(scale);
    storage.setVideoScale(scale);
  }

  const content = (
    <>
      {ScaleList.map((item) => (
        <div
          key={item.value}
          className={clsx(
            'flex cursor-pointer select-none items-center space-x-0.5 rounded px-5 py-1.5 hover:bg-neutral-700/60',
            item.value === videoScale ? 'text-blue-500' : 'text-white'
          )}
          onClick={() => updateScale(item.value)}
        >
          <span>{item.label}</span>
          {item.value > 0 && <PercentIcon size={12} />}
        </div>
      ))}
    </>
  );

  return (
    <Popover content={content} placement="rightTop" arrow={false} align={{ offset: [13, 0] }}>
      <div className="flex h-[32px] cursor-pointer items-center space-x-2 rounded px-3 text-neutral-300 hover:bg-neutral-700/50">
        <div className="flex size-[18px] items-center justify-center">
          <ScalingIcon size={16} />
        </div>
        <span>{t('video.scale')}</span>
      </div>
    </Popover>
  );
};


================================================
FILE: browser/src/components/mouse/absolute.tsx
================================================
import { useEffect, useRef } from 'react';
import { useAtomValue } from 'jotai';
import { useMediaQuery } from 'react-responsive';

import { createInitialTouchState, createTouchHandlers } from '@/components/mouse/touchpad.ts';
import { MouseAbsoluteEvent } from '@/components/mouse/types.ts';
import { scrollDirectionAtom, scrollIntervalAtom } from '@/jotai/mouse.ts';
import { device } from '@/libs/device';
import { MouseAbsoluteRelative } from '@/libs/mouse';
import { mouseJiggler } from '@/libs/mouse-jiggler';

export const Absolute = () => {
  const isBigScreen = useMediaQuery({ minWidth: 650 });

  const scrollDirection = useAtomValue(scrollDirectionAtom);
  const scrollInterval = useAtomValue(scrollIntervalAtom);

  const mouseRef = useRef(new MouseAbsoluteRelative());
  const lastPosRef = useRef({ x: 0.5, y: 0.5 });
  const lastScrollTimeRef = useRef(0);
  const touchStateRef = useRef(createInitialTouchState());

  useEffect(() => {
    const screen = document.getElementById('video') as HTMLVideoElement;
    if (!screen) return;

    // Add mouse event listeners
    screen.addEventListener('mousedown', handleMouseDown);
    screen.addEventListener('mouseup', handleMouseUp);
    screen.addEventListener('mousemove', handleMouseMove);
    screen.addEventListener('wheel', handleWheel);
    screen.addEventListener('click', disableEvent);
    screen.addEventListener('contextmenu', disableEvent);

    // Create touch handlers
    const touchState = touchStateRef.current;
    const touchHandlers = createTouchHandlers(touchState, {
      scrollDirection,
      scrollInterval,
      getCoordinate,
      handleMouseEvent,
      disableEvent
    });

    // Add touch event listeners (only on big screens)
    if (isBigScreen) {
      screen.addEventListener('touchstart', touchHandlers.handleTouchStart);
      screen.addEventListener('touchmove', touchHandlers.handleTouchMove);
      screen.addEventListener('touchend', touchHandlers.handleTouchEnd);
      screen.addEventListener('touchcancel', touchHandlers.handleTouchCancel);
    }

    // Mouse down event
    function handleMouseDown(e: MouseEvent): void {
      disableEvent(e);
      handleMouseEvent({ type: 'mousedown', button: e.button });
    }

    // Mouse up event
    function handleMouseUp(e: MouseEvent): void {
      disableEvent(e);
      handleMouseEvent({ type: 'mouseup', button: e.button });
    }

    // Mouse move event
    function handleMouseMove(e: MouseEvent): void {
      disableEvent(e);
      const { x, y } = getCoordinate(e);
      handleMouseEvent({ type: 'move', x, y });
    }

    // Mouse wheel event
    function handleWheel(e: WheelEvent): void {
      disableEvent(e);

      if (Math.floor(e.deltaY) === 0) {
        return;
      }

      const currentTime = Date.now();
      if (currentTime - lastScrollTimeRef.current < scrollInterval) {
        return;
      }

      const deltaY = (e.deltaY > 0 ? 1 : -1) * scrollDirection;
      handleMouseEvent({ type: 'wheel', deltaY });
      lastScrollTimeRef.current = currentTime;
    }

    // Calculate mouse coordinate
    function getCoordinate(event: { clientX: number; clientY: number }): { x: number; y: number } {
      const rect = screen.getBoundingClientRect();

      const clientX = event.clientX;
      const clientY = event.clientY;

      if (!screen.videoWidth || !screen.videoHeight) {
        const x = (clientX - rect.left) / rect.width;
        const y = (clientY - rect.top) / rect.height;
        return { x, y };
      }

      const videoRatio = screen.videoWidth / screen.videoHeight;
      const elementRatio = rect.width / rect.height;

      let renderedWidth = rect.width;
      let renderedHeight = rect.height;
      let offsetX = 0;
      let offsetY = 0;

      if (videoRatio > elementRatio) {
        renderedHeight = rect.width / videoRatio;
        offsetY = (rect.height - renderedHeight) / 2;
      } else {
        renderedWidth = rect.height * videoRatio;
        offsetX = (rect.width - renderedWidth) / 2;
      }

      const x = (clientX - rect.left - offsetX) / renderedWidth;
      const y = (clientY - rect.top - offsetY) / renderedHeight;
      return { x, y };
    }

    return () => {
      screen.removeEventListener('mousedown', handleMouseDown);
      screen.removeEventListener('mouseup', handleMouseUp);
      screen.removeEventListener('mousemove', handleMouseMove);
      screen.removeEventListener('wheel', handleWheel);
      screen.removeEventListener('click', disableEvent);
      screen.removeEventListener('contextmenu', disableEvent);
      screen.removeEventListener('touchstart', touchHandlers.handleTouchStart);
      screen.removeEventListener('touchmove', touchHandlers.handleTouchMove);
      screen.removeEventListener('touchend', touchHandlers.handleTouchEnd);
      screen.removeEventListener('touchcancel', touchHandlers.handleTouchCancel);

      touchHandlers.cleanup();
    };
  }, [isBigScreen, scrollDirection, scrollInterval]);

  // Mouse event handler
  async function handleMouseEvent(event: MouseAbsoluteEvent): Promise<void> {
    let report: number[];
    const mouse = mouseRef.current;

    switch (event.type) {
      case 'mousedown':
        mouse.buttonDown(event.button);
        report = mouse.buildButtonReport(lastPosRef.current.x, lastPosRef.current.y);
        break;
      case 'mouseup':
        mouse.buttonUp(event.button);
        report = mouse.buildButtonReport(lastPosRef.current.x, lastPosRef.current.y);
        break;
      case 'wheel':
        report = mouse.buildReport(lastPosRef.current.x, lastPosRef.current.y, event.deltaY);
        break;
      case 'move':
        report = mouse.buildReport(event.x, event.y);
        lastPosRef.current = { x: event.x, y: event.y };
        break;
      default:
        report = mouse.buildReport(lastPosRef.current.x, lastPosRef.current.y);
        break;
    }

    await device.sendMouseData([0x02, ...report]);

    mouseJiggler.moveEventCallback();
  }

  // Disable default events
  function disableEvent(event: Event): void {
    event.preventDefault();
    event.stopPropagation();
  }

  return <></>;
};


================================================
FILE: browser/src/components/mouse/index.tsx
================================================
import { useAtomValue } from 'jotai';

import { mouseModeAtom } from '@/jotai/mouse.ts';

import { Absolute } from './absolute.tsx';
import { Relative } from './relative.tsx';

export const Mouse = () => {
  const mouseMode = useAtomValue(mouseModeAtom);

  return <>{mouseMode === 'relative' ? <Relative /> : <Absolute />}</>;
};


================================================
FILE: browser/src/components/mouse/relative.tsx
================================================
import { useEffect, useRef } from 'react';
import { message } from 'antd';
import { useAtomValue } from 'jotai';
import { useTranslation } from 'react-i18next';

import { MouseRelativeEvent } from '@/components/mouse/types.ts';
import { scrollDirectionAtom, scrollIntervalAtom } from '@/jotai/mouse.ts';
import { device } from '@/libs/device';
import { MouseReportRelative } from '@/libs/mouse';
import { mouseJiggler } from '@/libs/mouse-jiggler';

export const Relative = () => {
  const { t } = useTranslation();
  const [messageApi, contextHolder] = message.useMessage();

  const scrollDirection = useAtomValue(scrollDirectionAtom);
  const scrollInterval = useAtomValue(scrollIntervalAtom);

  const mouseRef = useRef(new MouseReportRelative());
  const isLockedRef = useRef(false);
  const lastScrollTimeRef = useRef(0);

  showMessage();

  useEffect(() => {
    const screen = document.getElementById('video');
    if (!screen) return;

    screen.addEventListener('click', handleClick);
    screen.addEventListener('mousedown', handleMouseDown);
    screen.addEventListener('mouseup', handleMouseUp);
    screen.addEventListener('mousemove', handleMouseMove);
    screen.addEventListener('wheel', handleMouseWheel);
    screen.addEventListener('contextmenu', disableEvent);
    document.addEventListener('pointerlockchange', handlePointerLockChange);

    // Click to request pointer lock
    function handleClick(event: MouseEvent): void {
      disableEvent(event);

      if (!isLockedRef.current) {
        screen?.requestPointerLock();
      }
    }

    // Mouse down event
    function handleMouseDown(e: MouseEvent): void {
      disableEvent(e);
      handleMouseEvent({ type: 'mousedown', button: e.button });
    }

    // Mouse up event
    function handleMouseUp(e: MouseEvent): void {
      disableEvent(e);
      handleMouseEvent({ type: 'mouseup', button: e.button });
    }

    // Mouse move event
    function handleMouseMove(e: MouseEvent): void {
      disableEvent(e);

      const x = e.movementX || 0;
      const y = e.movementY || 0;
      if (x === 0 && y === 0) return;

      const deltaX = Math.abs(x * window.devicePixelRatio) < 10 ? x * 2 : x;
      const deltaY = Math.abs(y * window.devicePixelRatio) < 10 ? y * 2 : y;

      handleMouseEvent({ type: 'move', deltaX, deltaY });
    }

    // Mouse wheel event
    function handleMouseWheel(e: WheelEvent): void {
      disableEvent(e);

      if (Math.floor(e.deltaY) === 0) {
        return;
      }

      const currentTime = Date.now();
      if (currentTime - lastScrollTimeRef.current < scrollInterval) {
        return;
      }

      const deltaY = (e.deltaY > 0 ? 1 : -1) * scrollDirection;
      handleMouseEvent({ type: 'wheel', deltaY });
      lastScrollTimeRef.current = currentTime;
    }

    // Pointer lock state change
    function handlePointerLockChange(): void {
      isLockedRef.current = document.pointerLockElement === screen;
    }

    return (): void => {
      // Exit pointer lock when component unmounts
      if (document.pointerLockElement === screen) {
        document.exitPointerLock();
      }

      screen.removeEventListener('click', handleClick);
      screen.removeEventListener('mousedown', handleMouseDown);
      screen.removeEventListener('mouseup', handleMouseUp);
      screen.removeEventListener('mousemove', handleMouseMove);
      screen.removeEventListener('wheel', handleMouseWheel);
      screen.removeEventListener('contextmenu', disableEvent);
      document.removeEventListener('pointerlockchange', handlePointerLockChange);
    };
  }, [scrollDirection, scrollInterval]);

  // Mouse handler
  async function handleMouseEvent(event: MouseRelativeEvent): Promise<void> {
    let report: number[];
    const mouse = mouseRef.current;

    switch (event.type) {
      case 'mousedown':
        mouse.buttonDown(event.button);
        report = mouse.buildButtonReport();
        break;
      case 'mouseup':
        mouse.buttonUp(event.button);
        report = mouse.buildButtonReport();
        break;
      case 'wheel':
        report = mouse.buildReport(0, 0, event.deltaY);
        break;
      case 'move':
        report = mouse.buildReport(event.deltaX, event.deltaY);
        break;
      default:
        report = mouse.buildReport(0, 0);
        break;
    }

    await device.sendMouseData([0x01, ...report]);

    mouseJiggler.moveEventCallback();
  }

  function showMessage(): void {
    messageApi.open({
      key: 'requestPointer',
      type: 'info',
      content: t('mouse.requestPointer'),
      duration: 3,
      style: {
        marginTop: '40vh'
      }
    });
  }

  function disableEvent(event: Event): void {
    event.preventDefault();
    event.stopPropagation();
  }

  return <>{contextHolder}</>;
};


================================================
FILE: browser/src/components/mouse/touchpad.ts
================================================
import { MouseButton } from './types';
import type { MouseAbsoluteEvent } from './types';

// Touch event thresholds
const TAP_THRESHOLD = 8;
const DRAG_THRESHOLD = 10;
const VELOCITY_THRESHOLD = 0.3;
const LONG_PRESS_DELAY = 800;

export interface TouchHandlerOptions {
  scrollDirection: number;
  scrollInterval: number;
  getCoordinate: (event: { clientX: number; clientY: number }) => { x: number; y: number };
  handleMouseEvent: (event: MouseAbsoluteEvent) => void;
  disableEvent: (event: Event) => void;
}

export interface TouchState {
  touchStartTime: number;
  lastTouchY: number;
  longPressTimer: ReturnType<typeof setTimeout> | null;
  isLongPress: boolean;
  hasMove: boolean;
  isDragging: boolean;
  pressedButton: MouseButton | null;
  touchStartPos: { x: number; y: number };
  lastScrollTime: number;
}

export function createInitialTouchState(): TouchState {
  return {
    touchStartTime: 0,
    lastTouchY: 0,
    longPressTimer: null,
    isLongPress: false,
    hasMove: false,
    isDragging: false,
    pressedButton: null,
    touchStartPos: { x: 0, y: 0 },
    lastScrollTime: 0
  };
}

export function createTouchHandlers(state: TouchState, options: TouchHandlerOptions) {
  const { scrollDirection, scrollInterval, getCoordinate, handleMouseEvent, disableEvent } =
    options;

  function handleTouchStart(e: TouchEvent): void {
    disableEvent(e);

    if (e.touches.length === 0) {
      return;
    }

    const touch = e.touches[0];

    // Reset states
    state.touchStartTime = Date.now();
    state.lastTouchY = touch.clientY;
    state.isLongPress = false;
    state.hasMove = false;
    state.isDragging = false;
    state.pressedButton = null;
    state.touchStartPos = { x: touch.clientX, y: touch.clientY };

    if (state.longPressTimer) {
      clearTimeout(state.longPressTimer);
    }

    const { x, y } = getCoordinate(touch);
    handleMouseEvent({ type: 'move', x, y });

    if (e.touches.length > 1) {
      return;
    }

    // Start long press timer
    state.longPressTimer = setTimeout(() => {
      state.isLongPress = true;
      state.pressedButton = MouseButton.Right;
      if (navigator.vibrate) {
        navigator.vibrate(50);
      }

      handleMouseEvent({ type: 'mousedown', button: MouseButton.Right });
    }, LONG_PRESS_DELAY);
  }

  function handleTouchMove(e: TouchEvent): void {
    disableEvent(e);

    if (e.touches.length === 0) {
      return;
    }
    const touch = e.touches[0];

    // Handle two-finger scroll first
    if (e.touches.length > 1) {
      const currentTime = Date.now();
      if (currentTime - state.lastScrollTime < scrollInterval) {
        return;
      }

      const deltaY = (touch.clientY - state.lastTouchY > 0 ? 1 : -1) * scrollDirection;
      handleMouseEvent({ type: 'wheel', deltaY });

      state.lastTouchY = touch.clientY;
      state.lastScrollTime = currentTime;
      return;
    }

    const deltaX = Math.abs(touch.clientX - state.touchStartPos.x);
    const deltaY = Math.abs(touch.clientY - state.touchStartPos.y);
    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

    const timeDelta = Date.now() - state.touchStartTime;
    const velocity = timeDelta > 0 ? distance / timeDelta : 0;

    const shouldStartDrag =
      distance > DRAG_THRESHOLD || (distance > TAP_THRESHOLD && velocity > VELOCITY_THRESHOLD);

    if (shouldStartDrag && !state.isDragging && !state.isLongPress) {
      if (!state.hasMove) {
        state.hasMove = true;
      }

      if (state.longPressTimer) {
        clearTimeout(state.longPressTimer);
        state.longPressTimer = null;
      }

      if (state.pressedButton === null) {
        state.isDragging = true;
        state.pressedButton = MouseButton.Left;
        handleMouseEvent({ type: 'mousedown', button: MouseButton.Left });
      }
    }

    if (distance > TAP_THRESHOLD && !state.hasMove) {
      state.hasMove = true;
    }

    if (state.isDragging || state.isLongPress) {
      const { x, y } = getCoordinate(touch);
      handleMouseEvent({ type: 'move', x, y });
    }
  }

  function handleTouchEnd(e: TouchEvent): void {
    disableEvent(e);

    if (state.longPressTimer) {
      clearTimeout(state.longPressTimer);
      state.longPressTimer = null;
    }

    if (!state.hasMove && !state.isLongPress) {
      handleMouseEvent({ type: 'mousedown', button: MouseButton.Left });
      setTimeout(() => {
        handleMouseEvent({ type: 'mouseup', button: MouseButton.Left });
      }, 50);
    } else if (state.pressedButton !== null) {
      handleMouseEvent({ type: 'mouseup', button: state.pressedButton });
    }

    resetTouchState();
  }

  function handleTouchCancel(e: TouchEvent): void {
    disableEvent(e);

    if (state.longPressTimer) {
      clearTimeout(state.longPressTimer);
      state.longPressTimer = null;
    }

    if (state.pressedButton !== null) {
      handleMouseEvent({ type: 'mouseup', button: state.pressedButton });
    }

    resetTouchState();
  }

  function resetTouchState(): void {
    state.isLongPress = false;
    state.hasMove = false;
    state.isDragging = false;
    state.pressedButton = null;
  }

  function cleanup(): void {
    if (state.longPressTimer) {
      clearTimeout(state.longPressTimer);
      state.longPressTimer = null;
    }
  }

  return {
    handleTouchStart,
    handleTouchMove,
    handleTouchEnd,
    handleTouchCancel,
    cleanup
  };
}


================================================
FILE: browser/src/components/mouse/types.ts
================================================
export enum MouseButton {
  Left = 0,
  Middle = 1,
  Right = 2,
  Back = 3,
  Forward = 4
}

interface MouseMoveAbsoluteEvent {
  type: 'move';
  x: number;
  y: number;
}

interface MouseMoveRelativeEvent {
  type: 'move';
  deltaX: number;
  deltaY: number;
}

interface MouseButtonEvent {
  type: 'mousedown' | 'mouseup';
  button: number;
}

interface MouseWheelEvent {
  type: 'wheel';
  deltaY: number;
}

export type MouseAbsoluteEvent = MouseMoveAbsoluteEvent | MouseButtonEvent | MouseWheelEvent;

export type MouseRelativeEvent = MouseMoveRelativeEvent | MouseButtonEvent | MouseWheelEvent;


================================================
FILE: browser/src/components/ui/kbd.tsx
================================================
import clsx from 'clsx';

function Kbd({ className, ...props }: React.ComponentProps<'kbd'>) {
  return (
    <kbd
      data-slot="kbd"
      className={clsx(
        'pointer-events-none inline-flex h-5 w-fit min-w-9 select-none items-center justify-center gap-1 rounded border-b border-b-neutral-600 bg-neutral-700/70 px-1 font-sans text-xs font-medium text-neutral-300',
        "[&_svg:not([class*='size-'])]:size-3",
        '[[data-slot=tooltip-content]_&]:text-background [[data-slot=tooltip-content]_&]:bg-background/10',
        className
      )}
      {...props}
    />
  );
}

function KbdGroup({ className, ...props }: React.ComponentProps<'div'>) {
  return (
    <kbd
      data-slot="kbd-group"
      className={clsx('inline-flex items-center gap-1', className)}
      {...props}
    />
  );
}

export { Kbd, KbdGroup };


================================================
FILE: browser/src/components/ui/scroll-area.tsx
================================================
import * as React from 'react';
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
import clsx from 'clsx';

function ScrollArea({
  className,
  children,
  ...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
  return (
    <ScrollAreaPrimitive.Root
      data-slot="scroll-area"
      className={clsx('relative', className)}
      {...props}
    >
      <ScrollAreaPrimitive.Viewport
        data-slot="scroll-area-viewport"
        className="focus-visible:ring-ring/50 size-full rounded-[inherit] outline-none transition-[color,box-shadow] focus-visible:outline-1 focus-visible:ring-[3px]"
      >
        {children}
      </ScrollAreaPrimitive.Viewport>
      <ScrollBar />
      <ScrollAreaPrimitive.Corner />
    </ScrollAreaPrimitive.Root>
  );
}

function ScrollBar({
  className,
  orientation = 'vertical',
  ...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
  return (
    <ScrollAreaPrimitive.ScrollAreaScrollbar
      data-slot="scroll-area-scrollbar"
      orientation={orientation}
      className={clsx(
        'flex touch-none select-none p-px transition-colors',
        orientation === 'vertical' && 'h-full w-2.5 border-l border-l-transparent',
        orientation === 'horizontal' && 'h-2.5 flex-col border-t border-t-transparent',
        className
      )}
      {...props}
    >
      <ScrollAreaPrimitive.ScrollAreaThumb
        data-slot="scroll-area-thumb"
        className="bg-border relative flex-1 rounded-full bg-neutral-500/30"
      />
    </ScrollAreaPrimitive.ScrollAreaScrollbar>
  );
}

export { ScrollArea, ScrollBar };


================================================
FILE: browser/src/components/virtual-keyboard/index.tsx
================================================
import { useRef, useState } from 'react';
import clsx from 'clsx';
import { useAtom } from 'jotai';
import { XIcon } from 'lucide-react';
import Keyboard, { KeyboardButtonTheme } from 'react-simple-keyboard';
import { Drawer } from 'vaul';

import 'react-simple-keyboard/build/css/index.css';
import '@/assets/keyboard.css';

import { isKeyboardOpenAtom } from '@/jotai/keyboard.ts';
import { device } from '@/libs/device';
import { KeyboardReport } from '@/libs/keyboard/keyboard.ts';

import {
  doubleKeys,
  keyboardArrowsOptions,
  keyboardControlPadOptions,
  keyboardOptions,
  modifierKeys,
  specialKeys
} from './keys.ts';

type KeyboardProps = {
  isBigScreen: boolean;
};

export const VirtualKeyboard = ({ isBigScreen }: KeyboardProps) => {
  const [isKeyboardOpen, setIsKeyboardOpen] = useAtom(isKeyboardOpenAtom);

  const [activeModifierKeys, setActiveModifierKeys] = useState<string[]>([]);

  const keyboardRef = useRef(new KeyboardReport());

  // Key down event
  async function onKeyPress(key: string): Promise<void> {
    if (modifierKeys[key]) {
      if (!activeModifierKeys.includes(key)) {
        // Save modifier key
        setActiveModifierKeys([...activeModifierKeys, key]);
      } else {
        // Press and release modifier keys
        for (const modifierKey of activeModifierKeys) {
          await handleKeyEvent({ type: 'keydown', key: modifierKey });
        }
        for (const modifierKey of activeModifierKeys) {
          await handleKeyEvent({ type: 'keyup', key: modifierKey });
        }
        setActiveModifierKeys([]);
      }
      return;
    }

    for (const modifierKey of activeModifierKeys) {
      await handleKeyEvent({ type: 'keydown', key: modifierKey });
    }

    await handleKeyEvent({ type: 'keydown', key });
  }

  // Key up event
  async function onKeyReleased(key: string): Promise<void> {
    // Skip modifier key
    if (modifierKeys[key]) {
      return;
    }

    for (const modifierKey of activeModifierKeys) {
      await handleKeyEvent({ type: 'keyup', key: modifierKey });
    }
    await handleKeyEvent({ type: 'keyup', key });

    setActiveModifierKeys([]);
  }

  async function handleKeyEvent(event: { type: 'keydown' | 'keyup'; key: string }): Promise<void> {
    const code = specialKeys[event.key] ?? event.key;

    const kb = keyboardRef.current;
    const report = event.type === 'keydown' ? kb.keyDown(code) : kb.keyUp(code);

    await device.sendKeyboardData(report);
  }

  function getButtonTheme(): KeyboardButtonTheme[] {
    const theme = [{ class: 'hg-double', buttons: doubleKeys.join(' ') }];

    if (activeModifierKeys.length > 0) {
      const buttons = activeModifierKeys.join(' ');
      theme.push({ class: 'hg-highlight', buttons });
    }

    return theme;
  }

  return (
    <Drawer.Root open={isKeyboardOpen} onOpenChange={setIsKeyboardOpen} modal={false}>
      <Drawer.Portal>
        <Drawer.Content
          className={clsx(
            'fixed bottom-0 left-0 right-0 z-[999] mx-auto overflow-hidden rounded bg-white outline-none',
            isBigScreen ? 'w-[820px]' : 'w-[650px]'
          )}
        >
          {/* header */}
          <div className="flex justify-end px-3 py-1">
            <div
              className="flex h-[20px] w-[20px] cursor-pointer items-center justify-center rounded text-neutral-600 hover:bg-neutral-300 hover:text-white"
              onClick={() => setIsKeyboardOpen(false)}
            >
              <XIcon size={18} />
            </div>
          </div>

          <div className="h-px flex-shrink-0 border-b bg-neutral-300" />

          <div data-vaul-no-drag className="keyboardContainer w-full">
            {/* main keyboard */}
            <Keyboard
              buttonTheme={getButtonTheme()}
              onKeyPress={onKeyPress}
              onKeyReleased={onKeyReleased}
              layoutName="default"
              {...keyboardOptions}
            />

            {/* control keyboard */}
            {isBigScreen && (
              <div className="controlArrows">
                <Keyboard
                  onKeyPress={onKeyPress}
                  onKeyReleased={onKeyReleased}
                  {...keyboardControlPadOptions}
                />

                <Keyboard
                  onKeyPress={onKeyPress}
                  onKeyReleased={onKeyReleased}
                  {...keyboardArrowsOptions}
                />
              </div>
            )}
          </div>
        </Drawer.Content>
        <Drawer.Overlay />
      </Drawer.Portal>
    </Drawer.Root>
  );
};


================================================
FILE: browser/src/components/virtual-keyboard/keys.ts
================================================
// main keys
export const keyboardOptions = {
  theme: 'simple-keyboard hg-theme-default',
  baseClass: 'simple-keyboard-main',
  layout: {
    default: [
      '{escape} F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12',
      'Backquote Digit1 Digit2 Digit3 Digit4 Digit5 Digit6 Digit7 Digit8 Digit9 Digit0 Minus Equal {backspace}',
      '{tab} KeyQ KeyW KeyE KeyR KeyT KeyY KeyU KeyI KeyO KeyP BracketLeft BracketRight Backslash',
      '{capslock} KeyA KeyS KeyD KeyF KeyG KeyH KeyJ KeyK KeyL Semicolon Quote {enter}',
      '{shiftleft} KeyZ KeyX KeyC KeyV KeyB KeyN KeyM Comma Period Slash {shiftright}',
      '{controlleft} {winleft} {altleft} {space} {altright} {winright} {menu} {controlright}'
    ],
    mac: [
      '{escape} F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12',
      'Backquote Digit1 Digit2 Digit3 Digit4 Digit5 Digit6 Digit7 Digit8 Digit9 Digit0 Minus Equal {backspace}',
      '{tab} KeyQ KeyW KeyE KeyR KeyT KeyY KeyU KeyI KeyO KeyP BracketLeft BracketRight Backslash',
      '{capslock} KeyA KeyS KeyD KeyF KeyG KeyH KeyJ KeyK KeyL Semicolon Quote {enter}',
      '{shiftleft} KeyZ KeyX KeyC KeyV KeyB KeyN KeyM Comma Period Slash {shiftright}',
      '{controlleft} {altleft} {metaleft} {space} {metaright} {altright}'
    ]
  },
  display: {
    '{escape}': 'Esc',
    Backquote: '~<br/>`',
    Digit1: '!<br/>1',
    Digit2: '@<br/>2',
    Digit3: '#<br/>3',
    Digit4: '$<br/>4',
    Digit5: '%<br/>5',
    Digit6: '^<br/>6',
    Digit7: '&<br/>7',
    Digit8: '*<br/>8',
    Digit9: '(<br/>9',
    Digit0: ')<br/>0',
    Minus: '_<br/>-',
    Equal: '+<br/>=',
    '{backspace}': 'Backspace',

    '{tab}': 'Tab',
    KeyQ: 'Q',
    KeyW: 'W',
    KeyE: 'E',
    KeyR: 'R',
    KeyT: 'T',
    KeyY: 'Y',
    KeyU: 'U',
    KeyI: 'I',
    KeyO: 'O',
    KeyP: 'P',
    BracketLeft: '{<br/>[',
    BracketRight: '}<br/>]',
    Backslash: '|<br>\\',

    '{capslock}': 'Caps',
    KeyA: 'A',
    KeyS: 'S',
    KeyD: 'D',
    KeyF: 'F',
    KeyG: 'G',
    KeyH: 'H',
    KeyJ: 'J',
    KeyK: 'K',
    KeyL: 'L',
    Semicolon: ':<br/>;',
    Quote: '"<br/>\'',
    '{enter}': 'Enter',

    '{shiftleft}': 'Shift',
    KeyZ: 'Z',
    KeyX: 'X',
    KeyC: 'C',
    KeyV: 'V',
    KeyB: 'B',
    KeyN: 'N',
    KeyM: 'M',
    Comma: '<<br/>,',
    Period: '><br/>.',
    Slash: '?<br/>/',
    '{shiftright}': 'Shift',

    '{controlleft}': 'Ctrl',
    '{altleft}': 'Alt',
    '{metaleft}': 'Cmd',
    '{winleft}': 'Win',
    '{space}': 'Space',
    '{metaright}': 'Cmd',
    '{winright}': 'Win',
    '{altright}': 'Alt',
    '{menu}': 'Menu',
    '{controlright}': 'Ctrl'
  }
};

// control keys
export const keyboardControlPadOptions = {
  theme: 'simple-keyboard hg-theme-default',
  baseClass: 'simple-keyboard-control',
  layout: {
    default: [
      '{prtscr} {scrolllock} {pause}',
      '{insert} {home} {pageup}',
      '{delete} {end} {pagedown}'
    ]
  },

  display: {
    '{prtscr}': 'PrtScr',
    '{scrolllock}': 'Lock',
    '{pause}': 'Pause',
    '{insert}': 'Ins',
    '{home}': 'Home',
    '{pageup}': 'PgUp',
    '{delete}': 'Del',
    '{end}': 'End',
    '{pagedown}': 'PgDn'
  }
};

// arrow keys
export const keyboardArrowsOptions = {
  theme: 'simple-keyboard hg-theme-default',
  baseClass: 'simple-keyboard-arrows',
  layout: {
    default: ['{arrowup}', '{arrowleft} {arrowdown} {arrowright}']
  }
};

// keys require special mapping
export const specialKeys: Record<string, string> = {
  '{escape}': 'Escape',
  '{backspace}': 'Backspace',
  '{tab}': 'Tab',
  '{capslock}': 'CapsLock',
  '{enter}': 'Enter',
  '{shiftleft}': 'ShiftLeft',
  '{shiftright}': 'ShiftRight',
  '{controlleft}': 'ControlLeft',
  '{controlright}': 'ControlRight',
  '{altleft}': 'AltLeft',
  '{metaleft}': 'MetaLeft',
  '{winleft}': 'WinLeft',
  '{space}': 'Space',
  '{metaright}': 'MetaRight',
  '{winright}': 'WinRight',
  '{altright}': 'AltRight',
  '{prtscr}': 'PrintScreen',
  '{scrolllock}': 'ScrollLock',
  '{pause}': 'Pause',
  '{insert}': 'Insert',
  '{home}': 'Home',
  '{pageup}': 'PageUp',
  '{delete}': 'Delete',
  '{end}': 'End',
  '{pagedown}': 'PageDown',
  '{arrowright}': 'ArrowRight',
  '{arrowleft}': 'ArrowLeft',
  '{arrowdown}': 'ArrowDown',
  '{arrowup}': 'ArrowUp'
};

// modifier keys
export const modifierKeys: Record<string, string> = {
  '{shiftleft}': 'ShiftLeft',
  '{controlleft}': 'ControlLeft',
  '{altleft}': 'AltLeft',
  '{metaleft}': 'MetaLeft',
  '{winleft}': 'WinLeft',
  '{shiftright}': 'ShiftRight',
  '{controlright}': 'ControlRight',
  '{altright}': 'AltRight',
  '{metaright}': 'MetaRight',
  '{winright}': 'WinRight'
};

// double line display buttons
export const doubleKeys = [
  'Backquote',
  'Digit1',
  'Digit2',
  'Digit3',
  'Digit4',
  'Digit5',
  'Digit6',
  'Digit7',
  'Digit8',
  'Digit9',
  'Digit0',
  'Minus',
  'Equal',
  'BracketLeft',
  'BracketRight',
  'Backslash',
  'Semicolon',
  'Quote',
  'Comma',
  'Period',
  'Slash'
];


================================================
FILE: browser/src/i18n/index.ts
================================================
import i18n from 'i18next';
import type { Resource } from 'i18next';
import { initReactI18next } from 'react-i18next';

import { getLanguage } from '@/libs/storage';

function getResources(): Resource {
  const resources: Resource = {};

  const modules: Record<string, Resource> = import.meta.glob('./locales/*.ts', { eager: true });

  for (const path in modules) {
    const moduleName = path.split('/').pop()?.replace('.ts', '');
    if (moduleName) {
      resources[moduleName] = modules[path].default;
    }
  }

  return resources;
}

function getCurrentLanguage(): string {
  const languages = Object.keys(resources);

  const cookieLng = getLanguage();
  if (cookieLng && languages.includes(cookieLng)) {
    return cookieLng;
  }

  const navigatorLng = navigator.language.split('-')[0];
  if (languages.includes(navigatorLng)) {
    return navigatorLng;
  }

  return 'en';
}

const resources = getResources();
const lng = getCurrentLanguage();

i18n
  .use(initReactI18next)
  .init({
    resources,
    lng,
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false
    }
  })
  .then();

export default i18n;


================================================
FILE: browser/src/i18n/languages.ts
================================================
const languages = [
  { key: 'en', name: 'English' },
  { key: 'ru', name: 'Русский' },
  { key: 'zh', name: '简体中文' },
  { key: 'zh_tw', name: '繁體中文' },
  { key: 'de', name: 'Deutsch' },
  { key: 'nl', name: 'Nederlands' },
  { key: 'be', name: 'België' },
  { key: 'ko', name: '한국어' },
  { key: 'pt_br', name: 'Português (Brasil)' },
  { key: 'pl', name: 'Polski' }
];

languages.sort((a, b) => a.name.localeCompare(b.name, 'en', { sensitivity: 'base' }));

export default languages;


================================================
FILE: browser/src/i18n/locales/be.ts
================================================
const be = {
  translation: {
    serial: {
      notSupported:
        'Seriële poort wordt niet ondersteund. Gebruik de desktop Chrome-browser om muis en klavier te gebruiken.',
      failed: 'Verbinding met seriële poort mislukt. Probeer opnieuw'
    },
    camera: {
      tip: 'Wachten op toelating...',
      denied: 'Toelating geweigerd',
      authorize:
        'De externe desktop vereist cameratoegang. Geef toelating voor de camera in de browserinstellingen.',
      failed: 'Kan geen verbinding maken met de camera. Probeer opnieuw.'
    },
    modal: {
      title: 'Kies USB-apparaat',
      selectVideo: 'Kies een video-invoerapparaat',
      selectSerial: 'Kies serieel apparaat'
    },
    menu: {
      serial: 'Serieel',
      keyboard: 'Klavier',
      mouse: 'Muis'
    },
    video: {
      resolution: 'Resolutie',
      scale: 'Schaal',
      customResolution: 'Aangepast',
      device: 'Toestel',
      custom: {
        title: 'Aangepaste resolutie',
        width: 'Breedte',
        height: 'Hoogte',
        confirm: 'OK',
        cancel: 'Annuleren'
      }
    },
    keyboard: {
      paste: 'Plakken',
      virtualKeyboard: 'Virtueel klavier',
      shortcut: {
        title: 'Sneltoetsen',
        ctrlAltDel: 'Ctrl + Alt + Delete',
        ctrlD: 'Ctrl + D',
        winTab: 'Win + Tab'
      }
    },
    mouse: {
      cursor: {
        title: 'Muisaanwijzer',
        pointer: 'Wijzer',
        grab: 'Hand',
        cell: 'Kruis',
        hide: 'Verborgen'
      },
      mode: 'Muismodus',
      absolute: 'Absolute modus',
      relative: 'Relatieve modus',
      direction: 'Scrollrichting',
      scrollUp: 'Omhoog scrollen',
      scrollDown: 'Omlaag scrollen',
      requestPointer:
        'Gebruik relatieve modus. Klik op het bureaublad om de muisaanwijzer vast te nemen.'
    },
    settings: {
      language: 'Taal',
      document: 'Document',
      download: 'Download'
    }
  }
};

export default be;


================================================
FILE: browser/src/i18n/locales/de.ts
================================================
const de = {
  translation: {
    serial: {
      notSupported:
        'Seriell nicht unterstützt. Bitte benutze den Desktop Chrome Browser um Maus und Tastatur zu verwenden.',
      failed: 'Verbindung zu Seriell fehlgeschlagen. Bitte erneut versuchen'
    },
    camera: {
      tip: 'Warten auf Berechtigung...',
      denied: 'Berechtigung verweigert',
      authorize:
        'Der Remote-Desktop erfordert eine Kamerazulassung. Bitte autorisieren Sie die Kamera in den Browsereinstellungen.',
      failed: 'Kamera konnte nicht verbunden werden. Bitte versuche es erneut.'
    },
    modal: {
      title: 'USB-Gerät auswählen',
      selectVideo: 'Bitte wähle ein Video-Eingabegerät aus',
      selectSerial: 'Serielles Gerät auswählen'
    },
    menu: {
      serial: 'Seriell',
      keyboard: 'Tastatur',
      mouse: 'Maus'
    },
    video: {
      resolution: 'Auflösung',
      scale: 'Skalierung',
      customResolution: 'Benutzerdefiniert',
      device: 'Gerät',
      custom: {
        title: 'Benutzerdefinierte Aufösung',
        width: 'Breite',
        height: 'Höhe',
        confirm: 'Ok',
        cancel: 'Abbrechen'
      }
    },
    keyboard: {
      paste: 'Einfügen',
      virtualKeyboard: 'Virtuelle Tastatur',
      shortcut: {
        title: 'Tastenkürzel',
        ctrlAltDel: 'Strg + Alt + Entfernen',
        ctrlD: 'Strg + D',
        winTab: 'Win + Tab'
      }
    },
    mouse: {
      cursor: {
        title: 'Mauszeiger',
        pointer: 'Zeiger',
        grab: 'Hand',
        cell: 'Kreuz',
        hide: 'Versteckt'
      },
      mode: 'Mausmodus',
      absolute: 'Absoluter Modus',
      relative: 'Relativer Mode',
      direction: 'Scrollrichtung',
      scrollUp: 'Hochscrollen',
      scrollDown: 'Runterscrollen',
      speed: 'Scrollgeschwindigkeit',
      fast: 'Schnell',
      slow: 'Langsam',
      requestPointer:
        'Benutze relativen Modus. Bitte auf den Desktop klicken, um den Mauszeiger anzuzeigen.'
    },
    settings: {
      language: 'Sprache',
      document: 'Dokument',
      download: 'Download'
    }
  }
};

export default de;


================================================
FILE: browser/src/i18n/locales/en.ts
================================================
const en = {
  translation: {
    serial: {
      notSupported:
        'Serial not supported. Please use the desktop Chrome browser to enable mouse and keyboard.',
      failed: 'Failed to connect serial. Please try again'
    },
    camera: {
      tip: 'Waiting for authorization...',
      denied: 'Permission Denied',
      authorize:
        'Remote desktop requires camera permission. Please authorize camera in browser settings.',
      failed: 'Failed to connect camera. Please try again.'
    },
    modal: {
      title: 'Select USB Device',
      selectVideo: 'Please select a video input device',
      selectSerial: 'Select serial device'
    },
    menu: {
      serial: 'Serial',
      keyboard: 'Keyboard',
      mouse: 'Mouse'
    },
    video: {
      resolution: 'Resolution',
      scale: 'Scale',
      auto: "Auto",
      rotation: 'Rotation',
      customResolution: 'Custom',
      device: 'Device',
      custom: {
        title: 'Custom Resolution',
        width: 'Width',
        height: 'Height',
        confirm: 'Ok',
        cancel: 'Cancel'
      }
    },
    audio: {
      tip: 'Tip',
      permission:
        'Microphone access is required to connect your USB audio device. The operating system classifies USB inputs as microphones, so this permission is necessary.\n\nThis action is solely for device connectivity and does not enable audio recording.',
      viewDoc: 'View document.',
      ok: 'Ok'
    },
    keyboard: {
      paste: 'Paste',
      virtualKeyboard: 'Keyboard',
      shortcut: {
        title: 'Shortcuts',
        custom: 'Custom',
        capture: 'Click here to capture shortcut',
        clear: 'Clear',
        save: 'Save',
        captureTips:
          'Capturing system-level keys (such as the Windows key) requires full-screen permission.',
        enterFullScreen: 'Toggle full-screen mode.'
      }
    },
    mouse: {
      cursor: {
        title: 'Cursor',
        pointer: 'Pointer',
        grab: 'Grab',
        cell: 'Cell',
        hide: 'Hide'
      },
      mode: 'Mouse mode',
      absolute: 'Absolute mode',
      relative: 'Relative mode',
      direction: 'Wheel direction',
      scrollUp: 'Scroll up',
      scrollDown: 'Scroll down',
      speed: 'Wheel speed',
      fast: 'Fast',
      slow: 'Slow',
      requestPointer: 'Using relative mode. Please click desktop to get mouse pointer.',
      jiggler: {
        title: 'Mouse Jiggler',
        enable: 'Enable',
        disable: 'Disable'
      }
    },
    settings: {
      language: 'Language',
      document: 'Document',
      download: 'Download'
    }
  }
};

export default en;


================================================
FILE: browser/src/i18n/locales/ko.ts
================================================
const ko = {
  translation: {
    serial: {
      notSupported:
        '시리얼이 지원되지 않습니다. 마우스와 키보드를 사용하려면 Chrome 브라우저를 사용하세요.',
      failed: '시리얼 연결에 실패했습니다. 다시 시도해 주세요.'
    },
    camera: {
      tip: '권한을 기다리는 중...',
      denied: '권한이 거부되었습니다.',
      authorize:
        'Target PC 연결에 카메라 권한이 필요합니다. 브라우저 설정에서 카메라 권한을 허용해 주세요.',
      failed: '카메라 연결에 실패했습니다. 다시 시도해 주세요.'
    },
    modal: {
      title: 'USB 장치 선택',
      selectVideo: '비디오 입력 장치를 선택해 주세요.',
      selectSerial: '시리얼 장치를 선택해 주세요.'
    },
    menu: {
      serial: '시리얼',
      keyboard: '키보드',
      mouse: '마우스'
    },
    video: {
      resolution: '해상도',
      scale: '배율',
      customResolution: '사용자 정의',
      device: '장치',
      custom: {
        title: '사용자 정의 해상도',
        width: '가로',
        height: '세로',
        confirm: '확인',
        cancel: '취소'
      }
    },
    keyboard: {
      paste: '붙여넣기',
      virtualKeyboard: '가상 키보드',
      shortcut: {
        ctrlAltDel: 'Ctrl + Alt + Delete',
        ctrlD: 'Ctrl + D',
        winTab: 'Win + Tab'
      }
    },
    mouse: {
      cursor: {
        title: '커서 모양',
        pointer: '포인터',
        grab: '손',
        cell: '플러스',
        hide: '숨기기'
      },
      mode: '마우스 모드',
      absolute: '절대 모드',
      relative: '상대 모드',
      direction: '휠 방향',
      scrollUp: '위로 스크롤',
      scrollDown: '아래로 스크롤',
      speed: '휠 속도',
      fast: '빠르게',
      slow: '느리게',
      requestPointer: '상대 모드를 사용 중입니다. 마우스 포인터를 가져오려면 스크린을 클릭하세요.'
    },
    settings: {
      language: '언어',
      document: '문서',
      download: '다운로드'
    }
  }
};

export default ko;


================================================
FILE: browser/src/i18n/locales/nl.ts
================================================
const nl = {
  translation: {
    serial: {
      notSupported:
        'Seriële poort wordt niet ondersteund. Gebruik de desktop Chrome-browser om muis en toetsenbord te gebruiken.',
      failed: 'Verbinding met seriële poort mislukt. Probeer het opnieuw'
    },
    camera: {
      tip: 'Wachten op toestemming...',
      denied: 'Toestemming geweigerd',
      authorize:
        'De externe desktop vereist cameratoegang. Geef toestemming voor de camera in de browserinstellingen.',
      failed: 'Kan geen verbinding maken met de camera. Probeer het opnieuw.'
    },
    modal: {
      title: 'Selecteer USB-apparaat',
      selectVideo: 'Selecteer een video-invoerapparaat',
      selectSerial: 'Selecteer serieel apparaat'
    },
    menu: {
      serial: 'Serieel',
      keyboard: 'Toetsenbord',
      mouse: 'Muis'
    },
    video: {
      resolution: 'Resolutie',
      scale: 'Schaal',
      customResolution: 'Aangepast',
      device: 'Apparaat',
      custom: {
        title: 'Aangepaste resolutie',
        width: 'Breedte',
        height: 'Hoogte',
        confirm: 'OK',
        cancel: 'Annuleren'
      }
    },
    keyboard: {
      paste: 'Plakken',
      virtualKeyboard: 'Virtueel toetsenbord',
      shortcut: {
        title: 'Sneltoetsen',
        ctrlAltDel: 'Ctrl + Alt + Delete',
        ctrlD: 'Ctrl + D',
        winTab: 'Win + Tab'
      }
    },
    mouse: {
      cursor: {
        title: 'Muiscursor',
        pointer: 'Aanwijzer',
        grab: 'Hand',
        cell: 'Kruis',
        hide: 'Verborgen'
      },
      mode: 'Muismodus',
      absolute: 'Absolute modus',
      relative: 'Relatieve modus',
      direction: 'Scrollrichting',
      scrollUp: 'Omhoog scrollen',
      scrollDown: 'Omlaag scrollen',
      requestPointer:
        'Gebruik relatieve modus. Klik op het bureaublad om de muisaanwijzer vast te leggen.'
    },
    settings: {
      language: 'Taal',
      document: 'Document',
      download: 'Download'
    }
  }
};

export default nl;


================================================
FILE: browser/src/i18n/locales/pl.ts
================================================
const pl = {
  translation: {
    serial: {
      notSupported:
        'Przeglądarka nie obsługuje portu szeregowego. Proszę użyć przeglądarki Chrome (desktop) aby włączyć obsługę myszy i klawiatury.',
      failed: 'Nie udało połączyć się z portem szeregowym. Spróbuj ponownie.'
    },
    camera: {
      tip: 'Oczekiwanie na autoryzację...',
      denied: 'Brak uprawnień',
      authorize:
        'Zdalny pulpit wymaga uprawnienia dostępu do kamery. Zezwól na dostęp do kamery w ustawieniach przeglądarki.',
      failed: 'Nie udało połączyć się z kamerą. Spróbuj ponownie.'
    },
    modal: {
      title: 'Wybierz urządzenie USB',
      selectVideo: 'Wybierz urządzenie wejścia wideo',
      selectSerial: 'Wybierz urządzenie portu szeregowego'
    },
    menu: {
      serial: 'Port szeregowy',
      keyboard: 'Klawiatura',
      mouse: 'Mysz'
    },
    video: {
      resolution: 'Rozdzielczość',
      customResolution: 'Niestandardowa',
      device: 'Urządzenie',
      custom: {
        title: 'Niestandardowa rozdzielczość',
        width: 'Szerokość',
        height: 'Wysokość',
        confirm: 'Ok',
        cancel: 'Anuluj'
      }
    },
    keyboard: {
      paste: 'Wklej',
      virtualKeyboard: 'Klawiatura',
      shortcut: {
        ctrlAltDel: 'Ctrl + Alt + Delete',
        ctrlD: 'Ctrl + D',
        winTab: 'Win + Tab'
      }
    },
    mouse: {
      cursor: {
        title: 'Kursor',
        pointer: 'Wskaźnik',
        grab: 'Chwyć',
        cell: 'Zaznacz',
        hide: 'Ukryj'
      },
      mode: 'Tryb myszy',
      absolute: 'Tryb absolutny',
      relative: 'Tryb względny',
      direction: 'Kierunek kółka przewijania',
      scrollUp: 'Przewijanie w górę',
      scrollDown: 'Przewijanie w dół',
      speed: 'Szybkość kółka',
      fast: 'Szybko',
      slow: 'Powoli',
      requestPointer:
        'Użycie trybu względnego. Proszę kliknij na pulpicie aby aktywować wskaźnik myszy.'
    },
    settings: {
      language: 'Język',
      document: 'Dokumentacja',
      download: 'Pobieranie'
    }
  }
};

export default pl;


================================================
FILE: browser/src/i18n/locales/pt_br.ts
================================================
const pt_br = {
  translation: {
    serial: {
      notSupported:
        'Serial não suportado. Use o navegador Chrome para habilitar o mouse e teclado.',
      failed: 'Falha ao se conectar na porta serial. Tente novamente'
    },
    camera: {
      tip: 'Esperando autorização...',
      denied: 'Permissão negada',
      authorize:
        'A área de trabalho remota requer permissão de uso da câmera. Por favor, conceda as permissões de câmera nos ajustes do navegador.',
      failed: 'Falha ao se conectar à câmera. Tente novamente.'
    },
    modal: {
      title: 'Selecione o dispositivo USB',
      selectVideo: 'Selecione um dispositivo de vídeo de entrada',
      selectSerial: 'Selecione um dispositivo serial'
    },
    menu: {
      serial: 'Serial',
      keyboard: 'Teclado',
      mouse: 'Mouse'
    },
    video: {
      resolution: 'Resolução',
      customResolution: 'Personalizada',
      device: 'Dispositivo',
      custom: {
        title: 'Resolução Personalizada',
        width: 'Largura',
        height: 'Altura',
        confirm: 'Ok',
        cancel: 'Cancelar'
      }
    },
    keyboard: {
      paste: 'Colar',
      virtualKeyboard: 'Teclado Virtual',
      shortcut: {
        ctrlAltDel: 'Ctrl + Alt + Delete',
        ctrlD: 'Ctrl + D',
        winTab: 'Win + Tab'
      }
    },
    mouse: {
      cursor: {
        title: 'Cursor',
        pointer: 'Ponteiro',
        grab: 'Mão',
        cell: 'Célula',
        hide: 'Esconder'
      },
      mode: 'Modo do mouse',
      absolute: 'Modo absoluto',
      relative: 'Modo relativo',
      direction: 'Direção do scroll',
      scrollUp: 'Scroll para cima',
      scrollDown: 'Scroll para baixo',
      speed: 'Velocidade do scroll',
      fast: 'Rápido',
      slow: 'Lento',
      requestPointer:
        'Usando modo relativo. Por favor, clique na área de trabalho para restaurar o ponteiro do mouse.'
    },
    settings: {
      language: 'Linguagem',
      document: 'Documentação',
      download: 'Download'
    }
  }
};

export default pt_br;


================================================
FILE: browser/src/i18n/locales/ru.ts
================================================
const ru = {
  translation: {
    serial: {
      notSupported:
        'Подключение к последовательному порту не поддерживается. Чтобы пользоваться мышью и клавиатурой, используйте браузер Chrome для настольных компьютеров.',
      failed:
        'Не удалось установить подключение к последовательному порту. Пожалуйста, попробуйте еще раз.'
    },
    camera: {
      tip: 'Ожидание доступа...',
      denied: 'Доступ отказан',
      authorize:
        'Для удаленного рабочего стола требуется доступ к камере. Пожалуйста, разрешите доступ к камере в настройках браузера.',
      failed: 'Не удалось подключить камеру. Пожалуйста, попробуйте еще раз.'
    },
    modal: {
      title: 'Выберите устройство USB',
      selectVideo: 'Выбрать источник видео',
      selectSerial: 'Выбрать последовательный порт'
    },
    menu: {
      serial: 'Последовательный порт',
      keyboard: 'Клавиатура',
      mouse: 'Мышь'
    },
    video: {
      resolution: 'Разрешение',
      scale: 'Масштаб',
      customResolution: 'Пользовательское',
      device: 'Видеоустройство',
      custom: {
        title: 'Пользовательское разрешение',
        width: 'Ширина',
        height: 'Высота',
        confirm: 'Ок',
        cancel: 'Отмена'
      }
    },
    keyboard: {
      paste: 'Вставить текст',
      virtualKeyboard: 'Виртуальная клавиатура',
      shortcut: {
        title: 'Сочетания клавиш',
        ctrlAltDel: 'Ctrl + Alt + Delete',
        ctrlD: 'Ctrl + D',
        winTab: 'Win + Tab'
      }
    },
    mouse: {
      cursor: {
        title: 'Курсор',
        pointer: 'Указатель',
        grab: 'Захват',
        cell: 'Прицел',
        hide: 'Скрытый'
      },
      mode: 'Режим мыши',
      absolute: 'Абсолютное позиционирование',
      relative: 'Относительное позиционирование',
      direction: 'Направление прокрутки',
      scrollUp: 'Обычное',
      scrollDown: 'Инвертированное',
      speed: 'Скорость прокрутки',
      fast: 'Быстро',
      slow: 'Медленно',
      requestPointer:
        'Используется относительное позиционирование мыши. Чтобы захватить курсор, щелкните по видео на экране'
    },
    settings: {
      language: 'Язык приложения',
      document: 'Документация',
      download: 'Загрузить'
    }
  }
};

export default ru;


================================================
FILE: browser/src/i18n/locales/zh.ts
================================================
const zh = {
  translation: {
    serial: {
      notSupported: '当前浏览器不支持串口,无法使用键鼠。请使用桌面版 Chrome 浏览器。',
      failed: '串口连接失败,请重试。'
    },
    camera: {
      tip: '等待授权...',
      denied: '权限不足',
      authorize: '远程桌面需要获取摄像头权限,请在浏览器设置中允许使用摄像头。',
      failed: '摄像头连接失败,请重试。'
    },
    modal: {
      title: '选择 USB 设备',
      selectVideo: '请选择视频输入设备',
      selectSerial: '选择串口设备'
    },
    menu: {
      serial: '串口',
      keyboard: '键盘',
      mouse: '鼠标'
    },
    video: {
      resolution: '分辨率',
      scale: '缩放',
      auto: '自动',
      rotation: '旋转',
      customResolution: '自定义',
      device: '设备',
      custom: {
        title: '自定义分辨率',
        width: '宽度',
        height: '高度',
        confirm: '确定',
        cancel: '取消'
      }
    },
    audio: {
      tip: '提示',
      permission:
        '网页需要麦克风权限来获取 USB 设备的音频信号。因为电脑系统会将 USB 音频输入设备识别为麦克风,而非扬声器。\n\n此操作仅用于设备连接,不会录制任何声音。',
      viewDoc: '查看文档。',
      ok: '确定'
    },
    keyboard: {
      paste: '粘贴',
      virtualKeyboard: '虚拟键盘',
      shortcut: {
        title: '快捷键',
        custom: '自定义',
        capture: '点击此处捕获快捷键',
        clear: '清空',
        save: '保存',
        captureTips: '捕获系统级按键(如 Windows 键)需要全屏权限。',
        enterFullScreen: '切换全屏模式。'
      }
    },
    mouse: {
      cursor: {
        title: '鼠标指针',
        pointer: '箭头',
        grab: '抓取',
        cell: '单元',
        hide: '隐藏'
      },
      mode: '鼠标模式',
      absolute: '绝对模式',
      relative: '相对模式',
      direction: '滚轮方向',
      scrollUp: '向上',
      scrollDown: '向下',
      speed: '滚轮速度',
      fast: '快',
      slow: '慢',
      requestPointer: '正在使用鼠标相对模式,请点击桌面获取鼠标指针。',
      jiggler: {
        title: '空闲晃动',
        enable: '启用',
        disable: '禁用'
      }
    },
    settings: {
      language: '语言',
      document: '文档',
      download: '下载'
    }
  }
};

export default zh;


================================================
FILE: browser/src/i18n/locales/zh_tw.ts
================================================
const zh_tw = {
  translation: {
    serial: {
      notSupported: '當前瀏覽器不支援序列埠,無法使用鍵鼠。請使用桌面版 Chrome 瀏覽器。',
      failed: '序列埠連線失敗,請重試。'
    },
    camera: {
      tip: '等待授權中...',
      denied: '權限不足',
      authorize: '遠端桌面需要取得攝影機權限,請在瀏覽器設定中允許使用攝影機。',
      failed: '攝影機連線失敗,請重試。'
    },
    modal: {
      title: '選擇 USB 裝置',
      selectVideo: '請選擇視訊輸入裝置',
      selectSerial: '選擇序列埠裝置'
    },
    menu: {
      serial: '序列埠',
      keyboard: '鍵盤',
      mouse: '滑鼠'
    },
    video: {
      resolution: '解析度',
      customResolution: '自訂',
      device: '裝置',
      custom: {
        title: '自訂解析度',
        width: '寬度',
        height: '高度',
        confirm: '確定',
        cancel: '取消'
      }
    },
    keyboard: {
      paste: '貼上',
      virtualKeyboard: '虛擬鍵盤',
      shortcut: {
        ctrlAltDel: 'Ctrl + Alt + Delete',
        ctrlD: 'Ctrl + D',
        winTab: 'Win + Tab'
      }
    },
    mouse: {
      cursor: {
        title: '滑鼠指標',
        pointer: '箭頭',
        grab: '抓取',
        cell: '格線',
        hide: '隱藏'
      },
      mode: '滑鼠模式',
      absolute: '絕對模式',
      relative: '相對模式',
      direction: '滾輪方向',
      scrollUp: '向上',
      scrollDown: '向下',
      speed: '滾輪速度',
      fast: '快',
      slow: '慢',
      requestPointer: '正在使用滑鼠相對模式,請點擊桌面取得滑鼠指標。'
    },
    settings: {
      language: '語言',
      document: '文件',
      download: '下載'
    }
  }
};

export default zh_tw;


================================================
FILE: browser/src/jotai/device.ts
================================================
import { atom } from 'jotai';

import type { Resolution, Rotation } from '@/types.ts';

type VideoState = 'disconnected' | 'connecting' | 'connected';
type SerialState = 'notSupported' | 'disconnected' | 'connecting' | 'connected';

export const resolutionAtom = atom<Resolution>({
  width: 1920,
  height: 1080
});

export const videoScaleAtom = atom<number>(1.0);

export const videoRotationAtom = atom<Rotation>(0);

export const videoDeviceIdAtom = atom('');
export const videoStateAtom = atom<VideoState>('disconnected');

export const serialStateAtom = atom<SerialState>('disconnected');


================================================
FILE: browser/src/jotai/keyboard.ts
================================================
import { atom } from 'jotai';

export const isKeyboardEnableAtom = atom(true);

export const isKeyboardOpenAtom = atom(false);


================================================
FILE: browser/src/jotai/mouse.ts
================================================
// mouse cursor style
import { atom } from 'jotai';

export const mouseStyleAtom = atom('cursor-default');

// mouse mode: absolute or relative
export const mouseModeAtom = atom('absolute');

// mouse scroll direction: 1 or -1
export const scrollDirectionAtom = atom(-1);

// mouse scroll interval (unit: ms)
// mouse scroll interval (unit: ms)
export const scrollIntervalAtom = atom(0);

// mouse jiggler mode: enable or disable
export const mouseJigglerModeAtom = atom<'enable' | 'disable'>('disable');


================================================
FILE: browser/src/libs/browser/index.ts
================================================
export type System = 'Windows' | 'macOS' | 'Linux' | 'Unknown';

export interface BrowserInfo {
  os: System;
  isChrome: boolean;
}

export function getOperatingSystem(): System {
  if (typeof window === 'undefined') {
    return 'Unknown';
  }

  if ('userAgentData' in navigator) {
    // @ts-expect-error check userAgentData.platform
    const platform = navigator.userAgentData?.platform?.toLowerCase();
    if (platform) {
      if (platform === 'windows') return 'Windows';
      if (platform === 'macos') return 'macOS';
      if (platform === 'linux' || platform === 'android') return 'Linux';
    }
  }

  // Fallback to User Agent
  const userAgent = navigator.userAgent;

  if (/Win/i.test(userAgent)) return 'Windows';
  if (/Mac|iPhone|iPod|iPad/i.test(userAgent)) return 'macOS';
  if (/Linux|Android/i.test(userAgent)) return 'Linux';

  return 'Unknown';
}

export function isChromeBrowser(): boolean {
  if (typeof window === 'undefined' || !window.navigator) {
    return false;
  }

  if ('userAgentData' in navigator) {
    // @ts-expect-error userAgentData.brands
    return navigator.userAgentData?.brands?.some(
      (brand: any) => brand.brand === 'Google Chrome' || brand.brand === 'Chromium'
    );
  }

  const userAgent = navigator.userAgent;
  const vendor = navigator.vendor;

  return (
    /Chrome|Chromium/.test(userAgent) &&
    /Google Inc/.test(vendor) &&
    !/Edg/.test(userAgent) &&
    !/OPR/.test(userAgent)
  );
}

export function getBrowserInfo(): BrowserInfo {
  return {
    os: getOperatingSystem(),
    isChrome: isChromeBrowser()
  };
}


================================================
FILE: browser/src/libs/device/index.ts
================================================
import { CmdEvent, CmdPacket, InfoPacket } from './proto.ts';
import { SerialPort } from './serial-port.ts';

export class Device {
  addr: number;
  serialPort: SerialPort;

  constructor() {
    this.addr = 0x00;
    this.serialPort = new SerialPort();
  }

  async getInfo() {
    const data = new CmdPacket(this.addr, CmdEvent.GET_INFO).encode();
    await this.serialPort.write(data);

    const rsp = await this.serialPort.read(14);
    const rspPacket = new CmdPacket(-1, -1, rsp);
    return new InfoPacket(rspPacket.DATA);
  }

  async sendKeyboardData(report: number[]): Promise<void> {
    const cmdData = new CmdPacket(this.addr, CmdEvent.SEND_KB_GENERAL_DATA, report).encode();
    await this.serialPort.write(cmdData);
  }

  async sendMouseData(report: number[]): Promise<void> {
    if (report.length === 0) return;

    const cmdEvent = report[0] === 0x01 ? CmdEvent.SEND_MS_REL_DATA : CmdEvent.SEND_MS_ABS_DATA;
    const cmdData = new CmdPacket(this.addr, cmdEvent, report).encode();
    await this.serialPort.write(cmdData);
  }
}

export const device = new Device();


================================================
FILE: browser/src/libs/device/proto.ts
================================================
export enum CmdEvent {
  GET_INFO = 0x01,
  SEND_KB_GENERAL_DATA = 0x02,
  SEND_KB_MEDIA_DATA = 0x03,
  SEND_MS_ABS_DATA = 0x04,
  SEND_MS_REL_DATA = 0x05,
  SEND_MY_HID_DATA = 0x06,
  READ_MY_HID_DATA = 0x87,
  GET_PARA_CFG = 0x08,
  SET_PARA_CFG = 0x09,
  GET_USB_STRING = 0x0a,
  SET_USB_STRING = 0x0b,
  SET_DEFAULT_CFG = 0x0c,
  RESET = 0x0f
}

export class CmdPacket {
  readonly HEAD1: number = 0x57;
  readonly HEAD2: number = 0xab;

  ADDR: number = 0x00;
  CMD: number = 0x00;
  LEN: number = 0x00;
  DATA: number[] = [];
  SUM: number = 0x00;

  constructor(addr: number = 0x00, cmd: number = 0x00, data: number[] = []) {
    if (addr < 0 || cmd < 0) {
      this.decode(data);
      return;
    }
    this.save(addr, cmd, data);
  }

  encode(): number[] {
    return [this.HEAD1, this.HEAD2, this.ADDR, this.CMD, this.LEN, ...this.DATA, this.SUM];
  }

  public decode(data: number[]): number {
    const headerIndex = this.findHead(data);
    if (headerIndex < 0) {
      console.log('cannot find HEAD');
      return -1;
    }

    if (data.length - headerIndex < 6) {
      console.log('len error1');
      return -1;
    }

    const addr = data[headerIndex + 2];
    const cmd = data[headerIndex + 3];
    const dataLen = data[headerIndex + 4];

    if (data.length < headerIndex + 3 + dataLen + 1) {
      console.log('len error2');
      return -1;
    }

    let sum: number;
    try {
      sum = data[headerIndex + 5 + dataLen];
    } catch {
      console.log('len error3');
      return -1;
    }

    let s = 0;
    for (let i = headerIndex; i < headerIndex + 4 + dataLen; i++) {
      s += data[i];
    }

    if ((s & 0xff) !== sum) {
      // console.log(`sum error, sum${sum}, s${s & 0xff}`);
      return -1;
    }

    this.ADDR = addr;
    this.CMD = cmd;
    this.LEN = dataLen;
    this.DATA = data.slice(headerIndex + 5, headerIndex + 5 + this.LEN);
    this.SUM = sum;
    return 0;
  }

  private findHead(lst: number[]): number {
    const subsequence = [this.HEAD1, this.HEAD2];
    const subseqLen = subsequence.length;
    for (let i = 0; i <= lst.length - subseqLen; i++) {
      if (lst.slice(i, i + subseqLen).every((val, index) => val === subsequence[index])) {
        return i;
      }
    }
    return -1;
  }

  private save(addr: number, cmd: number, data: number[]): void {
    this.ADDR = addr;
    this.CMD = cmd;
    this.DATA = data;
    this.LEN = data.length;
    this.SUM = this.HEAD1 + this.HEAD2 + this.ADDR + this.CMD + this.LEN;
    for (const i of this.DATA) {
      this.SUM += i;
    }
    this.SUM &= 0xff;
  }
}

export class InfoPacket {
  CHIP_VERSION: string = 'V0.0';
  IS_CONNECTED: boolean = false;
  NUM_LOCK: boolean = false;
  CAPS_LOCK: boolean = false;
  SCROLL_LOCK: boolean = false;

  constructor(data: number[]) {
    if (data[0] < 0x30) {
      throw new Error('version error');
    }

    const versionE = data[0] - 0x30;
    const version = 1.0 + versionE / 10;
    this.CHIP_VERSION = `V${version.toFixed(1)}`;

    this.IS_CONNECTED = data[1] !== 0;

    this.NUM_LOCK = getBit(data[2], 0) === 1;
    this.CAPS_LOCK = getBit(data[2], 1) === 1;
    this.SCROLL_LOCK = getBit(data[2], 2) === 1;
  }
}

function getBit(number: number, bitPosition: number): number {
  return (number >> bitPosition) & 1;
}


================================================
FILE: browser/src/libs/device/serial-port.ts
================================================
import { isDisconnectError, raceWithTimeout } from './utils';

type WebSerialPort = {
  open: (options: { baudRate: number }) => Promise<void>;
  close: () => Promise<void>;
  readable: ReadableStream<Uint8Array> | null;
  writable: WritableStream<Uint8Array> | null;
};

type Options = {
  port: WebSerialPort;
  baudRate?: number;
  onDisconnect?: () => void;
};

export class SerialPort {
  readonly SERIAL_BAUD_RATE = 57600;
  readonly READ_TIMEOUT = 500;
  readonly CLEANUP_TIMEOUT = 1000;

  private instance: WebSerialPort | null = null;
  private reader: ReadableStreamDefaultReader<Uint8Array> | null = null;
  private writer: WritableStreamDefaultWriter<Uint8Array> | null = null;
  private onDisconnect?: () => void;

  private disconnectHandler = (event: Event) => {
    if (event.target === this.instance) {
      this.handleDisconnect();
    }
  };

  async init(options: Options): Promise<void> {
    if (this.instance) {
      await this.close();
    }

    try {
      this.instance = options.port;
      const baudRate = options.baudRate || this.SERIAL_BAUD_RATE;
      await this.instance.open({ baudRate });
    } catch (err) {
      this.instance = null;
      console.error('Error opening serial port:', err);
      throw err;
    }

    if (!this.instance.readable || !this.instance.writable) {
      this.instance = null;
      throw new Error('Serial port streams not available');
    }

    this.reader = this.instance.readable.getReader();
    this.writer = this.instance.writable.getWriter();

    if (options.onDisconnect) {
      this.onDisconnect = options.onDisconnect;
    }

    navigator.serial.addEventListener('disconnect', this.disconnectHandler);
  }

  private handleDisconnect(): void {
    if (!this.instance) return;

    this.releaseReader();
    this.releaseWriter();

    this.instance = null;

    if (this.onDisconnect) {
      this.onDisconnect();
      this.onDisconnect = undefined;
    }

    navigator.serial.removeEventListener('disconnect', this.disconnectHandler);
  }

  private releaseReader(): void {
    if (!this.reader) return;
    try {
      this.reader.releaseLock();
    } catch {
      // Lock already released
    }
    this.reader = null;
  }

  private releaseWriter(): void {
    if (!this.writer) return;
    try {
      this.writer.releaseLock();
    } catch {
      // Lock already released
    }
    this.writer = null;
  }

  async write(data: number[]): Promise<void> {
    if (!this.writer) {
      throw new Error('Serial port not initialized');
    }

    try {
      await this.writer.write(new Uint8Array(data));
    } catch (err) {
      if (isDisconnectError(err)) {
        this.handleDisconnect();
        throw new Error('Device disconnected');
      }
      throw err;
    }
  }

  async read(minSize: number, delayAfterRead: number = 0): Promise<number[]> {
    if (!this.reader) {
      throw new Error('Serial port not initialized');
    }

    const result: number[] = [];
    const startTime = Date.no
Download .txt
gitextract_n58uj4mo/

├── .github/
│   └── workflows/
│       ├── build.yml
│       ├── issue-tracker.yml
│       └── release.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── browser/
│   ├── .editorconfig
│   ├── .gitignore
│   ├── .prettierignore
│   ├── .prettierrc.yaml
│   ├── README.md
│   ├── eslint.config.js
│   ├── index.html
│   ├── package.json
│   ├── pnpm-workspace.yaml
│   ├── postcss.config.js
│   ├── src/
│   │   ├── App.tsx
│   │   ├── assets/
│   │   │   ├── index.css
│   │   │   └── keyboard.css
│   │   ├── components/
│   │   │   ├── device-modal/
│   │   │   │   ├── index.tsx
│   │   │   │   ├── serial-port.tsx
│   │   │   │   └── video.tsx
│   │   │   ├── keyboard/
│   │   │   │   └── index.tsx
│   │   │   ├── menu/
│   │   │   │   ├── audio/
│   │   │   │   │   └── index.tsx
│   │   │   │   ├── fullscreen/
│   │   │   │   │   └── index.tsx
│   │   │   │   ├── index.tsx
│   │   │   │   ├── keyboard/
│   │   │   │   │   ├── index.tsx
│   │   │   │   │   ├── paste.tsx
│   │   │   │   │   ├── shortcuts/
│   │   │   │   │   │   ├── index.tsx
│   │   │   │   │   │   ├── recorder.tsx
│   │   │   │   │   │   ├── shortcut.tsx
│   │   │   │   │   │   └── types.ts
│   │   │   │   │   └── virtual-keyboard.tsx
│   │   │   │   ├── mouse/
│   │   │   │   │   ├── direction.tsx
│   │   │   │   │   ├── index.tsx
│   │   │   │   │   ├── jiggler.tsx
│   │   │   │   │   ├── mode.tsx
│   │   │   │   │   ├── speed.tsx
│   │   │   │   │   └── style.tsx
│   │   │   │   ├── recorder/
│   │   │   │   │   └── index.tsx
│   │   │   │   ├── serial-port/
│   │   │   │   │   └── index.tsx
│   │   │   │   ├── settings/
│   │   │   │   │   ├── index.tsx
│   │   │   │   │   └── language.tsx
│   │   │   │   └── video/
│   │   │   │       ├── device.tsx
│   │   │   │       ├── index.tsx
│   │   │   │       ├── resolution.tsx
│   │   │   │       ├── rotation.tsx
│   │   │   │       └── scale.tsx
│   │   │   ├── mouse/
│   │   │   │   ├── absolute.tsx
│   │   │   │   ├── index.tsx
│   │   │   │   ├── relative.tsx
│   │   │   │   ├── touchpad.ts
│   │   │   │   └── types.ts
│   │   │   ├── ui/
│   │   │   │   ├── kbd.tsx
│   │   │   │   └── scroll-area.tsx
│   │   │   └── virtual-keyboard/
│   │   │       ├── index.tsx
│   │   │       └── keys.ts
│   │   ├── i18n/
│   │   │   ├── index.ts
│   │   │   ├── languages.ts
│   │   │   └── locales/
│   │   │       ├── be.ts
│   │   │       ├── de.ts
│   │   │       ├── en.ts
│   │   │       ├── ko.ts
│   │   │       ├── nl.ts
│   │   │       ├── pl.ts
│   │   │       ├── pt_br.ts
│   │   │       ├── ru.ts
│   │   │       ├── zh.ts
│   │   │       └── zh_tw.ts
│   │   ├── jotai/
│   │   │   ├── device.ts
│   │   │   ├── keyboard.ts
│   │   │   └── mouse.ts
│   │   ├── libs/
│   │   │   ├── browser/
│   │   │   │   └── index.ts
│   │   │   ├── device/
│   │   │   │   ├── index.ts
│   │   │   │   ├── proto.ts
│   │   │   │   ├── serial-port.ts
│   │   │   │   └── utils.ts
│   │   │   ├── keyboard/
│   │   │   │   ├── charCodes.ts
│   │   │   │   ├── keyboard.ts
│   │   │   │   └── keymap.ts
│   │   │   ├── media/
│   │   │   │   ├── camera.ts
│   │   │   │   └── permission.ts
│   │   │   ├── mouse/
│   │   │   │   └── index.ts
│   │   │   ├── mouse-jiggler/
│   │   │   │   └── index.ts
│   │   │   └── storage/
│   │   │       └── index.ts
│   │   ├── main.tsx
│   │   ├── types.ts
│   │   └── vite-env.d.ts
│   ├── tailwind.config.js
│   ├── tsconfig.app.json
│   ├── tsconfig.json
│   ├── tsconfig.node.json
│   ├── vite.config.d.ts
│   └── vite.config.ts
├── desktop/
│   ├── .editorconfig
│   ├── .gitignore
│   ├── .npmrc
│   ├── .prettierignore
│   ├── .prettierrc.yaml
│   ├── README.md
│   ├── build/
│   │   ├── entitlements.mac.plist
│   │   └── icon.icns
│   ├── dev-app-update.yml
│   ├── electron-builder.yml
│   ├── electron.vite.config.ts
│   ├── eslint.config.mjs
│   ├── notarize.js
│   ├── package.json
│   ├── src/
│   │   ├── common/
│   │   │   └── ipc-events.ts
│   │   ├── main/
│   │   │   ├── device/
│   │   │   │   ├── index.ts
│   │   │   │   ├── proto.ts
│   │   │   │   └── serial-port.ts
│   │   │   ├── events/
│   │   │   │   ├── app.ts
│   │   │   │   ├── index.ts
│   │   │   │   ├── serial-port.ts
│   │   │   │   └── updater.ts
│   │   │   └── index.ts
│   │   ├── preload/
│   │   │   ├── index.d.ts
│   │   │   └── index.ts
│   │   └── renderer/
│   │       ├── index.html
│   │       └── src/
│   │           ├── App.tsx
│   │           ├── assets/
│   │           │   └── styles/
│   │           │       ├── base.css
│   │           │       ├── keyboard.css
│   │           │       └── main.css
│   │           ├── components/
│   │           │   ├── device/
│   │           │   │   ├── connect.tsx
│   │           │   │   ├── disconnect.tsx
│   │           │   │   ├── index.tsx
│   │           │   │   ├── serial-port.tsx
│   │           │   │   └── video.tsx
│   │           │   ├── keyboard/
│   │           │   │   └── index.tsx
│   │           │   ├── menu/
│   │           │   │   ├── audio/
│   │           │   │   │   └── index.tsx
│   │           │   │   ├── index.tsx
│   │           │   │   ├── keyboard/
│   │           │   │   │   ├── index.tsx
│   │           │   │   │   ├── paste.tsx
│   │           │   │   │   ├── shortcuts/
│   │           │   │   │   │   ├── index.tsx
│   │           │   │   │   │   ├── recorder.tsx
│   │           │   │   │   │   ├── shortcut.tsx
│   │           │   │   │   │   └── types.ts
│   │           │   │   │   └── virtual-keyboard.tsx
│   │           │   │   ├── language/
│   │           │   │   │   └── index.tsx
│   │           │   │   ├── mouse/
│   │           │   │   │   ├── direction.tsx
│   │           │   │   │   ├── index.tsx
│   │           │   │   │   ├── jiggler.tsx
│   │           │   │   │   ├── mode.tsx
│   │           │   │   │   ├── speed.tsx
│   │           │   │   │   └── style.tsx
│   │           │   │   ├── recorder/
│   │           │   │   │   └── index.tsx
│   │           │   │   ├── serial-port/
│   │           │   │   │   └── index.tsx
│   │           │   │   ├── settings/
│   │           │   │   │   ├── about.tsx
│   │           │   │   │   ├── appearance.tsx
│   │           │   │   │   ├── index.tsx
│   │           │   │   │   ├── reset.tsx
│   │           │   │   │   └── update.tsx
│   │           │   │   └── video/
│   │           │   │       ├── device.tsx
│   │           │   │       ├── index.tsx
│   │           │   │       ├── resolution.tsx
│   │           │   │       └── scale.tsx
│   │           │   ├── mouse/
│   │           │   │   ├── absolute.tsx
│   │           │   │   ├── index.tsx
│   │           │   │   ├── relative.tsx
│   │           │   │   ├── touchpad.ts
│   │           │   │   └── types.ts
│   │           │   ├── ui/
│   │           │   │   ├── kbd.tsx
│   │           │   │   └── scroll-area.tsx
│   │           │   └── virtual-keyboard/
│   │           │       ├── index.tsx
│   │           │       └── virtual-keys.ts
│   │           ├── env.d.ts
│   │           ├── i18n/
│   │           │   ├── index.ts
│   │           │   ├── languages.ts
│   │           │   └── locales/
│   │           │       ├── be.ts
│   │           │       ├── de.ts
│   │           │       ├── en.ts
│   │           │       ├── ja.ts
│   │           │       ├── ko.ts
│   │           │       ├── nl.ts
│   │           │       ├── pl.ts
│   │           │       ├── pt_br.ts
│   │           │       ├── ru.ts
│   │           │       ├── zh.ts
│   │           │       └── zh_tw.ts
│   │           ├── jotai/
│   │           │   ├── device.ts
│   │           │   ├── keyboard.ts
│   │           │   └── mouse.ts
│   │           ├── libs/
│   │           │   ├── keyboard/
│   │           │   │   ├── charCodes.ts
│   │           │   │   ├── keyboard.ts
│   │           │   │   └── keymap.ts
│   │           │   ├── media/
│   │           │   │   ├── camera.ts
│   │           │   │   └── permission.ts
│   │           │   ├── mouse/
│   │           │   │   └── index.ts
│   │           │   ├── mouse-jiggler/
│   │           │   │   └── index.ts
│   │           │   └── storage/
│   │           │       ├── expiry.ts
│   │           │       └── index.ts
│   │           ├── main.tsx
│   │           └── types.ts
│   ├── tsconfig.json
│   ├── tsconfig.node.json
│   └── tsconfig.web.json
├── docker-compose.yml
└── nginx.conf
Download .txt
SYMBOL INDEX (476 symbols across 102 files)

FILE: browser/src/App.tsx
  function initResolution (line 82) | function initResolution() {
  function initRotation (line 91) | function initRotation() {
  function requestPermission (line 98) | async function requestPermission(resolution?: Resolution) {

FILE: browser/src/components/device-modal/serial-port.tsx
  type SerialPortProps (line 9) | type SerialPortProps = {

FILE: browser/src/components/device-modal/video.tsx
  type VideoProps (line 11) | type VideoProps = {
  function getDevices (line 28) | async function getDevices() {
  function selectVideo (line 60) | async function selectVideo(videoId: string) {

FILE: browser/src/components/keyboard/index.tsx
  type AltGrState (line 10) | interface AltGrState {
  constant ALTGR_THRESHOLD_MS (line 15) | const ALTGR_THRESHOLD_MS = 10;
  function handleKeyDown (line 44) | async function handleKeyDown(event: KeyboardEvent): Promise<void> {
  function handleKeyUp (line 77) | async function handleKeyUp(event: KeyboardEvent): Promise<void> {
  function handleCompositionStart (line 116) | function handleCompositionStart(): void {
  function handleCompositionEnd (line 121) | function handleCompositionEnd(): void {
  function handleBlur (line 126) | async function handleBlur(): Promise<void> {
  function handleVisibilityChange (line 131) | async function handleVisibilityChange(): Promise<void> {
  function releaseKeys (line 138) | async function releaseKeys(): Promise<void> {
  function normalizeKeyCode (line 167) | function normalizeKeyCode(event: KeyboardEvent, os?: string): string {
  function handleKeyEvent (line 195) | async function handleKeyEvent(event: { type: 'keydown' | 'keyup'; code: ...

FILE: browser/src/components/menu/audio/index.tsx
  function requestPermission (line 26) | async function requestPermission() {
  function closeModal (line 44) | function closeModal() {

FILE: browser/src/components/menu/fullscreen/index.tsx
  function onFullscreenChange (line 8) | function onFullscreenChange() {
  function handleFullscreen (line 21) | function handleFullscreen() {

FILE: browser/src/components/menu/index.tsx
  function toggleMenu (line 57) | function toggleMenu() {

FILE: browser/src/components/menu/keyboard/paste.tsx
  function paste (line 13) | async function paste(): Promise<void> {
  function send (line 43) | async function send(modifier: number, code: number): Promise<void> {

FILE: browser/src/components/menu/keyboard/shortcuts/index.tsx
  function addShortcut (line 42) | function addShortcut(shortcut: ShortcutInterface): void {
  function delShortcut (line 48) | function delShortcut(index: number): void {
  function handleOpenChange (line 54) | function handleOpenChange(open: boolean): void {

FILE: browser/src/components/menu/keyboard/shortcuts/recorder.tsx
  constant MAX_KEYS (line 14) | const MAX_KEYS = 6;
  type RecorderProps (line 49) | interface RecorderProps {
  function saveShortcut (line 157) | function saveShortcut() {
  function clearShortcut (line 165) | function clearShortcut() {
  function closeModal (line 170) | function closeModal() {
  function toggleFullscreen (line 175) | function toggleFullscreen() {

FILE: browser/src/components/menu/keyboard/shortcuts/shortcut.tsx
  type ShortcutProps (line 9) | type ShortcutProps = {
  function handleClick (line 16) | async function handleClick(): Promise<void> {
  function sendShortcut (line 29) | async function sendShortcut(): Promise<void> {

FILE: browser/src/components/menu/keyboard/shortcuts/types.ts
  type KeyInfo (line 1) | interface KeyInfo {
  type Shortcut (line 6) | interface Shortcut {

FILE: browser/src/components/menu/keyboard/virtual-keyboard.tsx
  function toggleKeyboard (line 11) | function toggleKeyboard() {

FILE: browser/src/components/menu/mouse/direction.tsx
  function update (line 21) | function update(direction: string): void {

FILE: browser/src/components/menu/mouse/index.tsx
  function initMouse (line 35) | function initMouse() {

FILE: browser/src/components/menu/mouse/jiggler.tsx
  function update (line 21) | function update(mode: 'enable' | 'disable'): void {

FILE: browser/src/components/menu/mouse/mode.tsx
  function update (line 19) | function update(mode: string) {

FILE: browser/src/components/menu/mouse/speed.tsx
  constant MAX_INTERVAL (line 10) | const MAX_INTERVAL = 300;
  function update (line 24) | function update(speed: number): void {
  function interval2Speed (line 30) | function interval2Speed(interval: number) {
  function speed2Interval (line 37) | function speed2Interval(speed: number) {

FILE: browser/src/components/menu/mouse/style.tsx
  function updateStyle (line 15) | function updateStyle(style: string) {

FILE: browser/src/components/menu/serial-port/index.tsx
  function selectSerial (line 9) | async function selectSerial() {

FILE: browser/src/components/menu/settings/index.tsx
  function openPage (line 10) | function openPage(url: string) {

FILE: browser/src/components/menu/settings/language.tsx
  function changeLanguage (line 12) | function changeLanguage(lng: string) {

FILE: browser/src/components/menu/video/device.tsx
  function getDevices (line 26) | async function getDevices() {
  function selectDevice (line 57) | async function selectDevice(device: MediaDevice) {

FILE: browser/src/components/menu/video/resolution.tsx
  function showModal (line 44) | function showModal() {
  function submit (line 50) | function submit() {
  function updateResolution (line 67) | async function updateResolution(w: number, h: number) {
  function removeCustomResolution (line 84) | function removeCustomResolution(e: any) {

FILE: browser/src/components/menu/video/rotation.tsx
  function updateRotation (line 24) | function updateRotation(rotation: VideoRotation): void {

FILE: browser/src/components/menu/video/scale.tsx
  function updateScale (line 32) | async function updateScale(scale: number): Promise<void> {

FILE: browser/src/components/mouse/absolute.tsx
  function handleMouseDown (line 54) | function handleMouseDown(e: MouseEvent): void {
  function handleMouseUp (line 60) | function handleMouseUp(e: MouseEvent): void {
  function handleMouseMove (line 66) | function handleMouseMove(e: MouseEvent): void {
  function handleWheel (line 73) | function handleWheel(e: WheelEvent): void {
  function getCoordinate (line 91) | function getCoordinate(event: { clientX: number; clientY: number }): { x...
  function handleMouseEvent (line 141) | async function handleMouseEvent(event: MouseAbsoluteEvent): Promise<void> {
  function disableEvent (line 172) | function disableEvent(event: Event): void {

FILE: browser/src/components/mouse/relative.tsx
  function handleClick (line 38) | function handleClick(event: MouseEvent): void {
  function handleMouseDown (line 47) | function handleMouseDown(e: MouseEvent): void {
  function handleMouseUp (line 53) | function handleMouseUp(e: MouseEvent): void {
  function handleMouseMove (line 59) | function handleMouseMove(e: MouseEvent): void {
  function handleMouseWheel (line 73) | function handleMouseWheel(e: WheelEvent): void {
  function handlePointerLockChange (line 91) | function handlePointerLockChange(): void {
  function handleMouseEvent (line 112) | async function handleMouseEvent(event: MouseRelativeEvent): Promise<void> {
  function showMessage (line 141) | function showMessage(): void {
  function disableEvent (line 153) | function disableEvent(event: Event): void {

FILE: browser/src/components/mouse/touchpad.ts
  constant TAP_THRESHOLD (line 5) | const TAP_THRESHOLD = 8;
  constant DRAG_THRESHOLD (line 6) | const DRAG_THRESHOLD = 10;
  constant VELOCITY_THRESHOLD (line 7) | const VELOCITY_THRESHOLD = 0.3;
  constant LONG_PRESS_DELAY (line 8) | const LONG_PRESS_DELAY = 800;
  type TouchHandlerOptions (line 10) | interface TouchHandlerOptions {
  type TouchState (line 18) | interface TouchState {
  function createInitialTouchState (line 30) | function createInitialTouchState(): TouchState {
  function createTouchHandlers (line 44) | function createTouchHandlers(state: TouchState, options: TouchHandlerOpt...

FILE: browser/src/components/mouse/types.ts
  type MouseButton (line 1) | enum MouseButton {
  type MouseMoveAbsoluteEvent (line 9) | interface MouseMoveAbsoluteEvent {
  type MouseMoveRelativeEvent (line 15) | interface MouseMoveRelativeEvent {
  type MouseButtonEvent (line 21) | interface MouseButtonEvent {
  type MouseWheelEvent (line 26) | interface MouseWheelEvent {
  type MouseAbsoluteEvent (line 31) | type MouseAbsoluteEvent = MouseMoveAbsoluteEvent | MouseButtonEvent | Mo...
  type MouseRelativeEvent (line 33) | type MouseRelativeEvent = MouseMoveRelativeEvent | MouseButtonEvent | Mo...

FILE: browser/src/components/ui/kbd.tsx
  function Kbd (line 3) | function Kbd({ className, ...props }: React.ComponentProps<'kbd'>) {
  function KbdGroup (line 18) | function KbdGroup({ className, ...props }: React.ComponentProps<'div'>) {

FILE: browser/src/components/ui/scroll-area.tsx
  function ScrollArea (line 5) | function ScrollArea({
  function ScrollBar (line 28) | function ScrollBar({

FILE: browser/src/components/virtual-keyboard/index.tsx
  type KeyboardProps (line 24) | type KeyboardProps = {
  function onKeyPress (line 36) | async function onKeyPress(key: string): Promise<void> {
  function onKeyReleased (line 62) | async function onKeyReleased(key: string): Promise<void> {
  function handleKeyEvent (line 76) | async function handleKeyEvent(event: { type: 'keydown' | 'keyup'; key: s...
  function getButtonTheme (line 85) | function getButtonTheme(): KeyboardButtonTheme[] {

FILE: browser/src/i18n/index.ts
  function getResources (line 7) | function getResources(): Resource {
  function getCurrentLanguage (line 22) | function getCurrentLanguage(): string {

FILE: browser/src/jotai/device.ts
  type VideoState (line 5) | type VideoState = 'disconnected' | 'connecting' | 'connected';
  type SerialState (line 6) | type SerialState = 'notSupported' | 'disconnected' | 'connecting' | 'con...

FILE: browser/src/libs/browser/index.ts
  type System (line 1) | type System = 'Windows' | 'macOS' | 'Linux' | 'Unknown';
  type BrowserInfo (line 3) | interface BrowserInfo {
  function getOperatingSystem (line 8) | function getOperatingSystem(): System {
  function isChromeBrowser (line 33) | function isChromeBrowser(): boolean {
  function getBrowserInfo (line 56) | function getBrowserInfo(): BrowserInfo {

FILE: browser/src/libs/device/index.ts
  class Device (line 4) | class Device {
    method constructor (line 8) | constructor() {
    method getInfo (line 13) | async getInfo() {
    method sendKeyboardData (line 22) | async sendKeyboardData(report: number[]): Promise<void> {
    method sendMouseData (line 27) | async sendMouseData(report: number[]): Promise<void> {

FILE: browser/src/libs/device/proto.ts
  type CmdEvent (line 1) | enum CmdEvent {
  class CmdPacket (line 17) | class CmdPacket {
    method constructor (line 27) | constructor(addr: number = 0x00, cmd: number = 0x00, data: number[] = ...
    method encode (line 35) | encode(): number[] {
    method decode (line 39) | public decode(data: number[]): number {
    method findHead (line 86) | private findHead(lst: number[]): number {
    method save (line 97) | private save(addr: number, cmd: number, data: number[]): void {
  class InfoPacket (line 110) | class InfoPacket {
    method constructor (line 117) | constructor(data: number[]) {
  function getBit (line 134) | function getBit(number: number, bitPosition: number): number {

FILE: browser/src/libs/device/serial-port.ts
  type WebSerialPort (line 3) | type WebSerialPort = {
  type Options (line 10) | type Options = {
  class SerialPort (line 16) | class SerialPort {
    method init (line 32) | async init(options: Options): Promise<void> {
    method handleDisconnect (line 62) | private handleDisconnect(): void {
    method releaseReader (line 78) | private releaseReader(): void {
    method releaseWriter (line 88) | private releaseWriter(): void {
    method write (line 98) | async write(data: number[]): Promise<void> {
    method read (line 114) | async read(minSize: number, delayAfterRead: number = 0): Promise<numbe...
    method close (line 147) | async close(): Promise<void> {

FILE: browser/src/libs/device/utils.ts
  function raceWithTimeout (line 1) | function raceWithTimeout<T>(promise: Promise<T>, ms: number): Promise<T ...
  function isDisconnectError (line 8) | function isDisconnectError(err: unknown): boolean {

FILE: browser/src/libs/keyboard/keyboard.ts
  constant MAX_KEYS (line 3) | const MAX_KEYS = 6;
  class KeyboardReport (line 5) | class KeyboardReport {
    method keyDown (line 9) | keyDown(code: string): number[] {
    method keyUp (line 21) | keyUp(code: string): number[] {
    method reset (line 30) | reset(): number[] {
    method buildReport (line 42) | private buildReport(): number[] {
    method getModifier (line 54) | getModifier(): number {
    method getPressedKeyCount (line 58) | getPressedKeyCount(): number {

FILE: browser/src/libs/keyboard/keymap.ts
  function isModifier (line 269) | function isModifier(code: string): boolean {
  function getModifierBit (line 274) | function getModifierBit(code: string): number {
  function getKeycode (line 279) | function getKeycode(code: string): number | undefined {

FILE: browser/src/libs/media/camera.ts
  class Camera (line 3) | class Camera {
    method open (line 10) | public async open(id: string, width: number, height: number, audioId?:...
    method updateResolution (line 51) | public async updateResolution(width: number, height: number) {
    method close (line 55) | public close(): void {
    method getStream (line 62) | public getStream(): MediaStream | null {
    method isOpen (line 66) | public isOpen(): boolean {

FILE: browser/src/libs/media/permission.ts
  function checkPermission (line 3) | async function checkPermission(device: 'camera' | 'microphone'): Promise...
  function requestCameraPermission (line 16) | async function requestCameraPermission(resolution?: Resolution) {
  function requestMicrophonePermission (line 32) | async function requestMicrophonePermission() {

FILE: browser/src/libs/mouse-jiggler/index.ts
  constant MOUSE_JIGGLER_INTERVAL (line 4) | const MOUSE_JIGGLER_INTERVAL = 15_000;
  class MouseJiggler (line 6) | class MouseJiggler {
    method constructor (line 12) | constructor() {
    method setMode (line 20) | setMode(mode: 'enable' | 'disable'): void {
    method moveEventCallback (line 33) | moveEventCallback(): void {
    method timeoutCallback (line 39) | timeoutCallback(): void {
    method sendJiggle (line 46) | async sendJiggle(): Promise<void> {

FILE: browser/src/libs/mouse/index.ts
  constant MAX_ABS_COORD (line 2) | const MAX_ABS_COORD = 4096;
  function getMouseButtonBit (line 14) | function getMouseButtonBit(button: number): number {
  class MouseReportRelative (line 39) | class MouseReportRelative {
    method buttonDown (line 42) | buttonDown(button: number): void {
    method buttonUp (line 46) | buttonUp(button: number): void {
    method buildReport (line 56) | buildReport(deltaX: number, deltaY: number, wheel: number = 0): number...
    method buildButtonReport (line 66) | buildButtonReport(): number[] {
    method reset (line 70) | reset(): number[] {
    method clamp (line 75) | private clamp(value: number, min: number, max: number): number {
  class MouseAbsoluteRelative (line 88) | class MouseAbsoluteRelative {
    method buttonDown (line 91) | buttonDown(button: number): void {
    method buttonUp (line 95) | buttonUp(button: number): void {
    method buildReport (line 105) | buildReport(x: number, y: number, wheel: number = 0): number[] {
    method buildButtonReport (line 122) | buildButtonReport(lastX: number, lastY: number): number[] {
    method reset (line 126) | reset(): number[] {
    method clamp (line 131) | private clamp(value: number, min: number, max: number): number {

FILE: browser/src/libs/storage/index.ts
  constant LANGUAGE_KEY (line 3) | const LANGUAGE_KEY = 'nanokvm-usb-language';
  constant VIDEO_DEVICE_ID_KEY (line 4) | const VIDEO_DEVICE_ID_KEY = 'nanokvm-usb-video-device-id';
  constant VIDEO_RESOLUTION_KEY (line 5) | const VIDEO_RESOLUTION_KEY = 'nanokvm-usb-video-resolution';
  constant CUSTOM_RESOLUTION_KEY (line 6) | const CUSTOM_RESOLUTION_KEY = 'nanokvm-usb-custom-resolution';
  constant VIDEO_SCALE_KEY (line 7) | const VIDEO_SCALE_KEY = 'nanokvm-usb-video-scale';
  constant VIDEO_ROTATION_KEY (line 8) | const VIDEO_ROTATION_KEY = 'nanokvm-usb-video-rotation';
  constant IS_MENU_OPEN_KEY (line 9) | const IS_MENU_OPEN_KEY = 'nanokvm-is-menu-open';
  constant MOUSE_STYLE_KEY (line 10) | const MOUSE_STYLE_KEY = 'nanokvm-usb-mouse-style';
  constant MOUSE_MODE_KEY (line 11) | const MOUSE_MODE_KEY = 'nanokvm-usb-mouse-mode';
  constant MOUSE_SCROLL_DIRECTION_KEY (line 12) | const MOUSE_SCROLL_DIRECTION_KEY = 'nanokvm-usb-mouse-scroll-direction';
  constant MOUSE_SCROLL_INTERVAL_KEY (line 13) | const MOUSE_SCROLL_INTERVAL_KEY = 'nanokvm-usb-mouse-scroll-interval';
  constant MOUSE_JIGGLER_MODE_KEY (line 14) | const MOUSE_JIGGLER_MODE_KEY = 'nanokvm-usb-mouse-jiggler-mode';
  constant KEYBOARD_SHORTCUT_KEY (line 15) | const KEYBOARD_SHORTCUT_KEY = 'nanokvm-usb-keyboard-shortcut';
  function getLanguage (line 17) | function getLanguage() {
  function setLanguage (line 21) | function setLanguage(language: string) {
  function setVideoDevice (line 25) | function setVideoDevice(id: string) {
  function getVideoDevice (line 29) | function getVideoDevice() {
  function setVideoResolution (line 33) | function setVideoResolution(width: number, height: number) {
  function getVideoResolution (line 37) | function getVideoResolution() {
  function getCustomResolutions (line 43) | function getCustomResolutions() {
  function setCustomResolution (line 49) | function setCustomResolution(width: number, height: number) {
  function removeCustomResolutions (line 59) | function removeCustomResolutions() {
  function getVideoScale (line 63) | function getVideoScale(): number | null {
  function setVideoScale (line 71) | function setVideoScale(scale: number): void {
  function getVideoRotation (line 75) | function getVideoRotation(): Rotation | null {
  function setVideoRotation (line 86) | function setVideoRotation(rotation: Rotation): void {
  function getIsMenuOpen (line 90) | function getIsMenuOpen(): boolean {
  function setIsMenuOpen (line 98) | function setIsMenuOpen(isOpen: boolean) {
  function getMouseStyle (line 102) | function getMouseStyle() {
  function setMouseStyle (line 106) | function setMouseStyle(mouse: string) {
  function getMouseMode (line 110) | function getMouseMode() {
  function setMouseMode (line 114) | function setMouseMode(mouse: string) {
  function getMouseScrollDirection (line 118) | function getMouseScrollDirection(): number | null {
  function setMouseScrollDirection (line 126) | function setMouseScrollDirection(direction: number): void {
  function getMouseScrollInterval (line 130) | function getMouseScrollInterval(): number | null {
  function setMouseScrollInterval (line 138) | function setMouseScrollInterval(interval: number): void {
  function getShortcuts (line 142) | function getShortcuts(): string | null {
  function setShortcuts (line 146) | function setShortcuts(shortcuts: string): void {
  function getMouseJigglerMode (line 150) | function getMouseJigglerMode(): 'enable' | 'disable' {
  function setMouseJigglerMode (line 155) | function setMouseJigglerMode(jiggler: 'enable' | 'disable'): void {

FILE: browser/src/types.ts
  type Resolution (line 1) | type Resolution = {
  type Rotation (line 6) | type Rotation = 0 | 90 | 180 | 270;
  type MediaDevice (line 8) | type MediaDevice = {

FILE: browser/src/vite-env.d.ts
  type Navigator (line 2) | interface Navigator {

FILE: desktop/src/common/ipc-events.ts
  type IpcEvents (line 1) | enum IpcEvents {

FILE: desktop/src/main/device/index.ts
  class Device (line 4) | class Device {
    method constructor (line 8) | constructor() {
    method getInfo (line 13) | async getInfo(): Promise<InfoPacket> {
    method sendKeyboardData (line 22) | async sendKeyboardData(report: number[]): Promise<void> {
    method sendMouseData (line 27) | async sendMouseData(report: number[]): Promise<void> {

FILE: desktop/src/main/device/proto.ts
  type CmdEvent (line 1) | enum CmdEvent {
  class CmdPacket (line 17) | class CmdPacket {
    method constructor (line 27) | constructor(addr: number = 0x00, cmd: number = 0x00, data: number[] = ...
    method encode (line 35) | encode(): number[] {
    method decode (line 39) | public decode(data: number[]): number {
    method findHead (line 86) | private findHead(lst: number[]): number {
    method save (line 97) | private save(addr: number, cmd: number, data: number[]): void {
  class InfoPacket (line 110) | class InfoPacket {
    method constructor (line 117) | constructor(data: number[]) {
  function getBit (line 134) | function getBit(number: number, bitPosition: number): number {

FILE: desktop/src/main/device/serial-port.ts
  type Options (line 3) | type Options = {
  class SerialPort (line 9) | class SerialPort {
    method constructor (line 16) | constructor() {
    method init (line 20) | async init(options: Options): Promise<void> {
    method handleDisconnect (line 60) | private handleDisconnect(): void {
    method isDisconnectError (line 72) | private isDisconnectError(err: Error): boolean {
    method write (line 82) | async write(data: number[]): Promise<void> {
    method read (line 91) | async read(minSize: number, sleep: number = 0): Promise<number[]> {
    method close (line 120) | async close(): Promise<void> {

FILE: desktop/src/main/events/app.ts
  function registerApp (line 6) | function registerApp(): void {
  function getAppVersion (line 15) | function getAppVersion(): string {
  function getPlatform (line 19) | function getPlatform(): string {
  function openExternalUrl (line 23) | function openExternalUrl(_: IpcMainEvent, url: string, options?: OpenExt...
  function checkMediaPermission (line 27) | function checkMediaPermission(_: IpcMainInvokeEvent, media: 'camera' | '...
  function requestMediaPermission (line 32) | async function requestMediaPermission(
  function setFullScreen (line 49) | function setFullScreen(e: IpcMainEvent, flag: boolean): void {

FILE: desktop/src/main/events/serial-port.ts
  function registerSerialPort (line 7) | function registerSerialPort(): void {
  function getSerialPorts (line 15) | async function getSerialPorts(): Promise<string[]> {
  function openSerialPort (line 34) | async function openSerialPort(
  function closeSerialPort (line 56) | async function closeSerialPort(): Promise<boolean> {
  function sendKeyboard (line 66) | async function sendKeyboard(_: IpcMainInvokeEvent, report: number[]): Pr...
  function sendMouse (line 74) | async function sendMouse(_: IpcMainInvokeEvent, report: number[]): Promi...

FILE: desktop/src/main/events/updater.ts
  function registerUpdater (line 9) | function registerUpdater(win: BrowserWindow): void {

FILE: desktop/src/main/index.ts
  function createWindow (line 13) | function createWindow(): void {

FILE: desktop/src/preload/index.d.ts
  type Window (line 4) | interface Window {

FILE: desktop/src/renderer/src/App.tsx
  type State (line 27) | type State = 'loading' | 'success' | 'failed'
  function requestMediaPermissions (line 57) | async function requestMediaPermissions(resolution?: Resolution): Promise...

FILE: desktop/src/renderer/src/components/device/serial-port.tsx
  type Option (line 10) | type Option = {
  type SerialPortProps (line 15) | type SerialPortProps = {
  function getSerialPorts (line 52) | async function getSerialPorts(autoOpen: boolean): Promise<void> {
  function selectSerialPort (line 65) | async function selectSerialPort(port: string, customBaudRate?: number): ...

FILE: desktop/src/renderer/src/components/device/video.tsx
  type VideoProps (line 11) | type VideoProps = {
  function getDevices (line 28) | async function getDevices(autoOpen: boolean): Promise<void> {
  function selectDevice (line 68) | async function selectDevice(videoId: string): Promise<void> {
  function openCamera (line 86) | async function openCamera(videoId: string, audioId?: string): Promise<vo...

FILE: desktop/src/renderer/src/components/keyboard/index.tsx
  type AltGrState (line 9) | interface AltGrState {
  constant ALTGR_THRESHOLD_MS (line 14) | const ALTGR_THRESHOLD_MS = 10
  function handleKeyDown (line 40) | async function handleKeyDown(event: KeyboardEvent): Promise<void> {
  function handleKeyUp (line 77) | async function handleKeyUp(event: KeyboardEvent): Promise<void> {
  function handleCompositionStart (line 120) | function handleCompositionStart(): void {
  function handleCompositionEnd (line 125) | function handleCompositionEnd(): void {
  function handleBlur (line 130) | async function handleBlur(): Promise<void> {
  function handleVisibilityChange (line 135) | async function handleVisibilityChange(): Promise<void> {
  function releaseKeys (line 142) | async function releaseKeys(): Promise<void> {
  function initAltGr (line 171) | async function initAltGr(): Promise<void> {
  function handleKeyEvent (line 180) | async function handleKeyEvent(event: { type: 'keydown' | 'keyup'; code: ...
  function sendReport (line 186) | async function sendReport(report: number[]): Promise<void> {

FILE: desktop/src/renderer/src/components/menu/audio/index.tsx
  function requestPermission (line 26) | async function requestPermission(): Promise<void> {
  function closeModal (line 44) | function closeModal(): void {

FILE: desktop/src/renderer/src/components/menu/index.tsx
  function toggleMenu (line 54) | function toggleMenu(): void {

FILE: desktop/src/renderer/src/components/menu/keyboard/paste.tsx
  function paste (line 13) | async function paste(): Promise<void> {
  function send (line 43) | async function send(modifier: number, code: number): Promise<void> {

FILE: desktop/src/renderer/src/components/menu/keyboard/shortcuts/index.tsx
  function addShortcut (line 42) | function addShortcut(shortcut: ShortcutInterface): void {
  function delShortcut (line 48) | function delShortcut(index: number): void {
  function handleOpenChange (line 54) | function handleOpenChange(open: boolean): void {

FILE: desktop/src/renderer/src/components/menu/keyboard/shortcuts/recorder.tsx
  constant MAX_KEYS (line 14) | const MAX_KEYS = 6
  type RecorderProps (line 49) | interface RecorderProps {
  function saveShortcut (line 157) | function saveShortcut(): void {
  function clearShortcut (line 165) | function clearShortcut(): void {
  function closeModal (line 170) | function closeModal(): void {

FILE: desktop/src/renderer/src/components/menu/keyboard/shortcuts/shortcut.tsx
  type ShortcutProps (line 9) | type ShortcutProps = {
  function handleClick (line 16) | async function handleClick(): Promise<void> {
  function sendShortcut (line 29) | async function sendShortcut(): Promise<void> {
  function send (line 41) | async function send(report: number[]): Promise<void> {

FILE: desktop/src/renderer/src/components/menu/keyboard/shortcuts/types.ts
  type KeyInfo (line 1) | interface KeyInfo {
  type Shortcut (line 6) | interface Shortcut {

FILE: desktop/src/renderer/src/components/menu/language/index.tsx
  function changeLanguage (line 13) | function changeLanguage(lng: string): void {

FILE: desktop/src/renderer/src/components/menu/mouse/direction.tsx
  function update (line 21) | function update(direction: string): void {

FILE: desktop/src/renderer/src/components/menu/mouse/jiggler.tsx
  function update (line 21) | function update(mode: 'enable' | 'disable'): void {

FILE: desktop/src/renderer/src/components/menu/mouse/mode.tsx
  function update (line 21) | function update(mode: string): void {

FILE: desktop/src/renderer/src/components/menu/mouse/speed.tsx
  constant MAX_INTERVAL (line 10) | const MAX_INTERVAL = 300
  function update (line 24) | function update(speed: number): void {
  function interval2Speed (line 30) | function interval2Speed(interval: number): number {
  function speed2Interval (line 37) | function speed2Interval(speed: number): number {

FILE: desktop/src/renderer/src/components/menu/mouse/style.tsx
  function updateStyle (line 26) | function updateStyle(style: string): void {

FILE: desktop/src/renderer/src/components/menu/serial-port/index.tsx
  function getSerialPorts (line 49) | async function getSerialPorts(): Promise<void> {
  function openSerialPort (line 54) | async function openSerialPort(port: string, customBaudRate?: number): Pr...
  function closeSerialPort (line 66) | async function closeSerialPort(): Promise<void> {
  function handleBaudRateChange (line 72) | async function handleBaudRateChange(newBaudRate: number): Promise<void> {

FILE: desktop/src/renderer/src/components/menu/settings/about.tsx
  function open (line 44) | function open(url: string): void {

FILE: desktop/src/renderer/src/components/menu/settings/appearance.tsx
  function changeLanguage (line 25) | function changeLanguage(value: string): void {
  function toggleMenu (line 32) | function toggleMenu(): void {

FILE: desktop/src/renderer/src/components/menu/settings/index.tsx
  function changeTab (line 46) | function changeTab(tab: string): void {
  function closeModal (line 55) | function closeModal(): void {

FILE: desktop/src/renderer/src/components/menu/settings/reset.tsx
  function handleReset (line 11) | function handleReset(): void {
  function confirmReset (line 15) | function confirmReset(): void {
  function cancelReset (line 21) | function cancelReset(): void {

FILE: desktop/src/renderer/src/components/menu/settings/update.tsx
  type Status (line 8) | type Status = 'loading' | 'latest' | 'outdated' | 'downloading' | 'insta...
  function getVersion (line 65) | function getVersion(): void {
  function update (line 73) | function update(): void {

FILE: desktop/src/renderer/src/components/menu/video/device.tsx
  function getDevices (line 25) | async function getDevices(): Promise<void> {
  function selectDevice (line 58) | async function selectDevice(device: MediaDevice): Promise<void> {

FILE: desktop/src/renderer/src/components/menu/video/resolution.tsx
  function showModal (line 45) | function showModal(): void {
  function submit (line 51) | function submit(): void {
  function updateResolution (line 68) | async function updateResolution(w: number, h: number): Promise<void> {
  function removeCustomResolution (line 85) | function removeCustomResolution(e: React.MouseEvent<HTMLSpanElement, Mou...

FILE: desktop/src/renderer/src/components/menu/video/scale.tsx
  function updateScale (line 31) | async function updateScale(scale: number): Promise<void> {

FILE: desktop/src/renderer/src/components/mouse/absolute.tsx
  function getCoordinate (line 28) | function getCoordinate(event: { clientX: number; clientY: number }): { x...
  function disableEvent (line 62) | function disableEvent(event: Event): void {
  function handleMouseEvent (line 68) | function handleMouseEvent(event: MouseAbsoluteEvent): void {
  function handleMouseDown (line 99) | function handleMouseDown(e: MouseEvent): void {
  function handleMouseUp (line 105) | function handleMouseUp(e: MouseEvent): void {
  function handleMouseMove (line 111) | function handleMouseMove(e: MouseEvent): void {
  function handleWheel (line 118) | function handleWheel(e: WheelEvent): void {

FILE: desktop/src/renderer/src/components/mouse/relative.tsx
  function handleClick (line 39) | function handleClick(event: MouseEvent): void {
  function handleMouseDown (line 48) | function handleMouseDown(e: MouseEvent): void {
  function handleMouseUp (line 54) | function handleMouseUp(e: MouseEvent): void {
  function handleMouseMove (line 60) | function handleMouseMove(e: MouseEvent): void {
  function handleMouseWheel (line 74) | function handleMouseWheel(e: WheelEvent): void {
  function handlePointerLockChange (line 92) | function handlePointerLockChange(): void {
  function handleMouseEvent (line 113) | function handleMouseEvent(event: MouseRelativeEvent): void {
  function showMessage (line 142) | function showMessage(): void {
  function disableEvent (line 154) | function disableEvent(event: Event): void {

FILE: desktop/src/renderer/src/components/mouse/touchpad.ts
  constant TAP_THRESHOLD (line 5) | const TAP_THRESHOLD = 8
  constant DRAG_THRESHOLD (line 6) | const DRAG_THRESHOLD = 10
  constant VELOCITY_THRESHOLD (line 7) | const VELOCITY_THRESHOLD = 0.3
  constant LONG_PRESS_DELAY (line 8) | const LONG_PRESS_DELAY = 800
  type TouchHandlerOptions (line 10) | interface TouchHandlerOptions {
  type TouchState (line 18) | interface TouchState {
  function createInitialTouchState (line 30) | function createInitialTouchState(): TouchState {
  function createTouchHandlers (line 44) | function createTouchHandlers(state: TouchState, options: TouchHandlerOpt...

FILE: desktop/src/renderer/src/components/mouse/types.ts
  type MouseButton (line 1) | enum MouseButton {
  type MouseMoveAbsoluteEvent (line 9) | interface MouseMoveAbsoluteEvent {
  type MouseMoveRelativeEvent (line 15) | interface MouseMoveRelativeEvent {
  type MouseButtonEvent (line 21) | interface MouseButtonEvent {
  type MouseWheelEvent (line 26) | interface MouseWheelEvent {
  type MouseAbsoluteEvent (line 31) | type MouseAbsoluteEvent = MouseMoveAbsoluteEvent | MouseButtonEvent | Mo...
  type MouseRelativeEvent (line 33) | type MouseRelativeEvent = MouseMoveRelativeEvent | MouseButtonEvent | Mo...

FILE: desktop/src/renderer/src/components/ui/kbd.tsx
  function Kbd (line 3) | function Kbd({ className, ...props }: React.ComponentProps<'kbd'>) {
  function KbdGroup (line 18) | function KbdGroup({ className, ...props }: React.ComponentProps<'div'>) {

FILE: desktop/src/renderer/src/components/ui/scroll-area.tsx
  function ScrollArea (line 5) | function ScrollArea({
  function ScrollBar (line 28) | function ScrollBar({

FILE: desktop/src/renderer/src/components/virtual-keyboard/index.tsx
  type KeyboardProps (line 24) | interface KeyboardProps {
  function onKeyPress (line 36) | async function onKeyPress(key: string): Promise<void> {
  function onKeyReleased (line 62) | async function onKeyReleased(key: string): Promise<void> {
  function handleKeyEvent (line 76) | async function handleKeyEvent(event: { type: 'keydown' | 'keyup'; key: s...
  function sendReport (line 85) | async function sendReport(report: number[]): Promise<void> {
  function getButtonTheme (line 89) | function getButtonTheme(): KeyboardButtonTheme[] {

FILE: desktop/src/renderer/src/i18n/index.ts
  function getResources (line 7) | function getResources(): Resource {
  function getCurrentLanguage (line 22) | function getCurrentLanguage(): string {

FILE: desktop/src/renderer/src/jotai/device.ts
  type VideoState (line 5) | type VideoState = 'disconnected' | 'connecting' | 'connected'
  type SerialState (line 6) | type SerialState = 'notSupported' | 'disconnected' | 'connecting' | 'con...

FILE: desktop/src/renderer/src/libs/keyboard/keyboard.ts
  constant MAX_KEYS (line 3) | const MAX_KEYS = 6
  class KeyboardReport (line 5) | class KeyboardReport {
    method keyDown (line 9) | keyDown(code: string): number[] {
    method keyUp (line 21) | keyUp(code: string): number[] {
    method reset (line 30) | reset(): number[] {
    method buildReport (line 42) | private buildReport(): number[] {
    method getModifier (line 54) | getModifier(): number {
    method getPressedKeyCount (line 58) | getPressedKeyCount(): number {

FILE: desktop/src/renderer/src/libs/keyboard/keymap.ts
  function isModifier (line 269) | function isModifier(code: string): boolean {
  function getModifierBit (line 274) | function getModifierBit(code: string): number {
  function getKeycode (line 279) | function getKeycode(code: string): number | undefined {

FILE: desktop/src/renderer/src/libs/media/camera.ts
  class Camera (line 3) | class Camera {
    method open (line 10) | public async open(id: string, width: number, height: number, audioId?:...
    method updateResolution (line 51) | public async updateResolution(width: number, height: number): Promise<...
    method close (line 55) | public close(): void {
    method getStream (line 62) | public getStream(): MediaStream | null {
    method isOpen (line 66) | public isOpen(): boolean {

FILE: desktop/src/renderer/src/libs/media/permission.ts
  function checkPermission (line 4) | async function checkPermission(device: 'camera' | 'microphone'): Promise...
  function requestCameraPermission (line 21) | async function requestCameraPermission(resolution?: Resolution): Promise...
  function requestMicrophonePermission (line 47) | async function requestMicrophonePermission(): Promise<boolean> {

FILE: desktop/src/renderer/src/libs/mouse-jiggler/index.ts
  constant MOUSE_JIGGLER_INTERVAL (line 4) | const MOUSE_JIGGLER_INTERVAL = 15_000
  class MouseJiggler (line 6) | class MouseJiggler {
    method constructor (line 12) | constructor() {
    method setMode (line 20) | setMode(mode: 'enable' | 'disable'): void {
    method moveEventCallback (line 33) | moveEventCallback(): void {
    method timeoutCallback (line 39) | timeoutCallback(): void {
    method sendJiggle (line 46) | async sendJiggle(): Promise<void> {

FILE: desktop/src/renderer/src/libs/mouse/index.ts
  constant MAX_ABS_COORD (line 2) | const MAX_ABS_COORD = 4096
  function getMouseButtonBit (line 14) | function getMouseButtonBit(button: number): number {
  class MouseReportRelative (line 39) | class MouseReportRelative {
    method buttonDown (line 42) | buttonDown(button: number): void {
    method buttonUp (line 46) | buttonUp(button: number): void {
    method buildReport (line 56) | buildReport(deltaX: number, deltaY: number, wheel: number = 0): number...
    method buildButtonReport (line 66) | buildButtonReport(): number[] {
    method reset (line 70) | reset(): number[] {
    method clamp (line 75) | private clamp(value: number, min: number, max: number): number {
  class MouseAbsoluteRelative (line 88) | class MouseAbsoluteRelative {
    method buttonDown (line 91) | buttonDown(button: number): void {
    method buttonUp (line 95) | buttonUp(button: number): void {
    method buildReport (line 105) | buildReport(x: number, y: number, wheel: number = 0): number[] {
    method buildButtonReport (line 122) | buildButtonReport(lastX: number, lastY: number): number[] {
    method reset (line 126) | reset(): number[] {
    method clamp (line 131) | private clamp(value: number, min: number, max: number): number {

FILE: desktop/src/renderer/src/libs/storage/expiry.ts
  type ItemWithExpiry (line 1) | type ItemWithExpiry = {
  function setWithExpiry (line 7) | function setWithExpiry(key: string, value: string, ttl: number): void {
  function getWithExpiry (line 19) | function getWithExpiry(key: string): string | null {

FILE: desktop/src/renderer/src/libs/storage/index.ts
  constant LANGUAGE_KEY (line 5) | const LANGUAGE_KEY = 'nanokvm-usb-language'
  constant VIDEO_DEVICE_ID_KEY (line 6) | const VIDEO_DEVICE_ID_KEY = 'nanokvm-usb-video-device-id'
  constant VIDEO_RESOLUTION_KEY (line 7) | const VIDEO_RESOLUTION_KEY = 'nanokvm-usb-video-resolution'
  constant VIDEO_SCALE_KEY (line 8) | const VIDEO_SCALE_KEY = 'nanokvm-usb-video-scale'
  constant CUSTOM_RESOLUTION_KEY (line 9) | const CUSTOM_RESOLUTION_KEY = 'nanokvm-usb-custom-resolution'
  constant SERIAL_PORT_KEY (line 10) | const SERIAL_PORT_KEY = 'nanokvm-serial-port'
  constant IS_MENU_OPEN_KEY (line 11) | const IS_MENU_OPEN_KEY = 'nanokvm-is-menu-open'
  constant MOUSE_STYLE_KEY (line 12) | const MOUSE_STYLE_KEY = 'nanokvm-usb-mouse-style'
  constant MOUSE_MODE_KEY (line 13) | const MOUSE_MODE_KEY = 'nanokvm-usb-mouse-mode'
  constant MOUSE_SCROLL_DIRECTION_KEY (line 14) | const MOUSE_SCROLL_DIRECTION_KEY = 'nanokvm-usb-mouse-scroll-direction'
  constant SKIP_UPDATE_KEY (line 15) | const SKIP_UPDATE_KEY = 'nano-kvm-check-update'
  constant MOUSE_SCROLL_INTERVAL_KEY (line 16) | const MOUSE_SCROLL_INTERVAL_KEY = 'nanokvm-usb-mouse-scroll-interval'
  constant BAUD_RATE_KEY (line 17) | const BAUD_RATE_KEY = 'nanokvm-usb-baud-rate'
  constant MOUSE_JIGGLER_MODE_KEY (line 18) | const MOUSE_JIGGLER_MODE_KEY = 'nanokvm-usb-mouse-jiggler-mode'
  constant KEYBOARD_SHORTCUT_KEY (line 19) | const KEYBOARD_SHORTCUT_KEY = 'nanokvm-usb-keyboard-shortcuts'
  function getLanguage (line 21) | function getLanguage(): string | null {
  function setLanguage (line 25) | function setLanguage(language: string): void {
  function getVideoDevice (line 29) | function getVideoDevice(): string | null {
  function setVideoDevice (line 33) | function setVideoDevice(id: string): void {
  function getVideoResolution (line 37) | function getVideoResolution(): Resolution | undefined {
  function setVideoResolution (line 45) | function setVideoResolution(width: number, height: number): void {
  function getCustomResolutions (line 49) | function getCustomResolutions(): Resolution[] | undefined {
  function setCustomResolution (line 55) | function setCustomResolution(width: number, height: number): void {
  function removeCustomResolutions (line 66) | function removeCustomResolutions(): void {
  function getVideoScale (line 70) | function getVideoScale(): number | null {
  function setVideoScale (line 78) | function setVideoScale(scale: number): void {
  function getSerialPort (line 82) | function getSerialPort(): string | null {
  function setSerialPort (line 86) | function setSerialPort(port: string): void {
  function getBaudRate (line 90) | function getBaudRate(): number {
  function setBaudRate (line 98) | function setBaudRate(baudRate: number): void {
  function getIsMenuOpen (line 102) | function getIsMenuOpen(): boolean {
  function setIsMenuOpen (line 110) | function setIsMenuOpen(isOpen: boolean): void {
  function getMouseStyle (line 114) | function getMouseStyle(): string | null {
  function setMouseStyle (line 118) | function setMouseStyle(mouse: string): void {
  function getMouseMode (line 122) | function getMouseMode(): string | null {
  function setMouseMode (line 126) | function setMouseMode(mouse: string): void {
  function getMouseScrollDirection (line 130) | function getMouseScrollDirection(): number | null {
  function setMouseScrollDirection (line 138) | function setMouseScrollDirection(direction: number): void {
  function getMouseScrollInterval (line 142) | function getMouseScrollInterval(): number | null {
  function setMouseScrollInterval (line 150) | function setMouseScrollInterval(interval: number): void {
  function getSkipUpdate (line 154) | function getSkipUpdate(): boolean {
  function setSkipUpdate (line 159) | function setSkipUpdate(skip: boolean): void {
  function clearAllSettings (line 164) | function clearAllSettings(): void {
  function getMouseJigglerMode (line 179) | function getMouseJigglerMode(): 'enable' | 'disable' {
  function setMouseJigglerMode (line 184) | function setMouseJigglerMode(jiggler: 'enable' | 'disable'): void {
  function getShortcuts (line 188) | function getShortcuts(): string | null {
  function setShortcuts (line 192) | function setShortcuts(shortcuts: string): void {

FILE: desktop/src/renderer/src/types.ts
  type Resolution (line 1) | type Resolution = {
  type MediaDevice (line 6) | type MediaDevice = {
Condensed preview — 200 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (456K chars).
[
  {
    "path": ".github/workflows/build.yml",
    "chars": 2772,
    "preview": "name: Build Browser and Desktop Apps\n\non:\n  workflow_dispatch:\n  push:\n    branches:\n      - main\n  pull_request:\n    br"
  },
  {
    "path": ".github/workflows/issue-tracker.yml",
    "chars": 2460,
    "preview": "name: Issue Tracker\n\non:\n  issues:\n    types: [opened, reopened, closed]\n\njobs:\n  track-issue:\n    name: Track Issue Upd"
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 5155,
    "preview": "name: Create Tag and Release\n\non:\n  workflow_dispatch:\n    inputs:\n      prerelease:\n        description: 'Mark as pre-r"
  },
  {
    "path": ".gitignore",
    "chars": 117,
    "preview": "# Editor directories and files\n.vscode/*\n!.vscode/extensions.json\n.idea\n.DS_Store\n*.suo\n*.ntvs*\n*.njsproj\n*.sln\n*.sw?"
  },
  {
    "path": "Dockerfile",
    "chars": 458,
    "preview": "FROM node:24-alpine3.21 AS frontend\nWORKDIR /app\n\nCOPY browser browser\n\nRUN yarn global add http-server\n\nRUN cd browser "
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 3224,
    "preview": "# NanoKVM-USB\n\n<div align=\"center\">\n\n![NanoKVM-USB](https://wiki.sipeed.com/hardware/assets/NanoKVM/usb/NanoKVM-USB.png)"
  },
  {
    "path": "browser/.editorconfig",
    "chars": 146,
    "preview": "root = true\n\n[*]\ncharset = utf-8\nindent_style = space\nindent_size = 2\nend_of_line = lf\ninsert_final_newline = true\ntrim_"
  },
  {
    "path": "browser/.gitignore",
    "chars": 283,
    "preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndis"
  },
  {
    "path": "browser/.prettierignore",
    "chars": 6,
    "preview": "*.hbs\n"
  },
  {
    "path": "browser/.prettierrc.yaml",
    "chars": 576,
    "preview": "singleQuote: true\ntrailingComma: none\nprintWidth: 100\ntabWidth: 2\nbracketSpacing: true\nimportOrder:\n  - ^(react/(.*)$)|^"
  },
  {
    "path": "browser/README.md",
    "chars": 694,
    "preview": "# NanoKVM-USB Browser\n\nThis is the NanoKVM-USB browser version project.\n\nOnline website: [usbkvm.sipeed.com](https://usb"
  },
  {
    "path": "browser/eslint.config.js",
    "chars": 888,
    "preview": "import js from '@eslint/js';\nimport eslintConfigPrettier from 'eslint-config-prettier';\nimport reactHooksPlugin from 'es"
  },
  {
    "path": "browser/index.html",
    "chars": 362,
    "preview": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/"
  },
  {
    "path": "browser/package.json",
    "chars": 1502,
    "preview": "{\n  \"name\": \"nanokvm-usb\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\""
  },
  {
    "path": "browser/pnpm-workspace.yaml",
    "chars": 579,
    "preview": "overrides:\n  minimatch: ^9.0.6\n  ajv@<6.14.0: '>=6.14.0'\n  '@babel/helpers@<7.26.10': '>=7.26.10'\n  '@babel/runtime@<7.2"
  },
  {
    "path": "browser/postcss.config.js",
    "chars": 79,
    "preview": "export default {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {}\n  }\n};\n"
  },
  {
    "path": "browser/src/App.tsx",
    "chars": 4667,
    "preview": "import { CSSProperties, useEffect, useMemo, useState } from 'react';\nimport { Alert, Result, Spin } from 'antd';\nimport "
  },
  {
    "path": "browser/src/assets/index.css",
    "chars": 179,
    "preview": "@layer tailwind-base, antd;\n\n@layer tailwind-base {\n  @tailwind base;\n}\n\n@tailwind components;\n@tailwind utilities;\n\nhtm"
  },
  {
    "path": "browser/src/assets/keyboard.css",
    "chars": 2325,
    "preview": ".keyboardContainer {\n  display: flex;\n  background-color: #e5e5e5;\n  justify-content: center;\n  margin: 0 auto;\n  border"
  },
  {
    "path": "browser/src/components/device-modal/index.tsx",
    "chars": 1545,
    "preview": "import { useEffect, useState } from 'react';\nimport { Modal } from 'antd';\nimport { useAtom, useSetAtom } from 'jotai';\n"
  },
  {
    "path": "browser/src/components/device-modal/serial-port.tsx",
    "chars": 1444,
    "preview": "import { useEffect } from 'react';\nimport { Button } from 'antd';\nimport { useAtom } from 'jotai';\nimport { useTranslati"
  },
  {
    "path": "browser/src/components/device-modal/video.tsx",
    "chars": 2965,
    "preview": "import { useEffect, useState } from 'react';\nimport { Select } from 'antd';\nimport { useAtom, useAtomValue } from 'jotai"
  },
  {
    "path": "browser/src/components/keyboard/index.tsx",
    "chars": 6290,
    "preview": "import { useEffect, useRef } from 'react';\nimport { useAtomValue } from 'jotai';\n\nimport { isKeyboardEnableAtom } from '"
  },
  {
    "path": "browser/src/components/menu/audio/index.tsx",
    "chars": 2203,
    "preview": "import { useEffect, useState } from 'react';\nimport { Button, Modal } from 'antd';\nimport { useSetAtom } from 'jotai';\ni"
  },
  {
    "path": "browser/src/components/menu/fullscreen/index.tsx",
    "chars": 1315,
    "preview": "import { useEffect, useState } from 'react';\nimport { MaximizeIcon, MinimizeIcon } from 'lucide-react';\n\nexport const Fu"
  },
  {
    "path": "browser/src/components/menu/index.tsx",
    "chars": 4200,
    "preview": "import { useCallback, useEffect, useRef, useState } from 'react';\nimport { Divider } from 'antd';\nimport clsx from 'clsx"
  },
  {
    "path": "browser/src/components/menu/keyboard/index.tsx",
    "chars": 907,
    "preview": "import { useState } from 'react';\nimport { Popover } from 'antd';\nimport { KeyboardIcon } from 'lucide-react';\n\nimport {"
  },
  {
    "path": "browser/src/components/menu/keyboard/paste.tsx",
    "chars": 1555,
    "preview": "import { useState } from 'react';\nimport { ClipboardIcon } from 'lucide-react';\nimport { useTranslation } from 'react-i1"
  },
  {
    "path": "browser/src/components/menu/keyboard/shortcuts/index.tsx",
    "chars": 3052,
    "preview": "import { useEffect, useState } from 'react';\nimport { Divider, Popover } from 'antd';\nimport { CommandIcon } from 'lucid"
  },
  {
    "path": "browser/src/components/menu/keyboard/shortcuts/recorder.tsx",
    "chars": 7103,
    "preview": "import { useEffect, useRef, useState } from 'react';\nimport { Button, Divider, Input, InputRef, Modal } from 'antd';\nimp"
  },
  {
    "path": "browser/src/components/menu/keyboard/shortcuts/shortcut.tsx",
    "chars": 1310,
    "preview": "import { useState } from 'react';\n\nimport { Kbd, KbdGroup } from '@/components/ui/kbd.tsx';\nimport { device } from '@/li"
  },
  {
    "path": "browser/src/components/menu/keyboard/shortcuts/types.ts",
    "chars": 112,
    "preview": "export interface KeyInfo {\n  code: string;\n  label: string;\n}\n\nexport interface Shortcut {\n  keys: KeyInfo[];\n}\n"
  },
  {
    "path": "browser/src/components/menu/keyboard/virtual-keyboard.tsx",
    "chars": 702,
    "preview": "import { useSetAtom } from 'jotai';\nimport { KeyboardIcon } from 'lucide-react';\nimport { useTranslation } from 'react-i"
  },
  {
    "path": "browser/src/components/menu/mouse/direction.tsx",
    "chars": 1613,
    "preview": "import { ReactElement } from 'react';\nimport { Popover } from 'antd';\nimport clsx from 'clsx';\nimport { useAtom } from '"
  },
  {
    "path": "browser/src/components/menu/mouse/index.tsx",
    "chars": 2325,
    "preview": "import { useEffect, useState } from 'react';\nimport { Divider, Popover } from 'antd';\nimport { useAtom, useSetAtom } fro"
  },
  {
    "path": "browser/src/components/menu/mouse/jiggler.tsx",
    "chars": 1742,
    "preview": "import { useEffect } from 'react';\nimport { Popover } from 'antd';\nimport clsx from 'clsx';\nimport { useAtom } from 'jot"
  },
  {
    "path": "browser/src/components/menu/mouse/mode.tsx",
    "chars": 1441,
    "preview": "import { Popover } from 'antd';\nimport clsx from 'clsx';\nimport { useAtom } from 'jotai';\nimport { SquareMousePointerIco"
  },
  {
    "path": "browser/src/components/menu/mouse/speed.tsx",
    "chars": 1841,
    "preview": "import { ReactElement, useEffect, useState } from 'react';\nimport { Popover, Slider } from 'antd';\nimport { useAtom } fr"
  },
  {
    "path": "browser/src/components/menu/mouse/style.tsx",
    "chars": 1919,
    "preview": "import { Popover } from 'antd';\nimport clsx from 'clsx';\nimport { useAtom } from 'jotai';\nimport { EyeOffIcon, HandIcon,"
  },
  {
    "path": "browser/src/components/menu/recorder/index.tsx",
    "chars": 3492,
    "preview": "import { useEffect, useRef, useState } from 'react';\nimport { Video } from 'lucide-react';\n\nimport { camera } from '@/li"
  },
  {
    "path": "browser/src/components/menu/serial-port/index.tsx",
    "chars": 861,
    "preview": "import { useState } from 'react';\nimport { CpuIcon, Loader2Icon } from 'lucide-react';\n\nimport { device } from '@/libs/d"
  },
  {
    "path": "browser/src/components/menu/settings/index.tsx",
    "chars": 1390,
    "preview": "import { Popover } from 'antd';\nimport { BookIcon, DownloadIcon, SettingsIcon } from 'lucide-react';\nimport { useTransla"
  },
  {
    "path": "browser/src/components/menu/settings/language.tsx",
    "chars": 1203,
    "preview": "import { Popover } from 'antd';\nimport clsx from 'clsx';\nimport { LanguagesIcon } from 'lucide-react';\nimport { useTrans"
  },
  {
    "path": "browser/src/components/menu/video/device.tsx",
    "chars": 3072,
    "preview": "import { useEffect, useState } from 'react';\nimport { Popover } from 'antd';\nimport clsx from 'clsx';\nimport { useAtom, "
  },
  {
    "path": "browser/src/components/menu/video/index.tsx",
    "chars": 753,
    "preview": "import { Popover } from 'antd';\nimport { MonitorIcon } from 'lucide-react';\n\nimport { Device } from './device.tsx';\nimpo"
  },
  {
    "path": "browser/src/components/menu/video/resolution.tsx",
    "chars": 6373,
    "preview": "import { useEffect, useState } from 'react';\nimport { Button, Divider, InputNumber, Modal, Popover } from 'antd';\nimport"
  },
  {
    "path": "browser/src/components/menu/video/rotation.tsx",
    "chars": 1765,
    "preview": "import { ReactElement } from 'react';\nimport { Popover } from 'antd';\nimport clsx from 'clsx';\nimport { useAtom } from '"
  },
  {
    "path": "browser/src/components/menu/video/scale.tsx",
    "chars": 1920,
    "preview": "import { ReactElement, useEffect } from 'react';\nimport { Popover } from 'antd';\nimport clsx from 'clsx';\nimport { useAt"
  },
  {
    "path": "browser/src/components/mouse/absolute.tsx",
    "chars": 6138,
    "preview": "import { useEffect, useRef } from 'react';\nimport { useAtomValue } from 'jotai';\nimport { useMediaQuery } from 'react-re"
  },
  {
    "path": "browser/src/components/mouse/index.tsx",
    "chars": 331,
    "preview": "import { useAtomValue } from 'jotai';\n\nimport { mouseModeAtom } from '@/jotai/mouse.ts';\n\nimport { Absolute } from './ab"
  },
  {
    "path": "browser/src/components/mouse/relative.tsx",
    "chars": 4785,
    "preview": "import { useEffect, useRef } from 'react';\nimport { message } from 'antd';\nimport { useAtomValue } from 'jotai';\nimport "
  },
  {
    "path": "browser/src/components/mouse/touchpad.ts",
    "chars": 5420,
    "preview": "import { MouseButton } from './types';\nimport type { MouseAbsoluteEvent } from './types';\n\n// Touch event thresholds\ncon"
  },
  {
    "path": "browser/src/components/mouse/types.ts",
    "chars": 602,
    "preview": "export enum MouseButton {\n  Left = 0,\n  Middle = 1,\n  Right = 2,\n  Back = 3,\n  Forward = 4\n}\n\ninterface MouseMoveAbsolut"
  },
  {
    "path": "browser/src/components/ui/kbd.tsx",
    "chars": 838,
    "preview": "import clsx from 'clsx';\n\nfunction Kbd({ className, ...props }: React.ComponentProps<'kbd'>) {\n  return (\n    <kbd\n     "
  },
  {
    "path": "browser/src/components/ui/scroll-area.tsx",
    "chars": 1629,
    "preview": "import * as React from 'react';\nimport * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';\nimport clsx from 'cl"
  },
  {
    "path": "browser/src/components/virtual-keyboard/index.tsx",
    "chars": 4567,
    "preview": "import { useRef, useState } from 'react';\nimport clsx from 'clsx';\nimport { useAtom } from 'jotai';\nimport { XIcon } fro"
  },
  {
    "path": "browser/src/components/virtual-keyboard/keys.ts",
    "chars": 4914,
    "preview": "// main keys\nexport const keyboardOptions = {\n  theme: 'simple-keyboard hg-theme-default',\n  baseClass: 'simple-keyboard"
  },
  {
    "path": "browser/src/i18n/index.ts",
    "chars": 1135,
    "preview": "import i18n from 'i18next';\nimport type { Resource } from 'i18next';\nimport { initReactI18next } from 'react-i18next';\n\n"
  },
  {
    "path": "browser/src/i18n/languages.ts",
    "chars": 485,
    "preview": "const languages = [\n  { key: 'en', name: 'English' },\n  { key: 'ru', name: 'Русский' },\n  { key: 'zh', name: '简体中文' },\n "
  },
  {
    "path": "browser/src/i18n/locales/be.ts",
    "chars": 1960,
    "preview": "const be = {\n  translation: {\n    serial: {\n      notSupported:\n        'Seriële poort wordt niet ondersteund. Gebruik d"
  },
  {
    "path": "browser/src/i18n/locales/de.ts",
    "chars": 2113,
    "preview": "const de = {\n  translation: {\n    serial: {\n      notSupported:\n        'Seriell nicht unterstützt. Bitte benutze den De"
  },
  {
    "path": "browser/src/i18n/locales/en.ts",
    "chars": 2629,
    "preview": "const en = {\n  translation: {\n    serial: {\n      notSupported:\n        'Serial not supported. Please use the desktop Ch"
  },
  {
    "path": "browser/src/i18n/locales/ko.ts",
    "chars": 1600,
    "preview": "const ko = {\n  translation: {\n    serial: {\n      notSupported:\n        '시리얼이 지원되지 않습니다. 마우스와 키보드를 사용하려면 Chrome 브라우저를 사용"
  },
  {
    "path": "browser/src/i18n/locales/nl.ts",
    "chars": 2003,
    "preview": "const nl = {\n  translation: {\n    serial: {\n      notSupported:\n        'Seriële poort wordt niet ondersteund. Gebruik d"
  },
  {
    "path": "browser/src/i18n/locales/pl.ts",
    "chars": 2078,
    "preview": "const pl = {\n  translation: {\n    serial: {\n      notSupported:\n        'Przeglądarka nie obsługuje portu szeregowego. P"
  },
  {
    "path": "browser/src/i18n/locales/pt_br.ts",
    "chars": 2051,
    "preview": "const pt_br = {\n  translation: {\n    serial: {\n      notSupported:\n        'Serial não suportado. Use o navegador Chrome"
  },
  {
    "path": "browser/src/i18n/locales/ru.ts",
    "chars": 2271,
    "preview": "const ru = {\n  translation: {\n    serial: {\n      notSupported:\n        'Подключение к последовательному порту не поддер"
  },
  {
    "path": "browser/src/i18n/locales/zh.ts",
    "chars": 1849,
    "preview": "const zh = {\n  translation: {\n    serial: {\n      notSupported: '当前浏览器不支持串口,无法使用键鼠。请使用桌面版 Chrome 浏览器。',\n      failed: '串"
  },
  {
    "path": "browser/src/i18n/locales/zh_tw.ts",
    "chars": 1414,
    "preview": "const zh_tw = {\n  translation: {\n    serial: {\n      notSupported: '當前瀏覽器不支援序列埠,無法使用鍵鼠。請使用桌面版 Chrome 瀏覽器。',\n      failed"
  },
  {
    "path": "browser/src/jotai/device.ts",
    "chars": 594,
    "preview": "import { atom } from 'jotai';\n\nimport type { Resolution, Rotation } from '@/types.ts';\n\ntype VideoState = 'disconnected'"
  },
  {
    "path": "browser/src/jotai/keyboard.ts",
    "chars": 127,
    "preview": "import { atom } from 'jotai';\n\nexport const isKeyboardEnableAtom = atom(true);\n\nexport const isKeyboardOpenAtom = atom(f"
  },
  {
    "path": "browser/src/jotai/mouse.ts",
    "chars": 505,
    "preview": "// mouse cursor style\nimport { atom } from 'jotai';\n\nexport const mouseStyleAtom = atom('cursor-default');\n\n// mouse mod"
  },
  {
    "path": "browser/src/libs/browser/index.ts",
    "chars": 1587,
    "preview": "export type System = 'Windows' | 'macOS' | 'Linux' | 'Unknown';\n\nexport interface BrowserInfo {\n  os: System;\n  isChrome"
  },
  {
    "path": "browser/src/libs/device/index.ts",
    "chars": 1088,
    "preview": "import { CmdEvent, CmdPacket, InfoPacket } from './proto.ts';\nimport { SerialPort } from './serial-port.ts';\n\nexport cla"
  },
  {
    "path": "browser/src/libs/device/proto.ts",
    "chars": 3291,
    "preview": "export enum CmdEvent {\n  GET_INFO = 0x01,\n  SEND_KB_GENERAL_DATA = 0x02,\n  SEND_KB_MEDIA_DATA = 0x03,\n  SEND_MS_ABS_DATA"
  },
  {
    "path": "browser/src/libs/device/serial-port.ts",
    "chars": 4387,
    "preview": "import { isDisconnectError, raceWithTimeout } from './utils';\n\ntype WebSerialPort = {\n  open: (options: { baudRate: numb"
  },
  {
    "path": "browser/src/libs/device/utils.ts",
    "chars": 647,
    "preview": "export function raceWithTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n  return Promise.race([\n  "
  },
  {
    "path": "browser/src/libs/keyboard/charCodes.ts",
    "chars": 2121,
    "preview": "export const CharCodes: Record<number, number> = {\n  48: 0x27, // 0\n  49: 0x1e, // 1\n  50: 0x1f, // 2\n  51: 0x20, // 3\n "
  },
  {
    "path": "browser/src/libs/keyboard/keyboard.ts",
    "chars": 1423,
    "preview": "import { getKeycode, getModifierBit, isModifier } from './keymap';\n\nconst MAX_KEYS = 6;\n\nexport class KeyboardReport {\n "
  },
  {
    "path": "browser/src/libs/keyboard/keymap.ts",
    "chars": 5450,
    "preview": "// Modifier key bit positions\nexport const ModifierBits = {\n  LeftCtrl: 1 << 0,\n  LeftShift: 1 << 1,\n  LeftAlt: 1 << 2,\n"
  },
  {
    "path": "browser/src/libs/media/camera.ts",
    "chars": 1695,
    "preview": "import { checkPermission } from '@/libs/media/permission.ts';\n\nclass Camera {\n  id: string = '';\n  width: number = 1920;"
  },
  {
    "path": "browser/src/libs/media/permission.ts",
    "chars": 1390,
    "preview": "import { Resolution } from '@/types.ts';\n\nexport async function checkPermission(device: 'camera' | 'microphone'): Promis"
  },
  {
    "path": "browser/src/libs/mouse/index.ts",
    "chars": 3404,
    "preview": "// Maximum absolute coordinate value\nconst MAX_ABS_COORD = 4096;\n\n// Button bit positions\nconst MouseButtons = {\n  Left:"
  },
  {
    "path": "browser/src/libs/mouse-jiggler/index.ts",
    "chars": 1526,
    "preview": "import { device } from '@/libs/device';\nimport { MouseReportRelative } from '@/libs/mouse';\n\nconst MOUSE_JIGGLER_INTERVA"
  },
  {
    "path": "browser/src/libs/storage/index.ts",
    "chars": 4827,
    "preview": "import type { Resolution, Rotation } from '@/types';\n\nconst LANGUAGE_KEY = 'nanokvm-usb-language';\nconst VIDEO_DEVICE_ID"
  },
  {
    "path": "browser/src/main.tsx",
    "chars": 509,
    "preview": "import { StrictMode } from 'react';\nimport { ConfigProvider, theme } from 'antd';\nimport { createRoot } from 'react-dom/"
  },
  {
    "path": "browser/src/types.ts",
    "chars": 223,
    "preview": "export type Resolution = {\n  width: number;\n  height: number;\n};\n\nexport type Rotation = 0 | 90 | 180 | 270;\n\nexport typ"
  },
  {
    "path": "browser/src/vite-env.d.ts",
    "chars": 81,
    "preview": "/// <reference types=\"vite/client\" />\ninterface Navigator {\n  serial?: Serial;\n}\n"
  },
  {
    "path": "browser/tailwind.config.js",
    "chars": 168,
    "preview": "/** @type {import('tailwindcss').Config} */\nexport default {\n  content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],\n"
  },
  {
    "path": "browser/tsconfig.app.json",
    "chars": 673,
    "preview": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"ES2020\", \"DOM\", \"DOM."
  },
  {
    "path": "browser/tsconfig.json",
    "chars": 107,
    "preview": "{\n  \"files\": [],\n  \"references\": [{ \"path\": \"./tsconfig.app.json\" }, { \"path\": \"./tsconfig.node.json\" }]\n}\n"
  },
  {
    "path": "browser/tsconfig.node.json",
    "chars": 233,
    "preview": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"skipLibCheck\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\""
  },
  {
    "path": "browser/vite.config.d.ts",
    "chars": 76,
    "preview": "declare const _default: import('vite').UserConfig;\nexport default _default;\n"
  },
  {
    "path": "browser/vite.config.ts",
    "chars": 289,
    "preview": "import react from '@vitejs/plugin-react';\nimport { defineConfig } from 'vite';\nimport viteTsconfigPaths from 'vite-tscon"
  },
  {
    "path": "desktop/.editorconfig",
    "chars": 146,
    "preview": "root = true\n\n[*]\ncharset = utf-8\nindent_style = space\nindent_size = 2\nend_of_line = lf\ninsert_final_newline = true\ntrim_"
  },
  {
    "path": "desktop/.gitignore",
    "chars": 67,
    "preview": "node_modules\ndist\nout\n.DS_Store\n.eslintcache\n*.log*\n\n.idea\n.vscode\n"
  },
  {
    "path": "desktop/.npmrc",
    "chars": 22,
    "preview": "shamefully-hoist=true\n"
  },
  {
    "path": "desktop/.prettierignore",
    "chars": 65,
    "preview": "out\ndist\npnpm-lock.yaml\nLICENSE.md\ntsconfig.json\ntsconfig.*.json\n"
  },
  {
    "path": "desktop/.prettierrc.yaml",
    "chars": 570,
    "preview": "singleQuote: true\nsemi: false\nprintWidth: 100\ntrailingComma: none\nimportOrder:\n  - ^(react/(.*)$)|^(react$)\n  - ^(next/("
  },
  {
    "path": "desktop/README.md",
    "chars": 250,
    "preview": "# NanoKVM-USB Desktop\n\nThis is the NanoKVM-USB desktop version project.\n\n## Development\n\n```shell\ncd desktop\npnpm instal"
  },
  {
    "path": "desktop/build/entitlements.mac.plist",
    "chars": 604,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
  },
  {
    "path": "desktop/dev-app-update.yml",
    "chars": 90,
    "preview": "provider: github\nowner: sipeed\nrepo: NanoKVM-USB\nupdaterCacheDirName: nanokvm-usb-updater\n"
  },
  {
    "path": "desktop/electron-builder.yml",
    "chars": 1590,
    "preview": "appId: com.sipeed.usbkvm\nproductName: NanoKVM-USB\n\ndirectories:\n  buildResources: build\n\nfiles:\n  - '!**/.vscode/*'\n  - "
  },
  {
    "path": "desktop/electron.vite.config.ts",
    "chars": 521,
    "preview": "import { resolve } from 'path'\nimport tailwindcss from '@tailwindcss/vite'\nimport react from '@vitejs/plugin-react'\nimpo"
  },
  {
    "path": "desktop/eslint.config.mjs",
    "chars": 1191,
    "preview": "import eslintConfigPrettier from '@electron-toolkit/eslint-config-prettier'\nimport tseslint from '@electron-toolkit/esli"
  },
  {
    "path": "desktop/notarize.js",
    "chars": 530,
    "preview": "const { notarize } = require('@electron/notarize')\n\nexports.default = async function notarizing(context) {\n  const { ele"
  },
  {
    "path": "desktop/package.json",
    "chars": 3653,
    "preview": "{\n  \"name\": \"nanokvm-usb\",\n  \"version\": \"1.1.4\",\n  \"description\": \"NanoKVM-USB Desktop\",\n  \"main\": \"./out/main/index.js\""
  },
  {
    "path": "desktop/src/common/ipc-events.ts",
    "chars": 877,
    "preview": "export enum IpcEvents {\n  GET_APP_VERSION = 'get-app-version',\n  GET_PLATFORM = 'get-platform',\n  OPEN_EXTERNAL_RUL = 'o"
  },
  {
    "path": "desktop/src/main/device/index.ts",
    "chars": 1085,
    "preview": "import { CmdEvent, CmdPacket, InfoPacket } from './proto'\nimport { SerialPort } from './serial-port'\n\nexport class Devic"
  },
  {
    "path": "desktop/src/main/device/proto.ts",
    "chars": 3232,
    "preview": "export enum CmdEvent {\n  GET_INFO = 0x01,\n  SEND_KB_GENERAL_DATA = 0x02,\n  SEND_KB_MEDIA_DATA = 0x03,\n  SEND_MS_ABS_DATA"
  },
  {
    "path": "desktop/src/main/device/serial-port.ts",
    "chars": 3359,
    "preview": "import { SerialPort as SP } from 'serialport'\n\ntype Options = {\n  path: string\n  baudRate?: number\n  onDisconnect?: () ="
  },
  {
    "path": "desktop/src/main/events/app.ts",
    "chars": 1682,
    "preview": "import { app, BrowserWindow, ipcMain, IpcMainInvokeEvent, shell, systemPreferences } from 'electron'\nimport type { IpcMa"
  },
  {
    "path": "desktop/src/main/events/index.ts",
    "chars": 78,
    "preview": "export * from './app'\nexport * from './serial-port'\nexport * from './updater'\n"
  },
  {
    "path": "desktop/src/main/events/serial-port.ts",
    "chars": 2278,
    "preview": "import { ipcMain, IpcMainInvokeEvent } from 'electron'\nimport { SerialPort } from 'serialport'\n\nimport { IpcEvents } fro"
  },
  {
    "path": "desktop/src/main/events/updater.ts",
    "chars": 1379,
    "preview": "import { BrowserWindow, ipcMain } from 'electron'\nimport { autoUpdater, UpdateInfo } from 'electron-updater'\n\nimport { I"
  },
  {
    "path": "desktop/src/main/index.ts",
    "chars": 1799,
    "preview": "import { join } from 'path'\nimport { electronApp, is, optimizer } from '@electron-toolkit/utils'\nimport { app, BrowserWi"
  },
  {
    "path": "desktop/src/preload/index.d.ts",
    "chars": 144,
    "preview": "import { ElectronAPI } from '@electron-toolkit/preload'\n\ndeclare global {\n  interface Window {\n    electron: ElectronAPI"
  },
  {
    "path": "desktop/src/preload/index.ts",
    "chars": 611,
    "preview": "import { electronAPI } from '@electron-toolkit/preload'\nimport { contextBridge } from 'electron'\n\n// Custom APIs for ren"
  },
  {
    "path": "desktop/src/renderer/index.html",
    "chars": 392,
    "preview": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <title>NanoKVM-USB</title>\n    <meta\n      ht"
  },
  {
    "path": "desktop/src/renderer/src/App.tsx",
    "chars": 3504,
    "preview": "import { ReactElement, useEffect, useState } from 'react'\nimport { Result, Spin } from 'antd'\nimport clsx from 'clsx'\nim"
  },
  {
    "path": "desktop/src/renderer/src/assets/styles/base.css",
    "chars": 62,
    "preview": "html,\nbody {\n  padding: 0;\n  margin: 0;\n  background: #000;\n}\n"
  },
  {
    "path": "desktop/src/renderer/src/assets/styles/keyboard.css",
    "chars": 2325,
    "preview": ".keyboardContainer {\n  display: flex;\n  background-color: #e5e5e5;\n  justify-content: center;\n  margin: 0 auto;\n  border"
  },
  {
    "path": "desktop/src/renderer/src/assets/styles/main.css",
    "chars": 119,
    "preview": "@import './base.css';\n\n@layer tailwind-base, antd;\n\n@layer tailwind-base {\n  @tailwind base;\n}\n\n@import 'tailwindcss';\n"
  },
  {
    "path": "desktop/src/renderer/src/components/device/connect.tsx",
    "chars": 779,
    "preview": "import { ReactElement, useState } from 'react'\nimport { Modal } from 'antd'\nimport { useTranslation } from 'react-i18nex"
  },
  {
    "path": "desktop/src/renderer/src/components/device/disconnect.tsx",
    "chars": 913,
    "preview": "import { ReactElement, useEffect } from 'react'\nimport { useSetAtom } from 'jotai'\n\nimport { IpcEvents } from '@common/i"
  },
  {
    "path": "desktop/src/renderer/src/components/device/index.tsx",
    "chars": 665,
    "preview": "import { ReactElement, useEffect, useState } from 'react'\nimport { useAtomValue } from 'jotai'\n\nimport { serialPortState"
  },
  {
    "path": "desktop/src/renderer/src/components/device/serial-port.tsx",
    "chars": 2758,
    "preview": "import { ReactElement, useEffect, useState } from 'react'\nimport { Select } from 'antd'\nimport { useAtom } from 'jotai'\n"
  },
  {
    "path": "desktop/src/renderer/src/components/device/video.tsx",
    "chars": 3511,
    "preview": "import { ReactElement, useEffect, useState } from 'react'\nimport { Select } from 'antd'\nimport { useAtom, useAtomValue }"
  },
  {
    "path": "desktop/src/renderer/src/components/keyboard/index.tsx",
    "chars": 6020,
    "preview": "import { ReactElement, useEffect, useRef } from 'react'\nimport { useAtomValue } from 'jotai'\n\nimport { IpcEvents } from "
  },
  {
    "path": "desktop/src/renderer/src/components/menu/audio/index.tsx",
    "chars": 2238,
    "preview": "import { useEffect, useState } from 'react'\nimport { Button, Modal } from 'antd'\nimport { useSetAtom } from 'jotai'\nimpo"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/index.tsx",
    "chars": 3779,
    "preview": "import { ReactElement, useEffect, useRef, useState } from 'react'\nimport { Divider } from 'antd'\nimport clsx from 'clsx'"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/keyboard/index.tsx",
    "chars": 892,
    "preview": "import { ReactElement, useState } from 'react'\nimport { Popover } from 'antd'\nimport { KeyboardIcon } from 'lucide-react"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/keyboard/paste.tsx",
    "chars": 1612,
    "preview": "import { ReactElement, useState } from 'react'\nimport { ClipboardIcon } from 'lucide-react'\nimport { useTranslation } fr"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/keyboard/shortcuts/index.tsx",
    "chars": 3002,
    "preview": "import { useEffect, useState } from 'react'\nimport { ScrollArea } from '@radix-ui/react-scroll-area'\nimport { Divider, P"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/keyboard/shortcuts/recorder.tsx",
    "chars": 6359,
    "preview": "import { useEffect, useRef, useState } from 'react'\nimport { ScrollArea } from '@radix-ui/react-scroll-area'\nimport { Bu"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/keyboard/shortcuts/shortcut.tsx",
    "chars": 1401,
    "preview": "import { useState } from 'react'\n\nimport { IpcEvents } from '@common/ipc-events'\nimport { Kbd, KbdGroup } from '@rendere"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/keyboard/shortcuts/types.ts",
    "chars": 109,
    "preview": "export interface KeyInfo {\n  code: string\n  label: string\n}\n\nexport interface Shortcut {\n  keys: KeyInfo[]\n}\n"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/keyboard/virtual-keyboard.tsx",
    "chars": 670,
    "preview": "import { ReactElement } from 'react'\nimport { useSetAtom } from 'jotai'\nimport { KeyboardIcon } from 'lucide-react'\nimpo"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/language/index.tsx",
    "chars": 1234,
    "preview": "import { ReactElement } from 'react'\nimport { Popover } from 'antd'\nimport clsx from 'clsx'\nimport { LanguagesIcon } fro"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/mouse/direction.tsx",
    "chars": 1609,
    "preview": "import { ReactElement } from 'react'\nimport { Popover } from 'antd'\nimport clsx from 'clsx'\nimport { useAtom } from 'jot"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/mouse/index.tsx",
    "chars": 2223,
    "preview": "import { ReactElement, useEffect, useState } from 'react'\nimport { Divider, Popover } from 'antd'\nimport { useAtom, useS"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/mouse/jiggler.tsx",
    "chars": 1771,
    "preview": "import { ReactElement, useEffect } from 'react'\nimport { Popover } from 'antd'\nimport clsx from 'clsx'\nimport { useAtom "
  },
  {
    "path": "desktop/src/renderer/src/components/menu/mouse/mode.tsx",
    "chars": 1497,
    "preview": "import { ReactElement } from 'react'\nimport { Popover } from 'antd'\nimport clsx from 'clsx'\nimport { useAtom } from 'jot"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/mouse/speed.tsx",
    "chars": 1847,
    "preview": "import { ReactElement, useEffect, useState } from 'react'\nimport { Popover, Slider } from 'antd'\nimport { useAtom } from"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/mouse/style.tsx",
    "chars": 1973,
    "preview": "import { ReactElement } from 'react'\nimport { Popover } from 'antd'\nimport clsx from 'clsx'\nimport { useAtom } from 'jot"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/recorder/index.tsx",
    "chars": 3450,
    "preview": "import { useEffect, useRef, useState } from 'react'\nimport { Video } from 'lucide-react'\n\nimport { camera } from '@rende"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/serial-port/index.tsx",
    "chars": 4718,
    "preview": "import { ReactElement, useEffect, useState } from 'react'\nimport { Divider, Popover, Select } from 'antd'\nimport clsx fr"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/settings/about.tsx",
    "chars": 2624,
    "preview": "import { ReactElement, useEffect, useState } from 'react'\nimport { GithubOutlined, XOutlined } from '@ant-design/icons'\n"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/settings/appearance.tsx",
    "chars": 1906,
    "preview": "import { ReactElement, useEffect, useState } from 'react'\nimport { Divider, Select, Switch } from 'antd'\nimport { Langua"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/settings/index.tsx",
    "chars": 3805,
    "preview": "import { ReactElement, useEffect, useState } from 'react'\nimport { Badge, Modal } from 'antd'\nimport clsx from 'clsx'\nim"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/settings/reset.tsx",
    "chars": 1761,
    "preview": "import { ReactElement, useState } from 'react'\nimport { Button, Modal } from 'antd'\nimport { useTranslation } from 'reac"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/settings/update.tsx",
    "chars": 3877,
    "preview": "import { ReactElement, useEffect, useState } from 'react'\nimport { LoadingOutlined, RocketOutlined, SmileOutlined } from"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/video/device.tsx",
    "chars": 3365,
    "preview": "import { ReactElement, useEffect, useState } from 'react'\nimport { Popover } from 'antd'\nimport clsx from 'clsx'\nimport "
  },
  {
    "path": "desktop/src/renderer/src/components/menu/video/index.tsx",
    "chars": 693,
    "preview": "import { ReactElement } from 'react'\nimport { Popover } from 'antd'\nimport { MonitorIcon } from 'lucide-react'\n\nimport {"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/video/resolution.tsx",
    "chars": 6393,
    "preview": "import React, { ReactElement, useEffect, useState } from 'react'\nimport { Button, Divider, InputNumber, Modal, Popover }"
  },
  {
    "path": "desktop/src/renderer/src/components/menu/video/scale.tsx",
    "chars": 1763,
    "preview": "import { ReactElement, useEffect } from 'react'\nimport { Popover } from 'antd'\nimport clsx from 'clsx'\nimport { useAtom "
  },
  {
    "path": "desktop/src/renderer/src/components/mouse/absolute.tsx",
    "chars": 6104,
    "preview": "import { ReactElement, useEffect, useRef } from 'react'\nimport { useAtomValue } from 'jotai'\nimport { useMediaQuery } fr"
  },
  {
    "path": "desktop/src/renderer/src/components/mouse/index.tsx",
    "chars": 372,
    "preview": "import { ReactElement } from 'react'\nimport { useAtomValue } from 'jotai'\n\nimport { mouseModeAtom } from '@renderer/jota"
  },
  {
    "path": "desktop/src/renderer/src/components/mouse/relative.tsx",
    "chars": 4767,
    "preview": "import { ReactElement, useEffect, useRef } from 'react'\nimport { message } from 'antd'\nimport { useAtomValue } from 'jot"
  },
  {
    "path": "desktop/src/renderer/src/components/mouse/touchpad.ts",
    "chars": 5330,
    "preview": "import { MouseButton } from './types'\nimport type { MouseAbsoluteEvent } from './types'\n\n// Touch event thresholds\nconst"
  },
  {
    "path": "desktop/src/renderer/src/components/mouse/types.ts",
    "chars": 590,
    "preview": "export enum MouseButton {\n  Left = 0,\n  Middle = 1,\n  Right = 2,\n  Back = 3,\n  Forward = 4\n}\n\ninterface MouseMoveAbsolut"
  },
  {
    "path": "desktop/src/renderer/src/components/ui/kbd.tsx",
    "chars": 834,
    "preview": "import clsx from 'clsx'\n\nfunction Kbd({ className, ...props }: React.ComponentProps<'kbd'>) {\n  return (\n    <kbd\n      "
  },
  {
    "path": "desktop/src/renderer/src/components/ui/scroll-area.tsx",
    "chars": 1623,
    "preview": "import * as React from 'react'\nimport * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area'\nimport clsx from 'clsx"
  },
  {
    "path": "desktop/src/renderer/src/components/virtual-keyboard/index.tsx",
    "chars": 4647,
    "preview": "import { ReactElement, useRef, useState } from 'react'\nimport clsx from 'clsx'\nimport { useAtom } from 'jotai'\nimport { "
  },
  {
    "path": "desktop/src/renderer/src/components/virtual-keyboard/virtual-keys.ts",
    "chars": 4908,
    "preview": "// main keys\nexport const keyboardOptions = {\n  theme: 'simple-keyboard hg-theme-default',\n  baseClass: 'simple-keyboard"
  },
  {
    "path": "desktop/src/renderer/src/env.d.ts",
    "chars": 38,
    "preview": "/// <reference types=\"vite/client\" />\n"
  },
  {
    "path": "desktop/src/renderer/src/i18n/index.ts",
    "chars": 1124,
    "preview": "import i18n from 'i18next'\nimport type { Resource } from 'i18next'\nimport { initReactI18next } from 'react-i18next'\n\nimp"
  },
  {
    "path": "desktop/src/renderer/src/i18n/languages.ts",
    "chars": 512,
    "preview": "const languages = [\n  { key: 'en', name: 'English' },\n  { key: 'ru', name: 'Русский' },\n  { key: 'zh', name: '简体中文' },\n "
  },
  {
    "path": "desktop/src/renderer/src/i18n/locales/be.ts",
    "chars": 3169,
    "preview": "const be = {\n  translation: {\n    camera: {\n      tip: 'Wachten op toelating...',\n      denied: 'Toelating geweigerd',\n "
  },
  {
    "path": "desktop/src/renderer/src/i18n/locales/de.ts",
    "chars": 3424,
    "preview": "const de = {\n  translation: {\n    camera: {\n      tip: 'Warten auf Berechtigung...',\n      denied: 'Berechtigung verweig"
  },
  {
    "path": "desktop/src/renderer/src/i18n/locales/en.ts",
    "chars": 3544,
    "preview": "const en = {\n  translation: {\n    camera: {\n      tip: 'Waiting for authorization...',\n      denied: 'Authorization fail"
  },
  {
    "path": "desktop/src/renderer/src/i18n/locales/ja.ts",
    "chars": 2631,
    "preview": "const ja = {\n  translation: {\n    camera: {\n      tip: '認証を待っています...',\n      denied: '認証に失敗しました',\n      authorize:\n     "
  },
  {
    "path": "desktop/src/renderer/src/i18n/locales/ko.ts",
    "chars": 1905,
    "preview": "const ko = {\n  translation: {\n    camera: {\n      tip: '권한을 기다리는 중...',\n      denied: '권한이 거부되었습니다.',\n      authorize: '"
  },
  {
    "path": "desktop/src/renderer/src/i18n/locales/nl.ts",
    "chars": 3203,
    "preview": "const nl = {\n  translation: {\n    camera: {\n      tip: 'Wachten op toestemming...',\n      denied: 'Toestemming geweigerd"
  },
  {
    "path": "desktop/src/renderer/src/i18n/locales/pl.ts",
    "chars": 2410,
    "preview": "const pl = {\n  translation: {\n    camera: {\n      tip: 'Oczekiwanie na autoryzację...',\n      denied: 'Brak uprawnień',\n"
  },
  {
    "path": "desktop/src/renderer/src/i18n/locales/pt_br.ts",
    "chars": 2462,
    "preview": "const pt_br = {\n  translation: {\n    camera: {\n      tip: 'Esperando autorização...',\n      denied: 'Falha na autorizaçã"
  },
  {
    "path": "desktop/src/renderer/src/i18n/locales/ru.ts",
    "chars": 3444,
    "preview": "const ru = {\n  translation: {\n    camera: {\n      tip: 'Ожидание доступа...',\n      denied: 'Доступ отказан',\n      auth"
  },
  {
    "path": "desktop/src/renderer/src/i18n/locales/zh.ts",
    "chars": 2485,
    "preview": "const zh = {\n  translation: {\n    camera: {\n      tip: '等待授权...',\n      denied: '权限不足',\n      authorize: '远程桌面需要获取摄像头权限,"
  },
  {
    "path": "desktop/src/renderer/src/i18n/locales/zh_tw.ts",
    "chars": 1412,
    "preview": "const zh_tw = {\n  translation: {\n    serial: {\n      notSupported: '當前瀏覽器不支援序列埠,無法使用鍵鼠。請使用桌面版 Chrome 瀏覽器。',\n      failed"
  },
  {
    "path": "desktop/src/renderer/src/jotai/device.ts",
    "chars": 605,
    "preview": "import { atom } from 'jotai'\n\nimport { Resolution } from '@renderer/types'\n\ntype VideoState = 'disconnected' | 'connecti"
  },
  {
    "path": "desktop/src/renderer/src/jotai/keyboard.ts",
    "chars": 124,
    "preview": "import { atom } from 'jotai'\n\nexport const isKeyboardEnableAtom = atom(true)\n\nexport const isKeyboardOpenAtom = atom(fal"
  },
  {
    "path": "desktop/src/renderer/src/jotai/mouse.ts",
    "chars": 463,
    "preview": "// mouse cursor style\nimport { atom } from 'jotai'\n\nexport const mouseStyleAtom = atom('cursor-default')\n\n// mouse mode:"
  },
  {
    "path": "desktop/src/renderer/src/libs/keyboard/charCodes.ts",
    "chars": 2119,
    "preview": "export const CharCodes: Record<number, number> = {\n  48: 0x27, // 0\n  49: 0x1e, // 1\n  50: 0x1f, // 2\n  51: 0x20, // 3\n "
  },
  {
    "path": "desktop/src/renderer/src/libs/keyboard/keyboard.ts",
    "chars": 1401,
    "preview": "import { getKeycode, getModifierBit, isModifier } from './keymap'\n\nconst MAX_KEYS = 6\n\nexport class KeyboardReport {\n  p"
  },
  {
    "path": "desktop/src/renderer/src/libs/keyboard/keymap.ts",
    "chars": 5444,
    "preview": "// Modifier key bit positions\nexport const ModifierBits = {\n  LeftCtrl: 1 << 0,\n  LeftShift: 1 << 1,\n  LeftAlt: 1 << 2,\n"
  },
  {
    "path": "desktop/src/renderer/src/libs/media/camera.ts",
    "chars": 1707,
    "preview": "import { checkPermission } from '@renderer/libs/media/permission'\n\nclass Camera {\n  id: string = ''\n  width: number = 19"
  },
  {
    "path": "desktop/src/renderer/src/libs/media/permission.ts",
    "chars": 2304,
    "preview": "import { IpcEvents } from '@common/ipc-events'\nimport type { Resolution } from '@renderer/types'\n\nexport async function "
  },
  {
    "path": "desktop/src/renderer/src/libs/mouse/index.ts",
    "chars": 3370,
    "preview": "// Maximum absolute coordinate value\nconst MAX_ABS_COORD = 4096\n\n// Button bit positions\nconst MouseButtons = {\n  Left: "
  },
  {
    "path": "desktop/src/renderer/src/libs/mouse-jiggler/index.ts",
    "chars": 1641,
    "preview": "import { IpcEvents } from '@common/ipc-events'\nimport { MouseReportRelative } from '@renderer/libs/mouse'\n\nconst MOUSE_J"
  },
  {
    "path": "desktop/src/renderer/src/libs/storage/expiry.ts",
    "chars": 725,
    "preview": "type ItemWithExpiry = {\n  value: string\n  expiry: number\n}\n\n// set the value with expiration time (unit: milliseconds)\ne"
  },
  {
    "path": "desktop/src/renderer/src/libs/storage/index.ts",
    "chars": 6014,
    "preview": "import type { Resolution } from '@renderer/types'\n\nimport { getWithExpiry, setWithExpiry } from './expiry'\n\nconst LANGUA"
  },
  {
    "path": "desktop/src/renderer/src/main.tsx",
    "chars": 524,
    "preview": "import React from 'react'\nimport { ConfigProvider, theme } from 'antd'\nimport ReactDOM from 'react-dom/client'\n\nimport A"
  },
  {
    "path": "desktop/src/renderer/src/types.ts",
    "chars": 171,
    "preview": "export type Resolution = {\n  width: number\n  height: number\n}\n\nexport type MediaDevice = {\n  videoId: string\n  videoName"
  },
  {
    "path": "desktop/tsconfig.json",
    "chars": 107,
    "preview": "{\n  \"files\": [],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }, { \"path\": \"./tsconfig.web.json\" }]\n}\n"
  },
  {
    "path": "desktop/tsconfig.node.json",
    "chars": 341,
    "preview": "{\n  \"extends\": \"@electron-toolkit/tsconfig/tsconfig.node.json\",\n  \"include\": [\n    \"electron.vite.config.*\",\n    \"src/co"
  },
  {
    "path": "desktop/tsconfig.web.json",
    "chars": 456,
    "preview": "{\n  \"extends\": \"@electron-toolkit/tsconfig/tsconfig.web.json\",\n  \"include\": [\n    \"src/common/**/*\",\n    \"src/renderer/s"
  },
  {
    "path": "docker-compose.yml",
    "chars": 183,
    "preview": "services:\n  nanokvm-usb:\n    build:\n      context: ./\n      dockerfile: Dockerfile\n    image: sipeed/nanokvm-usb:latest\n"
  },
  {
    "path": "nginx.conf",
    "chars": 734,
    "preview": "worker_processes  1;\n\nerror_log /dev/stdout info;\n\nevents {\n    worker_connections 1024;\n}\n\nhttp {\n    include mime.type"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the sipeed/NanoKVM-USB GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 200 files (408.3 KB), approximately 118.1k tokens, and a symbol index with 476 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!