chore: main window
4
.gitattributes
vendored
@ -1,4 +0,0 @@
|
||||
*.js linguist-vendored
|
||||
*.tsx linguist-vendored
|
||||
*.scss linguist-vendored
|
||||
src/**/*.ts linguist-vendored
|
||||
53
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@ -1,53 +0,0 @@
|
||||
name: '🕷️ Bug report'
|
||||
description: 'report bugs'
|
||||
title: '[Bug]'
|
||||
labels:
|
||||
- 'bug'
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Please **DO NOT** file issues here if you are having problems with ChatGPT itself. Issues should **ONLY** be created here for bugs that pertain to this package, [lencx/ChatGPT](https://github.com/lencx/ChatGPT). If you are experiencing an issue on [chat.openai.com](https://chat.openai.com), please contact **OpenAI** for support or submit feedback through ChatGPT itself. If you **only have an issue with this app** and do not have the issue on [chat.openai.com](https://chat.openai.com), please file an issue here.
|
||||
|
||||
Please make sure to [search for existing issues](https://github.com/lencx/ChatGPT/issues) before filing a new one!
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Non-ChatGPT bug
|
||||
options:
|
||||
- label: |
|
||||
This issue does not occur on chat.openai.com and only occurs on this app.
|
||||
required: true
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Bug report
|
||||
Please fill in the following information to help us reproduce the bug:
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: 'Please specify the version of ChatGPT you are using, a newer version may have fixed the bug you encountered.Check the [UPDATE_LOG](https://github.com/lencx/ChatGPT/blob/main/UPDATE_LOG.md) for more information.'
|
||||
placeholder: 'e.g. v0.1.0'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: bug
|
||||
attributes:
|
||||
label: Bug description
|
||||
description: |
|
||||
Please describe the bug here,if possible, please provide a minimal example to reproduce the bug.The content of `~/.chatgpt/chatgpt.log` may be helpful if you encounter a crash.
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: OS
|
||||
attributes:
|
||||
label: OS
|
||||
description: 'Please specify the OS you are using.'
|
||||
placeholder: 'e.g. Ubuntu 22.04'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: Environment
|
||||
description: 'If you think your environment may be related to the problem, please describe it here.'
|
||||
37
.github/ISSUE_TEMPLATE/build_error_report.yml
vendored
@ -1,37 +0,0 @@
|
||||
name: '❌ Build error report'
|
||||
description: 'report errors when building by yourself'
|
||||
title: '[Build Error]'
|
||||
labels:
|
||||
- 'build error'
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Please make sure to [search for existing issues](https://github.com/lencx/ChatGPT/issues) before filing a new one!'
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Please make sure to build from the source code with the latest version of ChatGPT.'
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Build error report
|
||||
Please fill in the following information to help us reproduce the bug:
|
||||
- type: textarea
|
||||
id: error
|
||||
attributes:
|
||||
label: Error message
|
||||
description: 'Please paste the error message here.'
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: OS
|
||||
attributes:
|
||||
label: OS
|
||||
description: 'Please specify the OS you are using.'
|
||||
placeholder: 'e.g. Ubuntu 22.04'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: Environment
|
||||
description: 'If you think your environment may be related to the problem, please describe it here.'
|
||||
1
.github/ISSUE_TEMPLATE/config.yml
vendored
@ -1 +0,0 @@
|
||||
blank_issues_enabled: false
|
||||
19
.github/ISSUE_TEMPLATE/docmentation_issue.yml
vendored
@ -1,19 +0,0 @@
|
||||
name: '📚 Documentation Issue'
|
||||
description: 'report documentation issues, typos welcome!'
|
||||
title: '[Doc]'
|
||||
labels:
|
||||
- 'documentation'
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Please make sure to [search for existing issues](https://github.com/lencx/ChatGPT/issues) before creating a new one.'
|
||||
- type: textarea
|
||||
id: doc-description
|
||||
attributes:
|
||||
label: 'Provide a description of requested docs changes'
|
||||
description: 'Briefly describe the requested docs changes.'
|
||||
validations:
|
||||
required: true
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Please limit one request per issue.
|
||||
34
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@ -1,34 +0,0 @@
|
||||
name: '⭐ Feature or enhancement request'
|
||||
description: 'suggest new features or enhancements'
|
||||
title: '[Feature]'
|
||||
labels:
|
||||
- 'enhancement'
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Please make sure to [search for existing issues](https://github.com/lencx/ChatGPT/issues) before creating a new one.'
|
||||
- type: textarea
|
||||
id: feature-description
|
||||
attributes:
|
||||
label: 'Feature description'
|
||||
description: "Describe the feature or enhancements you'd like to see."
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: motivation
|
||||
attributes:
|
||||
label: 'Motivation'
|
||||
description: 'Describe the motivation for this feature or enhancement.'
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: 'Alternatives'
|
||||
description: "Describe any alternatives you've considered."
|
||||
- type: textarea
|
||||
id: additional-context
|
||||
attributes:
|
||||
label: 'Additional context'
|
||||
description: 'Add any other context or screenshots about the feature request here.'
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Please limit one request per issue.
|
||||
34
.github/ISSUE_TEMPLATE/security.yml
vendored
@ -1,34 +0,0 @@
|
||||
name: '⚠️ Security&Privacy issue'
|
||||
description: 'Report security or privacy issues'
|
||||
title: '[Security]'
|
||||
labels:
|
||||
- 'security'
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Please make sure to [search for existing issues](https://github.com/lencx/ChatGPT/issues) before creating a new one.'
|
||||
- type: textarea
|
||||
id: security-description
|
||||
attributes:
|
||||
label: 'Description'
|
||||
description: 'Describe the security or privacy issue.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: motivation
|
||||
attributes:
|
||||
label: 'Motivation'
|
||||
description: 'Describe the motivation for this security or privacy issue.'
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: 'Alternatives'
|
||||
description: "Describe any alternatives you've considered."
|
||||
- type: textarea
|
||||
id: additional-context
|
||||
attributes:
|
||||
label: 'Additional context'
|
||||
description: 'Add any other context or screenshots about the security or privacy issue here.'
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Please limit one request per issue.
|
||||
197
.github/workflows/release.yml
vendored
@ -1,197 +0,0 @@
|
||||
name: Release CI
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
|
||||
|
||||
jobs:
|
||||
build-chatgpt:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- build: linux
|
||||
os: ubuntu-latest
|
||||
arch: x86_64
|
||||
target: x86_64-unknown-linux-gnu
|
||||
- build: macos
|
||||
os: macos-latest
|
||||
arch: x86_64
|
||||
target: x86_64-apple-darwin
|
||||
- build: macos
|
||||
os: macos-latest
|
||||
arch: aarch64
|
||||
target: aarch64-apple-darwin
|
||||
- build: windows
|
||||
os: windows-latest
|
||||
arch: x86_64
|
||||
target: x86_64-pc-windows-msvc
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: pnpm/action-setup@v2
|
||||
name: Install pnpm
|
||||
id: pnpm-install
|
||||
with:
|
||||
version: 7
|
||||
run_install: false
|
||||
|
||||
- name: Install Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 18
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: 'Setup Rust'
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: ${{ matrix.target }}
|
||||
|
||||
- name: Install dependencies (ubuntu only)
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libayatana-appindicator3-dev librsvg2-dev patchelf
|
||||
|
||||
- name: Build FE
|
||||
run: pnpm build:fe
|
||||
|
||||
- name: Install rust target
|
||||
run: rustup target add ${{ matrix.target }}
|
||||
|
||||
- name: fix tray icon
|
||||
if: matrix.os != 'macos-latest'
|
||||
run: |
|
||||
pnpm fix:tray
|
||||
|
||||
- run: pnpm build --target ${{ matrix.target }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
|
||||
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
with:
|
||||
name: artifacts-${{ matrix.arch }}
|
||||
path: |
|
||||
./target/${{ matrix.target }}/release/bundle/appimage/**.AppImage.*
|
||||
./target/${{ matrix.target }}/release/bundle/deb/**.deb
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: matrix.os == 'macos-latest'
|
||||
with:
|
||||
name: artifacts-${{ matrix.arch }}
|
||||
path: |
|
||||
./target/${{ matrix.target }}/release/bundle/dmg/**.dmg
|
||||
./target/${{ matrix.target }}/release/bundle/macos/**.app.*
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: matrix.os == 'windows-latest'
|
||||
with:
|
||||
name: artifacts-${{ matrix.arch }}
|
||||
path: |
|
||||
./target/${{ matrix.target }}/release/bundle/msi/**
|
||||
|
||||
release-chatgpt:
|
||||
needs: build-chatgpt
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Query version number
|
||||
run: echo "version=${GITHUB_REF:11}" >> $GITHUB_ENV
|
||||
|
||||
- name: Download x86_64 artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: artifacts-x86_64
|
||||
path: artifacts/x86_64
|
||||
|
||||
- name: Download aarch64 artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: artifacts-aarch64
|
||||
path: artifacts/aarch64
|
||||
|
||||
- name: Rename artifacts
|
||||
run: |
|
||||
mv "artifacts/aarch64/dmg/ChatGPT_${{ env.version }}_aarch64.dmg" "artifacts/ChatGPT_${{ env.version }}_macos_aarch64.dmg"
|
||||
mv "artifacts/aarch64/macos/ChatGPT.app.tar.gz" "artifacts/ChatGPT_${{ env.version }}_macos_aarch64.app.tar.gz"
|
||||
mv "artifacts/aarch64/macos/ChatGPT.app.tar.gz.sig" "artifacts/ChatGPT_${{ env.version }}_macos_aarch64.app.tar.gz.sig"
|
||||
|
||||
mv "artifacts/x86_64/dmg/ChatGPT_${{ env.version }}_x64.dmg" "artifacts/ChatGPT_${{ env.version }}_macos_x86_64.dmg"
|
||||
mv "artifacts/x86_64/macos/ChatGPT.app.tar.gz" "artifacts/ChatGPT_${{ env.version }}_macos_x86_64.app.tar.gz"
|
||||
mv "artifacts/x86_64/macos/ChatGPT.app.tar.gz.sig" "artifacts/ChatGPT_${{ env.version }}_macos_x86_64.app.tar.gz.sig"
|
||||
|
||||
mv "artifacts/x86_64/deb/chat-gpt_${{ env.version }}_amd64.deb" "artifacts/x86_64/deb/ChatGPT_${{ env.version }}_linux_x86_64.deb"
|
||||
mv "artifacts/x86_64/appimage/chat-gpt_${{ env.version }}_amd64.AppImage.tar.gz" "artifacts/ChatGPT_${{ env.version }}_linux_x86_64.AppImage.tar.gz"
|
||||
mv "artifacts/x86_64/appimage/chat-gpt_${{ env.version }}_amd64.AppImage.tar.gz.sig" "artifacts/ChatGPT_${{ env.version }}_linux_x86_64.AppImage.tar.gz.sig"
|
||||
|
||||
mv "artifacts/x86_64/ChatGPT_${{ env.version }}_x64_en-US.msi" "artifacts/ChatGPT_${{ env.version }}_windows_x86_64.msi"
|
||||
mv "artifacts/x86_64/ChatGPT_${{ env.version }}_x64_en-US.msi.zip" "artifacts/ChatGPT_${{ env.version }}_windows_x86_64.msi.zip"
|
||||
mv "artifacts/x86_64/ChatGPT_${{ env.version }}_x64_en-US.msi.zip.sig" "artifacts/ChatGPT_${{ env.version }}_windows_x86_64.msi.zip.sig"
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@master
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: v${{ env.version }}
|
||||
name: ChatGPT v${{ env.version }}
|
||||
body: See the assets to download this version and install.
|
||||
prerelease: false
|
||||
generate_release_notes: false
|
||||
files: ./artifacts/**/*
|
||||
|
||||
updater:
|
||||
runs-on: ubuntu-latest
|
||||
needs: release-chatgpt
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: pnpm/action-setup@v2
|
||||
name: Install pnpm
|
||||
id: pnpm-install
|
||||
with:
|
||||
version: 7
|
||||
run_install: false
|
||||
|
||||
- name: Install Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 18
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Updater JSON
|
||||
run: pnpm updater --token=${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Deploy install.json
|
||||
uses: peaceiris/actions-gh-pages@v3
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
publish_dir: ./updater
|
||||
# force_orphan: true
|
||||
|
||||
- name: Query version number
|
||||
run: echo "version=${GITHUB_REF:11}" >> $GITHUB_ENV
|
||||
|
||||
# publish-winget:
|
||||
# # Action can only be run on windows
|
||||
# runs-on: windows-latest
|
||||
# needs: [build-chatgpt, release-chatgpt]
|
||||
# steps:
|
||||
# - uses: vedantmgoyal2009/winget-releaser@v1
|
||||
# with:
|
||||
# identifier: lencx.ChatGPT
|
||||
# token: ${{ secrets.WINGET_TOKEN }}
|
||||
# version: ${{ github.event.release.tag_name }}
|
||||
16
.gitignore
vendored
@ -1,15 +1,3 @@
|
||||
package-lock.json
|
||||
node_modules/
|
||||
|
||||
.yarn/*
|
||||
.pnp.*
|
||||
|
||||
# Testing
|
||||
private/
|
||||
|
||||
# rust
|
||||
target/
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
@ -19,6 +7,10 @@ yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# rust
|
||||
target/
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
@ -1,6 +0,0 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
|
||||
npm run pretty-quick
|
||||
cargo fmt
|
||||
git add .
|
||||
@ -1,45 +0,0 @@
|
||||
package-lock.json
|
||||
node_modules/
|
||||
yarn.lock
|
||||
*.lock
|
||||
|
||||
casks/
|
||||
|
||||
# rust
|
||||
src-tauri/
|
||||
target/
|
||||
Cargo.lock
|
||||
*.toml
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
assets/**
|
||||
public/**
|
||||
|
||||
.gitattributes
|
||||
.gitignore
|
||||
.prettierignore
|
||||
|
||||
LICENSE
|
||||
@ -1,7 +0,0 @@
|
||||
{
|
||||
"trailingComma": "all",
|
||||
"singleQuote": true,
|
||||
"semi": true,
|
||||
"tabWidth": 2,
|
||||
"printWidth": 100
|
||||
}
|
||||
2817
Cargo.lock
generated
10
Cargo.toml
@ -1,9 +1,11 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["src-tauri"]
|
||||
|
||||
# fix: mac v1.2.0 can not copy/paste
|
||||
# https://github.com/tauri-apps/tauri/issues/5669
|
||||
# https://v2.tauri.app/test/webdriver/example/#adding-tauri-to-the-cargo-project
|
||||
[profile.release]
|
||||
strip = true
|
||||
lto = true
|
||||
incremental = false
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
661
LICENSE
@ -1,661 +0,0 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are 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.
|
||||
|
||||
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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
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 AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
262
README-ZH_CN.md
@ -1,262 +0,0 @@
|
||||
<p align="center">
|
||||
<img width="180" src="./public/logo.png" alt="ChatGPT">
|
||||
<h1 align="center">ChatGPT</h1>
|
||||
<p align="center">ChatGPT 桌面应用(Mac, Windows and Linux)</p>
|
||||
</p>
|
||||
|
||||
[](./README.md)
|
||||
[](./README-ZH_CN.md)\
|
||||
[](https://github.com/lencx/ChatGPT/releases)
|
||||
[](https://discord.gg/aPhCRf4zZr)
|
||||
[](https://twitter.com/lencx_)
|
||||
|
||||
<!-- [](https://twitter.com/lencx_) -->
|
||||
|
||||
<a href="https://www.buymeacoffee.com/lencx" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 145px !important;" ></a>
|
||||
|
||||
**它是一个非官方项目,仅供个人学习研究。ChatGPT 桌面应用开源的这段时间,受到了很多关注,谢谢大家的支持。随着事情的发展,有两个问题严重影响了项目的下一步开发计划:**
|
||||
|
||||
- **有人利用它进行二次打包销售,谋取私利**
|
||||
- **ChatGPT 因名称和图标问题可能会涉及侵权**
|
||||
|
||||
**新仓库:https://github.com/lencx/nofwl**
|
||||
|
||||
---
|
||||
|
||||
## 📦 安装
|
||||
|
||||
- [📝 更新日志](./UPDATE_LOG.md)
|
||||
- [🕒 历史版本...](https://github.com/lencx/ChatGPT/releases)
|
||||
|
||||
<!-- tr-download-start -->
|
||||
|
||||
### Windows
|
||||
|
||||
- [ChatGPT_1.1.0_windows_x86_64.msi](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_windows_x86_64.msi)
|
||||
- 使用 [winget](https://winstall.app/apps/lencx.ChatGPT):
|
||||
|
||||
```bash
|
||||
# install the latest version
|
||||
winget install --id=lencx.ChatGPT -e
|
||||
|
||||
# install the specified version
|
||||
winget install --id=lencx.ChatGPT -e --version 0.10.0
|
||||
```
|
||||
|
||||
**注意:如果安装路径和应用名称相同,会导致冲突 ([#142](https://github.com/lencx/ChatGPT/issues/142))**
|
||||
|
||||
### Mac
|
||||
|
||||
- [ChatGPT_1.1.0_macos_aarch64.dmg](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_macos_aarch64.dmg)
|
||||
- [ChatGPT_1.1.0_macos_x86_64.dmg](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_macos_x86_64.dmg)
|
||||
- Homebrew \
|
||||
_[Homebrew 快捷安装](https://brew.sh) ([Cask](https://docs.brew.sh/Cask-Cookbook)):_
|
||||
```sh
|
||||
brew tap lencx/chatgpt https://github.com/lencx/ChatGPT.git
|
||||
brew install --cask chatgpt --no-quarantine
|
||||
```
|
||||
如果你坚持使用 _[Brewfile](https://github.com/Homebrew/homebrew-bundle#usage)_ ,则需要添加以下配置:
|
||||
```rb
|
||||
repo = "lencx/chatgpt"
|
||||
tap repo, "https://github.com/#{repo}.git"
|
||||
cask "chatgpt", args: { "no-quarantine": true }
|
||||
```
|
||||
|
||||
如果在 macOS 上安装软件时遇到 `“ChatGPT” is damaged and can't be opened. You should move it to the Trash.` 错误消息,可能是由于 macOS 安全设置的限制导致的。为了解决此问题,请在终端尝试以下命令:
|
||||
|
||||
```bash
|
||||
sudo xattr -r -d com.apple.quarantine /YOUR_PATH/ChatGPT.app
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
- [ChatGPT_1.1.0_linux_x86_64.deb](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_linux_x86_64.deb)
|
||||
- [ChatGPT_1.1.0_linux_x86_64.AppImage.tar.gz](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_linux_x86_64.AppImage.tar.gz): **工作可靠,`.deb` 运行失败时可以尝试它**
|
||||
|
||||
<!-- tr-download-end -->
|
||||
|
||||
## 📢 公告
|
||||
|
||||
这是一个令人兴奋的重大更新。像 `Telegram 机器人指令` 那样工作,帮助你快速填充自定模型,来让 ChatGPT 按照你想要的方式去工作。这个项目倾注了我大量业余时间,如果它对你有所帮助,宣传转发,或者 star 都是对我的巨大鼓励。我希望我可以持续更新下去,加入更多有趣的功能。
|
||||
|
||||
### 如何使用指令?
|
||||
|
||||
你可以从 [awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts) 来寻找有趣的功能来导入到应用。也可以使用 `Sync Prompts`,来一键同步所有,如果你不想让某些提示出现在你的斜杠命令,你可以禁用它们。
|
||||
|
||||

|
||||

|
||||
|
||||
<!-- 数据导入完成后,可以重新启动应用来使配置生效(`Menu -> Preferences -> Restart ChatGPT`)。 -->
|
||||
|
||||
在 ChatGPT 文本输入区域,键入 `/` 开头的字符,则会弹出指令提示,按下空格键,它会默认将命令关联的文本填充到输入区域(注意:如果包含多个指令提示,它只会选择第一个作为填充,你可以持续输入,直到第一个提示命令为你想要时,再按下空格键。或者使用鼠标来点击多条指令中的某一个)。填充完成后,你只需要按下回车键即可。斜杠命令下,使用 TAB 键修改 `{q}` 标签内容(仅支持单个修改 [#54](https://github.com/lencx/ChatGPT/issues/54))。使用键盘 `⇧` 和 `⇩`(上下键)来选择斜杠指令。
|
||||
|
||||

|
||||

|
||||
|
||||
## ✨ 功能概览
|
||||
|
||||
- 跨平台: `macOS` `Linux` `Windows`
|
||||
- 导出 ChatGPT 聊天记录 (支持 PNG, PDF 和生成分享链接)
|
||||
- 应用自动升级通知
|
||||
- 丰富的快捷键
|
||||
- 系统托盘悬浮窗
|
||||
- 应用菜单功能强大
|
||||
- 支持斜杠命令及其配置(可手动配置或从文件同步 [#55](https://github.com/lencx/ChatGPT/issues/55))
|
||||
- 自定义全局快捷键 ([#108](https://github.com/lencx/ChatGPT/issues/108))
|
||||
- 划词搜索 ([#122](https://github.com/lencx/ChatGPT/issues/122) 鼠标选中文本,不超过 400 个字符):应用使用 Tauri 构建,因其安全限制,会导致部分操作按钮无效,建议前往浏览器操作。
|
||||
|
||||
### #️⃣ 菜单项
|
||||
|
||||
- **Preferences (喜好)**
|
||||
- `Theme` - `Light`, `Dark`, `System` (仅支持 macOS 和 Windows)
|
||||
- `Stay On Top`: 窗口置顶
|
||||
- `Titlebar`: 是否显示 `Titlebar`,仅 macOS 支持
|
||||
- `Hide Dock Icon` ([#35](https://github.com/lencx/ChatGPT/issues/35)): 隐藏 Dock 中的应用图标 (仅 macOS 支持)
|
||||
- 系统图盘右键单击打开菜单,然后在菜单项中点击 `Show Dock Icon` 可以重新将应用图标显示在 Dock(`SystemTrayMenu -> Show Dock Icon`)
|
||||
- `Control Center`: ChatGPT 应用的控制中心,它将为应用提供无限的可能
|
||||
- 设置 `Theme`,`Stay On Top`,`Titlebar` 等
|
||||
- `User Agent` ([#17](https://github.com/lencx/ChatGPT/issues/17)): 自定义 `user agent` 防止网站安全检测,默认值为空
|
||||
- `Go to Config`: 打开 ChatGPT 配置目录 (`path: ~/.chatgpt/*`)
|
||||
- `Clear Config`: 清除 ChatGPT 配置数据 (`path: ~/.chatgpt/*`), 这是危险操作,请提前备份数据
|
||||
- `Restart ChatGPT`: 重启应用。如果注入脚本编辑完成,或者应用可卡死可以通过此菜单重新启动应用
|
||||
- **Edit** - `Undo`, `Redo`, `Cut`, `Copy`, `SelectAll`, ...
|
||||
- **View** - `Go Back`, `Go Forward`, `Scroll to Top of Screen`, `Scroll to Bottom of Screen`, `Refresh the Screen`, ...
|
||||
- **Help**
|
||||
- `Update Log`: ChatGPT 应用更新日志
|
||||
- `Report Bug`: 报告 BUG 或反馈建议
|
||||
- `Toggle Developer Tools`: 网站调试工具,调试页面或脚本可能需要
|
||||
|
||||
## ⚙️ 应用配置
|
||||
|
||||
| 平台 | 路径 |
|
||||
| ------- | ------------------------- |
|
||||
| Linux | `/home/lencx/.chatgpt` |
|
||||
| macOS | `/Users/lencx/.chatgpt` |
|
||||
| Windows | `C:\Users\lencx\.chatgpt` |
|
||||
|
||||
- `[.chatgpt]` - 应用配置根路径
|
||||
- `chat.conf.json` - 应用喜好配置
|
||||
<!-- - `chat.awesome.json` - 自定义 URL 列表,类似于浏览器书签。可以将任意 URL 作为主窗口或托盘窗口 (**Control Conter -> Awesome**) -->
|
||||
- `chat.prompt.json` - ChatGPT 输入提示,通过斜杠命令来快速完成输入,主要包含三部分:
|
||||
- `user_custom` - 需要手动录入 (**Control Conter -> Prompts -> User Custom**)
|
||||
- `sync_prompts` - 从 [f/awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts) 同步数据 (**Control Conter -> Prompts -> Sync Prompts**)
|
||||
- `sync_custom` - 同步自定义的 json 或 csv 文件数据,支持本地和远程 (**Control Conter -> Prompts -> Sync Custom**)
|
||||
- `chat.prompt.cmd.json` - 过滤(是否启用)和排序处理后的斜杠命令数据
|
||||
- `[cache_prompts]` - 缓存同步或录入的数据
|
||||
- `chatgpt_prompts.json` - 缓存 `sync_prompts` 数据
|
||||
- `user_custom.json` - 缓存 `user_custom` 数据
|
||||
- `ae6cf32a6f8541b499d6bfe549dbfca3.json` - 随机生成的文件名,缓存 `sync_custom` 数据
|
||||
- `4f695d3cfbf8491e9b1f3fab6d85715c.json` - 随机生成的文件名,缓存 `sync_custom` 数据
|
||||
- `bd1b96f15a1644f7bd647cc53073ff8f.json` - 随机生成的文件名,缓存 `sync_custom` 数据
|
||||
|
||||
### 客户端信息同步
|
||||
|
||||
目前同步自定文件仅支持 json 和 csv,且需要满足以下格式,否则会导致应用异常:
|
||||
|
||||
`JSON 格式`
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"cmd": "a",
|
||||
"act": "aa",
|
||||
"prompt": "aaa aaa aaa"
|
||||
},
|
||||
{
|
||||
"cmd": "b",
|
||||
"act": "bb",
|
||||
"prompt": "bbb bbb bbb"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
`CSV 格式`
|
||||
|
||||
```csv
|
||||
"cmd","act","prompt"
|
||||
"a","aa","aaa aaa aaa"
|
||||
"b","bb","bbb bbb bbb"
|
||||
```
|
||||
|
||||
## 👀 预览
|
||||
|
||||
| 预览 | 预览 |
|
||||
| ---------------------------------------------- | -------------------------------------------------------------- |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
## ❓ 常见问题
|
||||
|
||||
### 不能打开 ChatGPT
|
||||
|
||||
如果升级应用后无法打开,请尝试清除配置,它位于此目录 `~/.chatgpt/*`。
|
||||
|
||||
### 主窗口已经登录,但是系统托盘窗口显示未登录
|
||||
|
||||
可通过菜单项里的 `Restart ChatGPT` 重启应用来修复这个问题(`Menu -> Preferences -> Restart ChatGPT`)。
|
||||
|
||||
### 它是否安全?
|
||||
|
||||
它是安全的,仅仅只是对 [OpenAI ChatGPT](https://chat.openai.com) 网站的包装,注入了一些额外功能(均在本地,未发起网络请求),如果存疑,可以检查源代码。
|
||||
|
||||
### 开发者未验证?
|
||||
|
||||
Mac 上无法安装,提示开发者未验证,具体可以查看下面给出的解决方案(它是开源的,很安全)。
|
||||
|
||||
- [Open a Mac app from an unidentified developer](https://support.apple.com/en-sg/guide/mac-help/mh40616/mac)
|
||||
|
||||
---
|
||||
|
||||
### 我想自己构建它?
|
||||
|
||||
#### 预安装
|
||||
|
||||
- [Rust (必须)](https://www.rust-lang.org/)
|
||||
- [Node.js (必须)](https://nodejs.org/)
|
||||
- [VS Code (可选)](https://code.visualstudio.com/)
|
||||
- [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)
|
||||
- [tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode)
|
||||
|
||||
#### 开始
|
||||
|
||||
```bash
|
||||
# step1: 克隆仓库
|
||||
git clone https://github.com/lencx/ChatGPT.git
|
||||
|
||||
# step2: 进入目录
|
||||
cd ChatGPT
|
||||
|
||||
# step3: 安装依赖
|
||||
yarn
|
||||
|
||||
# step4: 开发启动
|
||||
yarn dev
|
||||
|
||||
# step5: 构建应用
|
||||
# 构建后的安装包位置: src-tauri/target/release/bundle
|
||||
yarn build
|
||||
```
|
||||
|
||||
- [The distDir configuration is set to "../dist" but this path doesn't exist](https://github.com/lencx/ChatGPT/discussions/180)
|
||||
- [Error A public key has been found, but no private key. Make sure to set TAURI_PRIVATE_KEY environment variable.](https://github.com/lencx/ChatGPT/discussions/182)
|
||||
|
||||
## ❤️ 感谢
|
||||
|
||||
- 分享按钮的代码从 [@liady](https://github.com/liady) 的插件获得,并做了一些本地化修改
|
||||
- 感谢 [Awesome ChatGPT Prompts](https://github.com/f/awesome-chatgpt-prompts) 项目为这个应用自定义指令功能所带来的启发
|
||||
|
||||
---
|
||||
|
||||
[](https://star-history.com/#lencx/chatgpt&Timeline)
|
||||
|
||||
## 中国用户
|
||||
|
||||
国内用户如果遇到使用问题或者想交流 ChatGPT 技巧,可以关注公众号“浮之静”,发送 “chat” 进群参与讨论。公众号会更新[《Tauri 系列》](https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzIzNjE2NTI3NQ==&action=getalbum&album_id=2593843659863752704)文章,技术思考等等,如果对 tauri 开发应用感兴趣可以关注公众号后回复 “tauri” 进技术开发群(想私聊的也可以关注公众号,来添加微信)。开源不易,如果这个项目对你有帮助可以分享给更多人,或者微信扫码打赏。
|
||||
|
||||
<img width="180" src="https://user-images.githubusercontent.com/16164244/207228300-ea5c4688-c916-4c55-a8c3-7f862888f351.png"> <img width="200" src="https://user-images.githubusercontent.com/16164244/207228025-117b5f77-c5d2-48c2-a070-774b7a1596f2.png">
|
||||
|
||||
<a href="https://t.zsxq.com/0bQikmcVw"><img width="360" src="./assets/zsxq.png"></a>
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 License
|
||||
111
README.md
@ -1,11 +1,8 @@
|
||||
<p align="center">
|
||||
<img width="180" src="./public/logo.png" alt="ChatGPT">
|
||||
<h1 align="center">ChatGPT</h1>
|
||||
<img width="180" src="./public/ChatGPT.png" alt="ChatGPT">
|
||||
<p align="center">ChatGPT Desktop Application (Available on Mac, Windows, and Linux)</p>
|
||||
</p>
|
||||
|
||||
[](./README.md)
|
||||
[](./README-ZH_CN.md)\
|
||||
[](https://github.com/lencx/ChatGPT/releases)
|
||||
[](https://discord.gg/aPhCRf4zZr)
|
||||
[](https://twitter.com/lencx_)
|
||||
@ -15,107 +12,13 @@
|
||||
|
||||
---
|
||||
|
||||
> [!NOTE] > **If you want to experience a more powerful AI wrapper application, you can try the Noi (https://github.com/lencx/Noi), which is a successor to the ChatGPT desktop application concept.**
|
||||
> [!NOTE]
|
||||
> **If you want to experience a more powerful AI wrapper application, you can try the Noi (https://github.com/lencx/Noi), which is a successor to the ChatGPT desktop application concept.**
|
||||
|
||||
---
|
||||
Thank you very much for your interest in this project. OpenAI has now released the macOS version of the application, and a Windows version will be available later ([Introducing GPT-4o and more tools to ChatGPT free users](https://openai.com/index/gpt-4o-and-more-tools-to-chatgpt-free/)). If you prefer the official application, you can stay updated with the latest information from OpenAI.
|
||||
|
||||
This is an unofficial project solely intended for personal learning and research. Since the ChatGPT desktop application was open-sourced, it has garnered a lot of attention, and I want to thank everyone for their support. However, as the project progressed, two issues have arisen that greatly impact its future development:
|
||||
If you want to learn about or download the previous version (v1.1.0), please click [here](https://github.com/lencx/ChatGPT/tree/release-v1.1.0).
|
||||
|
||||
- Some individuals have repackaged and sold it for profit.
|
||||
- The name and icon of ChatGPT could potentially lead to infringement disputes.
|
||||
I am currently looking for some differentiating features to develop version 2.0. If you are interested in this, please stay tuned.
|
||||
|
||||
## Live Demo
|
||||
|
||||
- [ChatGPT Desktop Application v1.0.0](https://youtu.be/IIuuB5vFFAQ)
|
||||
- [ChatGPT automatically performs the "Continue generating" button, freeing up your hands.](https://youtu.be/bbL5cPmiGig)
|
||||
|
||||
## 📦 Install
|
||||
|
||||
- [📝 Update Log](./UPDATE_LOG.md)
|
||||
- [🕒 History versions...](https://github.com/lencx/ChatGPT/releases)
|
||||
|
||||
<!-- tr-download-start -->
|
||||
|
||||
### Windows
|
||||
|
||||
- [ChatGPT_1.1.0_windows_x86_64.msi](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_windows_x86_64.msi): Direct download installer
|
||||
- Use [winget](https://winstall.app/apps/lencx.ChatGPT):
|
||||
|
||||
```bash
|
||||
# install the latest version
|
||||
winget install --id=lencx.ChatGPT -e
|
||||
|
||||
# install the specified version
|
||||
winget install --id=lencx.ChatGPT -e --version 1.1.0
|
||||
```
|
||||
|
||||
**Note: If the installation path and application name are the same, it will lead to conflict ([#142](https://github.com/lencx/ChatGPT/issues/142))**
|
||||
|
||||
### Mac
|
||||
|
||||
- [ChatGPT_1.1.0_macos_aarch64.dmg](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_macos_aarch64.dmg): Direct download installer
|
||||
- [ChatGPT_1.1.0_macos_x86_64.dmg](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_macos_x86_64.dmg): Direct download installer
|
||||
- Homebrew \
|
||||
Or you can install with _[Homebrew](https://brew.sh) ([Cask](https://docs.brew.sh/Cask-Cookbook)):_
|
||||
```sh
|
||||
brew tap lencx/chatgpt https://github.com/lencx/ChatGPT.git
|
||||
brew install --cask chatgpt --no-quarantine
|
||||
```
|
||||
Also, if you keep a _[Brewfile](https://github.com/Homebrew/homebrew-bundle#usage)_, you can add something like this:
|
||||
```rb
|
||||
repo = "lencx/chatgpt"
|
||||
tap repo, "https://github.com/#{repo}.git"
|
||||
cask "chatgpt", args: { "no-quarantine": true }
|
||||
```
|
||||
|
||||
**If you encounter the error message `"ChatGPT" is damaged and can't be opened. You should move it to the Trash`. while installing software on macOS, it may be due to security settings restrictions in macOS. To solve this problem, please try the following command in Terminal:**
|
||||
|
||||
```bash
|
||||
sudo xattr -r -d com.apple.quarantine /YOUR_PATH/ChatGPT.app
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
- [ChatGPT_1.1.0_linux_x86_64.deb](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_linux_x86_64.deb): Download `.deb` installer, advantage small size, disadvantage poor compatibility
|
||||
- [ChatGPT_1.1.0_linux_x86_64.AppImage.tar.gz](https://github.com/lencx/ChatGPT/releases/download/v1.1.0/ChatGPT_1.1.0_linux_x86_64.AppImage.tar.gz): Works reliably, you can try it if `.deb` fails to run
|
||||
|
||||
<!-- tr-download-end -->
|
||||
|
||||
## ChatGPT Prompts!
|
||||
|
||||
You can look at **[awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts)** to find interesting features to import into the app. You can also use `Sync Prompts` to sync all in one click, and if you don't want certain prompts to appear in your slash commands, you can disable them.
|
||||
|
||||

|
||||
|
||||
## ✨ Features
|
||||
|
||||
- Multi-platform: `macOS` `Linux` `Windows`
|
||||
- Export ChatGPT history (PNG, PDF and Markdown)
|
||||
- Automatic application upgrade notification
|
||||
- Common shortcut keys
|
||||
- System tray hover window
|
||||
- Powerful menu items
|
||||
- Support for slash commands and their configuration (can be configured manually or synchronized from a file [#55](https://github.com/lencx/ChatGPT/issues/55))
|
||||
- Customize global shortcuts ([#108](https://github.com/lencx/ChatGPT/issues/108))
|
||||
- Pop-up Search ([#122](https://github.com/lencx/ChatGPT/issues/122) mouse selected content, no more than 400 characters): The application is built using Tauri, and due to its security restrictions, some of the action buttons will not work, so we recommend going to your browser.
|
||||
|
||||
## Thanks
|
||||
|
||||
- The core implementation of the share button code was copied from the [@liady](https://github.com/liady) extension with some modifications.
|
||||
- Thanks to the [Awesome ChatGPT Prompts](https://github.com/f/awesome-chatgpt-prompts) repository for inspiring the custom command function for this application.
|
||||
|
||||
---
|
||||
|
||||
[](https://star-history.com/#lencx/chatgpt&Timeline)
|
||||
|
||||
## 中国用户
|
||||
|
||||
国内用户如果遇到使用问题或者想交流 ChatGPT 技巧,可以关注公众号“浮之静”,发送 “chat” 进群参与讨论。公众号会更新[《Tauri 系列》](https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzIzNjE2NTI3NQ==&action=getalbum&album_id=2593843659863752704)文章,技术思考等等,如果对 tauri 开发应用感兴趣可以关注公众号后回复 “tauri” 进技术开发群(想私聊的也可以关注公众号,来添加微信)。开源不易,如果这个项目对你有帮助可以分享给更多人,或者微信扫码打赏。
|
||||
|
||||
<img width="180" src="https://user-images.githubusercontent.com/16164244/207228300-ea5c4688-c916-4c55-a8c3-7f862888f351.png"> <img width="200" src="https://user-images.githubusercontent.com/16164244/207228025-117b5f77-c5d2-48c2-a070-774b7a1596f2.png">
|
||||
|
||||
<a href="https://t.zsxq.com/0bQikmcVw"><img width="360" src="./assets/zsxq.png"></a>
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 License
|
||||

|
||||
304
UPDATE_LOG.md
@ -1,304 +0,0 @@
|
||||
# UPDATE LOG
|
||||
|
||||
**It is an unofficial project intended for personal learning and research purposes only. During the time that the ChatGPT desktop application was open-sourced, it received a lot of attention, and I would like to thank everyone for their support. However, as things have developed, there are two issues that seriously affect the project's next development plan:**
|
||||
|
||||
- **Some people have used it for repackaging and selling for profit.**
|
||||
- **The name and icon of ChatGPT may be involved in infringement issues.**
|
||||
|
||||
**New repository: https://github.com/lencx/nofwl**
|
||||
|
||||
## v1.1.0
|
||||
|
||||
Fix:
|
||||
|
||||
- Fixed the issue where the cmd slash command does not work in some cases.
|
||||
- Moved the export button to the sidebar to prevent layout conflicts.
|
||||
|
||||
## v1.0.0
|
||||
|
||||
Note: This version modifies some configuration files. It is recommended to backup the `~/.chatgpt` folder in advance to avoid loss of important configurations.
|
||||
|
||||
Feat:
|
||||
|
||||
- The synchronization method for prompts has been optimized, now supporting local file uploads
|
||||
- Scripts have been externalized, allowing for editing and synchronization
|
||||
- Removed the `Awesome` menu from `Control Center`
|
||||
|
||||
Fix:
|
||||
|
||||
- Chat history export is blank
|
||||
- Change the export files location to the `Download` directory
|
||||
|
||||
## v0.12.0
|
||||
|
||||
Feat:
|
||||
|
||||
- Add refresh button
|
||||
- Add text-to-speech (`Control Center -> Settings -> General -> Set Speech Language`) (https://github.com/lencx/ChatGPT/issues/534)
|
||||
- Automatically focus input field (https://github.com/lencx/ChatGPT/issues/550)
|
||||
|
||||
## v0.11.1
|
||||
|
||||
Fix:
|
||||
|
||||
- Export button blinks (https://github.com/lencx/ChatGPT/issues/541)
|
||||
- System tray supports sending with Enter key, for text line breaks please use the shortcut key `Shift + Enter` (https://github.com/lencx/ChatGPT/issues/533)
|
||||
|
||||
## v0.11.0
|
||||
|
||||
Fix:
|
||||
|
||||
- User-defined close button behavior (exit or minimize) (`Control Center -> Settings -> Main Window -> Close Exit`). (https://github.com/lencx/ChatGPT/issues/359)
|
||||
- Markdown content layout (https://github.com/lencx/ChatGPT/issues/378)
|
||||
|
||||
Feat:
|
||||
|
||||
- Set the main window and tray window size (https://github.com/lencx/ChatGPT/issues/405)
|
||||
- Save window positions and sizes and restore them when the app is reopened (`Control Center -> Settings -> General -> Save Window State`)
|
||||
- macOS support for aarch64 installer (https://github.com/lencx/ChatGPT/issues/380)
|
||||
|
||||
## v0.10.3
|
||||
|
||||
> Note: As of now the ChatGPT desktop app has added a lot of exciting features and it continues to improve, as the app grows it has gone far beyond what ChatGPT was intended for. I want to make it the ultimate goal that any website can be easily wrapped to the desktop through user customization. So it needed an international user guide to guide users to use it more professionally. And https://app.nofwl.com is the manual for the app, which will be built into the app (`Menu -> Window -> ChatGPT User's Guide`) so you can access it anytime. It's just starting at the moment, so stay tuned.
|
||||
|
||||
Fix:
|
||||
|
||||
- Incompatible configuration data causes program crashes (https://github.com/lencx/ChatGPT/issues/295)
|
||||
|
||||
Feat:
|
||||
|
||||
- Silent copy text
|
||||
- Markdown export support distinguishes between users and bots (https://github.com/lencx/ChatGPT/issues/233)
|
||||
|
||||
## v0.10.2
|
||||
|
||||
Fix:
|
||||
|
||||
- PNG and PDF buttons do not work (https://github.com/lencx/ChatGPT/issues/274)
|
||||
- Change the window size and the Send button is obscured by the Export button (https://github.com/lencx/ChatGPT/issues/286)
|
||||
- Change forward and backward shortcuts (https://github.com/lencx/ChatGPT/issues/254)
|
||||
- MacOS: `Cmd [`, `Cmd ]`
|
||||
- Windows and Linux: `Ctrl [`, `Ctrl ]`
|
||||
|
||||
Feat:
|
||||
|
||||
- Copy a single record to the clipboard (https://github.com/lencx/ChatGPT/issues/191)
|
||||
|
||||
## v0.10.1
|
||||
|
||||
Fix:
|
||||
|
||||
- Program exception when `Awesome` data is empty (https://github.com/lencx/ChatGPT/issues/248)
|
||||
|
||||
Feat:
|
||||
|
||||
- New shortcut key to change zoom level (30% - 200%), `+` or `-` 10% each time, `0` will be reset to 100% (https://github.com/lencx/ChatGPT/issues/202)
|
||||
- Windows: `Ctrl +`, `Ctrl -`, `Ctrl 0`
|
||||
- MacOS: `Cmd +`, `Cmd -`, `Cmd 0`
|
||||
|
||||
## v0.10.0
|
||||
|
||||
Fix:
|
||||
|
||||
- After exporting a file in Windows, open an empty file explorer (https://github.com/lencx/ChatGPT/issues/242)
|
||||
|
||||
Feat:
|
||||
|
||||
- Markdown files support editing and live preview
|
||||
- Add `Awesome` menu to the `Control Center` (similar to bookmarks, but it's just a start, more possibilities in the future), custom URL support for the home and tray windows (if you're tired of ChatGPT as your home screen).
|
||||
|
||||
## v0.9.2
|
||||
|
||||
Fix: Slash command does not work
|
||||
|
||||
## v0.9.1
|
||||
|
||||
Fix: Slash command does not work
|
||||
|
||||
## v0.9.0
|
||||
|
||||
Fix:
|
||||
|
||||
- Export button does not work
|
||||
|
||||
Feat:
|
||||
|
||||
- Add an export markdown button
|
||||
- `Control Center` adds `Notes` and `Download` menus for managing exported chat files (Markdown, PNG, PDF). `Notes` supports markdown previews.
|
||||
|
||||
## v0.8.1
|
||||
|
||||
Fix:
|
||||
|
||||
- Export button keeps blinking
|
||||
- Export button in the old chat does not work
|
||||
- Disable export sharing links because it is a security risk
|
||||
|
||||
## v0.8.0
|
||||
|
||||
Feat:
|
||||
|
||||
- Theme enhancement (Light, Dark, System)
|
||||
- Automatic updates support `silent` settings
|
||||
- Pop-up search: select the ChatGPT content with the mouse, the `DALL·E 2` button appears, and click to jump (note: because the search content filled by the script cannot trigger the event directly, you need to enter a space in the input box to make the button clickable).
|
||||
|
||||
Fix:
|
||||
|
||||
- Close the main window and hide it in the tray (windows systems)
|
||||
|
||||
## v0.7.4
|
||||
|
||||
Fix:
|
||||
|
||||
- Trying to resolve linux errors: `error while loading shared libraries`
|
||||
- Customize global shortcuts (`Menu -> Preferences -> Control Center -> General -> Global Shortcut`)
|
||||
|
||||
## v0.7.3
|
||||
|
||||
Chore:
|
||||
|
||||
- Optimize slash command style
|
||||
- Optimize tray menu icon and button icons
|
||||
- Global shortcuts to the chatgpt app (mac: `Command + Shift + O`, windows: `Ctrl + Shift + O`)
|
||||
|
||||
## v0.7.2
|
||||
|
||||
Fix: Some windows systems cannot start the application
|
||||
|
||||
## v0.7.1
|
||||
|
||||
Fix:
|
||||
|
||||
- Some windows systems cannot start the application
|
||||
- Windows and linux add about menu (show version information)
|
||||
- The tray icon is indistinguishable from the background in dark mode on window and linux
|
||||
|
||||
## v0.7.0
|
||||
|
||||
Fix:
|
||||
|
||||
- Mac m1 copy/paste does not work on some system versions
|
||||
- Optimize the save chat log button to a small icon, the tray window no longer provides a save chat log button (the buttons causes the input area to become larger and the content area to become smaller)
|
||||
|
||||
Feat:
|
||||
|
||||
- Use the keyboard `⇧` (arrow up) and `⇩` (arrow down) keys to select the slash command
|
||||
<!-- - global shortcuts to the chatgpt app (mac: command+shift+o, windows: ctrl+shift+o) -->
|
||||
|
||||
## v0.6.10
|
||||
|
||||
Fix: Sync failure on windows
|
||||
|
||||
## v0.6.4
|
||||
|
||||
Fix: Path not allowed on the configured scope
|
||||
|
||||
Feat:
|
||||
|
||||
- Optimize the generated pdf file size
|
||||
- Menu added `Sync Prompts`
|
||||
- `Control Center` added `Sync Custom`
|
||||
- The slash command is triggered by the enter key
|
||||
- Under the slash command, use the tab key to modify the contents of the `{q}` tag (only single changes are supported (https://github.com/lencx/ChatGPT/issues/54)
|
||||
|
||||
## v0.6.0
|
||||
|
||||
Fix:
|
||||
|
||||
- Windows show Chinese when upgrading
|
||||
|
||||
## v0.5.1
|
||||
|
||||
Some optimization
|
||||
|
||||
## v0.5.0
|
||||
|
||||
Feat: `Control Center` added `chatgpt-prompts` synchronization
|
||||
|
||||
## v0.4.2
|
||||
|
||||
Add chatgpt log (path: `~/.chatgpt/chatgpt.log`)
|
||||
|
||||
## v0.4.1
|
||||
|
||||
Fix:
|
||||
|
||||
- Tray window style optimization
|
||||
|
||||
## v0.4.0
|
||||
|
||||
Feat:
|
||||
|
||||
- Customize the ChatGPT prompts command (https://github.com/lencx/ChatGPT#-announcement)
|
||||
- Menu enhancement: hide application icons from the Dock (support macOS only)
|
||||
|
||||
## v0.3.0
|
||||
|
||||
Fix: Can't open ChatGPT
|
||||
|
||||
Feat: Menu enhancement
|
||||
|
||||
- The control center of ChatGPT application
|
||||
- Open the configuration file directory
|
||||
|
||||
## v0.2.2
|
||||
|
||||
Feat:
|
||||
|
||||
- Menu: go to config
|
||||
|
||||
## v0.2.1
|
||||
|
||||
Feat: Menu optimization
|
||||
|
||||
## v0.2.0
|
||||
|
||||
Feat: Menu enhancement
|
||||
|
||||
- Customize user-agent to prevent security detection interception
|
||||
- Clear all chatgpt configuration files
|
||||
|
||||
## v0.1.8
|
||||
|
||||
Feat:
|
||||
|
||||
- Menu enhancement: theme, titlebar
|
||||
- Modify website address
|
||||
|
||||
## v0.1.7
|
||||
|
||||
Feat: Tray window
|
||||
|
||||
## v0.1.6
|
||||
|
||||
Feat:
|
||||
|
||||
- Stay on top
|
||||
- Export ChatGPT history
|
||||
|
||||
## v0.1.5
|
||||
|
||||
Fix: Mac can't use shortcut keys
|
||||
|
||||
## v0.1.4
|
||||
|
||||
Feat:
|
||||
|
||||
- Beautify icons
|
||||
- Add system tray menu
|
||||
|
||||
## v0.1.3
|
||||
|
||||
Fix: Only mac supports `TitleBarStyle`
|
||||
|
||||
## v0.1.2
|
||||
|
||||
Initialization
|
||||
|
||||
## v0.1.1
|
||||
|
||||
Initialization
|
||||
|
||||
## v0.1.0
|
||||
|
||||
Initialization
|
||||
|
Before Width: | Height: | Size: 773 KiB |
|
Before Width: | Height: | Size: 5.0 MiB |
|
Before Width: | Height: | Size: 774 KiB |
|
Before Width: | Height: | Size: 426 KiB |
|
Before Width: | Height: | Size: 808 KiB |
|
Before Width: | Height: | Size: 241 KiB |
|
Before Width: | Height: | Size: 580 KiB |
|
Before Width: | Height: | Size: 406 KiB |
|
Before Width: | Height: | Size: 9.3 MiB |
|
Before Width: | Height: | Size: 192 KiB |
BIN
assets/zsxq.png
|
Before Width: | Height: | Size: 30 KiB |
@ -1,28 +0,0 @@
|
||||
cask "chatgpt" do
|
||||
version "1.0.0"
|
||||
arch = Hardware::CPU.arch.to_s
|
||||
sha256s = {
|
||||
"x86_64" => "474c6024ac1100512c242449da8d93b521334d0d03a9457c42446293a64eaff4",
|
||||
"aarch64" => "998d15813194957de140a530605252fdf3f68fafdba1353706fa00d070c7c23d"
|
||||
}
|
||||
if arch == "arm64" then arch = "aarch64" end
|
||||
url "https://github.com/lencx/ChatGPT/releases/download/v#{version}/ChatGPT_#{version}_macos_#{arch}.dmg"
|
||||
sha256 sha256s[arch]
|
||||
|
||||
name "ChatGPT"
|
||||
desc "Desktop wrapper for OpenAI ChatGPT"
|
||||
homepage "https://github.com/lencx/ChatGPT#readme"
|
||||
|
||||
app "ChatGPT.app"
|
||||
|
||||
uninstall quit: "com.lencx.chatgpt"
|
||||
|
||||
zap trash: [
|
||||
"~/.chatgpt",
|
||||
"~/Library/Caches/com.lencx.chatgpt",
|
||||
"~/Library/HTTPStorages/com.lencx.chatgpt.binarycookies",
|
||||
"~/Library/Preferences/com.lencx.chatgpt.plist",
|
||||
"~/Library/Saved Application State/com.lencx.chatgpt.savedState",
|
||||
"~/Library/WebKit/com.lencx.chatgpt",
|
||||
]
|
||||
end
|
||||
BIN
docs/static/chatgpt-v2.gif
vendored
Normal file
|
After Width: | Height: | Size: 377 KiB |
@ -1,11 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>ChatGPT</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
|
||||
98
package.json
@ -1,81 +1,37 @@
|
||||
{
|
||||
"name": "chatgpt",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"version": "2.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev:fe": "vite",
|
||||
"build:fe": "tsc && vite build",
|
||||
"dev": "tauri dev",
|
||||
"build": "tauri build",
|
||||
"updater": "tr updater",
|
||||
"release": "tr release --git",
|
||||
"fix:conf": "tr override --json.tauri_updater_active=false",
|
||||
"fix:tray": "tr override --json.tauri_systemTray_iconPath=\"icons/tray-icon-light.png\" --json.tauri_systemTray_iconAsTemplate=false",
|
||||
"fix:tray:mac": "tr override --json.tauri_systemTray_iconPath=\"icons/tray-icon.png\" --json.tauri_systemTray_iconAsTemplate=true",
|
||||
"download": "tr download --mdfile=README.md,README-ZH_CN.md --f1=43 --f2=43",
|
||||
"fmt:rs": "cargo fmt",
|
||||
"tr": "tr",
|
||||
"tauri": "tauri",
|
||||
"prettier": "prettier -c --write '**/*.{js,md,ts,tsx,yml}'",
|
||||
"pretty-quick": "pretty-quick --staged",
|
||||
"prepare": "husky install"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "lencx <cxin1314@gmail.com>",
|
||||
"keywords": [
|
||||
"chatgpt",
|
||||
"app",
|
||||
"desktop",
|
||||
"tauri",
|
||||
"macos",
|
||||
"linux",
|
||||
"windows"
|
||||
],
|
||||
"homepage": "https://github.com/lencx/ChatGPT",
|
||||
"bugs": "https://github.com/lencx/ChatGPT/issues",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/lencx/ChatGPT"
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^4.8.0",
|
||||
"@monaco-editor/react": "^4.4.6",
|
||||
"@tauri-apps/api": "^1.5.1",
|
||||
"antd": "^5.11.0",
|
||||
"clsx": "^1.2.1",
|
||||
"dayjs": "^1.11.7",
|
||||
"github-markdown-css": "^5.1.0",
|
||||
"@tauri-apps/api": "2.0.0-beta.11",
|
||||
"@tauri-apps/plugin-os": "2.0.0-beta.3",
|
||||
"@tauri-apps/plugin-shell": "2.0.0-beta.3",
|
||||
"clsx": "^2.1.1",
|
||||
"lodash": "^4.17.21",
|
||||
"monaco-editor": "^0.34.1",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-markdown": "^8.0.4",
|
||||
"react-resizable-panels": "^0.0.33",
|
||||
"react-router-dom": "^6.4.5",
|
||||
"react-syntax-highlighter": "^15.5.0",
|
||||
"rehype-raw": "^6.1.1",
|
||||
"remark-comment-config": "^7.0.1",
|
||||
"remark-gfm": "^3.0.1",
|
||||
"uuid": "^9.0.0"
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.23.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^1.5.6",
|
||||
"@tauri-release/cli": "^0.2.5",
|
||||
"@types/lodash": "^4.14.191",
|
||||
"@types/node": "^18.7.10",
|
||||
"@types/react": "^18.0.15",
|
||||
"@types/react-dom": "^18.0.6",
|
||||
"@types/react-syntax-highlighter": "^15.5.6",
|
||||
"@types/uuid": "^9.0.0",
|
||||
"@vitejs/plugin-react": "^3.0.0",
|
||||
"husky": "^8.0.3",
|
||||
"prettier": "^2.8.3",
|
||||
"pretty-quick": "^3.1.3",
|
||||
"sass": "^1.56.2",
|
||||
"typescript": "^4.9.4",
|
||||
"vite": "^4.0.0",
|
||||
"vite-tsconfig-paths": "^4.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^14.18.0 || ^16.0.0 || ^18.0.0"
|
||||
"@tailwindcss/typography": "^0.5.13",
|
||||
"@tauri-apps/cli": "2.0.0-beta.15",
|
||||
"@types/lodash": "^4.17.1",
|
||||
"@types/node": "^20.12.12",
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
"autoprefixer": "^10.4.19",
|
||||
"postcss": "^8.4.38",
|
||||
"tailwindcss": "^3.4.3",
|
||||
"typescript": "^5.4.5",
|
||||
"vite": "^5.2.11",
|
||||
"vite-tsconfig-paths": "^4.3.2"
|
||||
}
|
||||
}
|
||||
|
||||
6376
pnpm-lock.yaml
6
postcss.config.js
Normal file
@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
BIN
public/ChatGPT.png
Normal file
|
After Width: | Height: | Size: 44 KiB |
BIN
public/bmc.png
|
Before Width: | Height: | Size: 4.6 KiB |
BIN
public/logo.png
|
Before Width: | Height: | Size: 22 KiB |
BIN
public/wxp.png
|
Before Width: | Height: | Size: 248 KiB |
@ -1,6 +1,6 @@
|
||||
max_width = 100
|
||||
hard_tabs = false
|
||||
tab_spaces = 2
|
||||
tab_spaces = 4
|
||||
newline_style = "Auto"
|
||||
use_small_heuristics = "Default"
|
||||
reorder_imports = true
|
||||
|
||||
@ -1,5 +0,0 @@
|
||||
# ChatGPT Scripts
|
||||
|
||||
> ChatGPT Desktop Application Core Extension Scripts.
|
||||
|
||||
[ChatGPT/scripts](https://github.com/lencx/ChatGPT/tree/main/scripts)
|
||||
@ -1,70 +0,0 @@
|
||||
/**
|
||||
* @name chat.js
|
||||
* @version 0.1.4
|
||||
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/chat.js
|
||||
*/
|
||||
|
||||
function chatInit() {
|
||||
const ICONS = {
|
||||
copy: `<svg class="chatappico copy" stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path><rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect></svg>`,
|
||||
cpok: `<svg class="chatappico cpok" viewBox="0 0 24 24"><g fill="none" stroke="#10a37f" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><rect width="8" height="4" x="8" y="2" rx="1" ry="1"/><path d="M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2M16 4h2a2 2 0 0 1 2 2v4m1 4H11"/><path d="m15 10l-4 4l4 4"/></g></svg>`,
|
||||
};
|
||||
|
||||
let currentUtterance = null;
|
||||
let currentIndex = -1;
|
||||
let chatConf = {};
|
||||
|
||||
async function init() {
|
||||
chatConf = (await invoke('get_app_conf')) || {};
|
||||
|
||||
new MutationObserver(observeMutations).observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
|
||||
document.addEventListener('visibilitychange', focusOnInput);
|
||||
// autoContinue();
|
||||
}
|
||||
|
||||
function observeMutations(mutationsList) {
|
||||
for (const mutation of mutationsList) {
|
||||
if (mutation.target.closest('form')) {
|
||||
addChatButtons();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function focusOnInput() {
|
||||
const textArea = document.getElementsByTagName('textarea')[0];
|
||||
if (textArea) {
|
||||
textArea.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function addChatButtons() {
|
||||
const list = Array.from(document.querySelectorAll('main >div>div>div>div>div'));
|
||||
|
||||
list.forEach((item, idx) => {
|
||||
if (shouldSkip(item)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const saybtn = item.querySelector('button.rounded-md').cloneNode(true);
|
||||
saybtn.classList.add('chat-item-voice');
|
||||
saybtn.title = 'Say';
|
||||
saybtn.innerHTML = ICONS.voice;
|
||||
|
||||
item.querySelector('.self-end').appendChild(saybtn);
|
||||
|
||||
saybtn.onclick = () => handleClick(item, idx, saybtn);
|
||||
});
|
||||
}
|
||||
|
||||
function shouldSkip(item) {
|
||||
return !item.querySelector('button.rounded-md') || !item.querySelector('.self-end');
|
||||
}
|
||||
|
||||
init();
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', chatInit);
|
||||
365
scripts/cmd.js
@ -1,365 +0,0 @@
|
||||
/**
|
||||
* @name cmd.js
|
||||
* @version 0.1.2
|
||||
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/cmd.js
|
||||
*/
|
||||
|
||||
function cmdInit() {
|
||||
const styleDom = document.createElement('style');
|
||||
styleDom.innerHTML = `form {
|
||||
position: relative;
|
||||
}
|
||||
.chat-prompt-cmd-list {
|
||||
position: absolute;
|
||||
bottom: 60px;
|
||||
max-height: 100px;
|
||||
overflow: auto;
|
||||
z-index: 9999;
|
||||
}
|
||||
.chat-prompt-cmd-list>div {
|
||||
border: solid 2px rgba(80,80,80,.3);
|
||||
border-radius: 5px;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
html.dark .chat-prompt-cmd-list>div {
|
||||
background-color: #4a4a4a;
|
||||
}
|
||||
html.dark .chat-prompt-cmd-list .cmd-item {
|
||||
border-color: #666;
|
||||
}
|
||||
html.dark .chat-prompt-cmd-list .cmd-item b {
|
||||
color: #e8e8e8;
|
||||
}
|
||||
html.dark .chat-prompt-cmd-list .cmd-item i {
|
||||
color: #999;
|
||||
}
|
||||
html.dark .chat-prompt-cmd-list .cmd-item.selected {
|
||||
background: rgba(59,130,246,.5);
|
||||
}
|
||||
|
||||
.chat-prompt-cmd-list .cmd-item {
|
||||
font-size: 12px;
|
||||
border-bottom: solid 1px rgba(80,80,80,.2);
|
||||
padding: 2px 4px;
|
||||
display: flex;
|
||||
user-select: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chat-prompt-cmd-list .cmd-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.chat-prompt-cmd-list .cmd-item.selected {
|
||||
background: rgba(59,130,246,.3);
|
||||
}
|
||||
.chat-prompt-cmd-list .cmd-item b {
|
||||
display: inline-block;
|
||||
width: 100px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
border-radius: 4px;
|
||||
margin-right: 10px;
|
||||
color: #2a2a2a;
|
||||
}
|
||||
.chat-prompt-cmd-list .cmd-item i {
|
||||
width: 100%;
|
||||
max-width: 200px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
text-align: right;
|
||||
color: #888;
|
||||
}
|
||||
.chatappico {
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
}
|
||||
.chatappico.png {
|
||||
width: 0.8rem;
|
||||
height: 0.9rem;
|
||||
}
|
||||
#download-markdown-button,
|
||||
#download-png-button,
|
||||
#download-pdf-button,
|
||||
#refresh-page-button {
|
||||
border: none;
|
||||
}
|
||||
@media screen and (max-width: 767px) {
|
||||
#download-png-button, #download-pdf-button, #download-html-button {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
`;
|
||||
document.head.append(styleDom);
|
||||
|
||||
if (window.formInterval) {
|
||||
clearInterval(window.formInterval);
|
||||
}
|
||||
window.formInterval = setInterval(() => {
|
||||
const form = document.querySelector('form textarea');
|
||||
if (!form) return;
|
||||
clearInterval(window.formInterval);
|
||||
cmdTip();
|
||||
new MutationObserver(function (mutationsList) {
|
||||
for (const mutation of mutationsList) {
|
||||
if (mutation.target.getAttribute('id') === '__next') {
|
||||
initDom();
|
||||
cmdTip();
|
||||
}
|
||||
if (mutation.target.getAttribute('class') === 'chat-prompt-cmd-list') {
|
||||
// The `chatgpt prompt` fill can be done by clicking on the event.
|
||||
const searchDom = document.querySelector('form .chat-prompt-cmd-list>div');
|
||||
const searchInput = document.querySelector('form textarea');
|
||||
if (!searchDom) return;
|
||||
searchDom.addEventListener('click', (event) => {
|
||||
const item = event.target.closest('div');
|
||||
if (item) {
|
||||
const val = decodeURIComponent(item.getAttribute('data-prompt'));
|
||||
searchInput.value = val;
|
||||
document.querySelector('form textarea').focus();
|
||||
initDom();
|
||||
}
|
||||
});
|
||||
}
|
||||
if (mutation.type === 'childList' && mutation.removedNodes.length) {
|
||||
for (let node of mutation.removedNodes) {
|
||||
if (node.querySelector('form textarea')) {
|
||||
initDom();
|
||||
cmdTip();
|
||||
(async function () {
|
||||
async function platform() {
|
||||
return invoke('platform', {
|
||||
__tauriModule: 'Os',
|
||||
message: { cmd: 'platform' },
|
||||
});
|
||||
}
|
||||
if (__TAURI_METADATA__.__currentWindow.label !== 'tray') {
|
||||
const _platform = await platform();
|
||||
const chatConf = (await invoke('get_app_conf')) || {};
|
||||
if (/darwin/.test(_platform) && !chatConf.titlebar) {
|
||||
const nav = document.body.querySelector('nav');
|
||||
if (nav) {
|
||||
nav.style.paddingTop = '25px';
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}).observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
}, 300);
|
||||
|
||||
async function cmdTip() {
|
||||
initDom();
|
||||
const chatPromptJson = (await invoke('get_chat_prompt_cmd')) || {};
|
||||
const data = chatPromptJson.data;
|
||||
if (data.length <= 0) return;
|
||||
|
||||
let promptDom = document.querySelector('.chat-prompt-cmd-list');
|
||||
if (!promptDom) {
|
||||
const dom = document.createElement('div');
|
||||
dom.classList.add('chat-prompt-cmd-list');
|
||||
document.querySelector('form').appendChild(dom);
|
||||
promptDom = document.querySelector('.chat-prompt-cmd-list');
|
||||
|
||||
// fix: tray window
|
||||
if (__TAURI_METADATA__.__currentWindow.label === 'tray') {
|
||||
promptDom.style.bottom = '54px';
|
||||
}
|
||||
|
||||
const convertToSafeHtml = (v) => {
|
||||
return JSON.stringify(v, null, 2)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
};
|
||||
|
||||
const itemDom = (v) =>
|
||||
`<div class="cmd-item" title="${convertToSafeHtml(v.prompt)}" data-cmd="${
|
||||
v.cmd
|
||||
}" data-prompt="${encodeURIComponent(v.prompt)}"><b title="${v.cmd}">/${v.cmd}</b><i>${
|
||||
v.act
|
||||
}</i></div>`;
|
||||
const renderList = (v) => {
|
||||
initDom();
|
||||
promptDom.innerHTML = `<div>${v.map(itemDom).join('')}</div>`;
|
||||
window.__CHAT_CMD_PROMPT__ = v[0]?.prompt.trim();
|
||||
window.__CHAT_CMD__ = v[0]?.cmd.trim();
|
||||
window.__cmd_list = promptDom.querySelectorAll('.cmd-item');
|
||||
window.__cmd_index = 0;
|
||||
window.__cmd_list[window.__cmd_index].classList.add('selected');
|
||||
};
|
||||
const setPrompt = (v = '') => {
|
||||
if (v.trim()) {
|
||||
window.__CHAT_CMD_PROMPT__ = window.__CHAT_CMD_PROMPT__?.replace(
|
||||
/\{([^{}]*)\}/,
|
||||
`{${v.trim()}}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
const searchInput = document.querySelector('form textarea');
|
||||
|
||||
// Enter a command starting with `/` and press a space to automatically fill `chatgpt prompt`.
|
||||
// If more than one command appears in the search results, the first one will be used by default.
|
||||
function cmdKeydown(event) {
|
||||
if (!window.__CHAT_CMD_PROMPT__) {
|
||||
if (
|
||||
!event.shiftKey &&
|
||||
event.keyCode === 13 &&
|
||||
__TAURI_METADATA__.__currentWindow.label === 'tray'
|
||||
) {
|
||||
const btn = document.querySelector('form button');
|
||||
if (btn) btn.click();
|
||||
event.preventDefault();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// ------------------ Keyboard scrolling (ArrowUp | ArrowDown) --------------------------
|
||||
if (event.keyCode === 38 && window.__cmd_index > 0) {
|
||||
// ArrowUp
|
||||
window.__cmd_list[window.__cmd_index].classList.remove('selected');
|
||||
window.__cmd_index = window.__cmd_index - 1;
|
||||
window.__cmd_list[window.__cmd_index].classList.add('selected');
|
||||
window.__CHAT_CMD_PROMPT__ = decodeURIComponent(
|
||||
window.__cmd_list[window.__cmd_index].getAttribute('data-prompt'),
|
||||
);
|
||||
searchInput.value = `/${window.__cmd_list[window.__cmd_index].getAttribute('data-cmd')}`;
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (event.keyCode === 40 && window.__cmd_index < window.__cmd_list.length - 1) {
|
||||
// ArrowDown
|
||||
window.__cmd_list[window.__cmd_index].classList.remove('selected');
|
||||
window.__cmd_index = window.__cmd_index + 1;
|
||||
window.__cmd_list[window.__cmd_index].classList.add('selected');
|
||||
window.__CHAT_CMD_PROMPT__ = decodeURIComponent(
|
||||
window.__cmd_list[window.__cmd_index].getAttribute('data-prompt'),
|
||||
);
|
||||
searchInput.value = `/${window.__cmd_list[window.__cmd_index].getAttribute('data-cmd')}`;
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
const containerHeight = promptDom.offsetHeight;
|
||||
const itemHeight = window.__cmd_list[0].offsetHeight + 1;
|
||||
|
||||
const itemTop = window.__cmd_list[window.__cmd_index].offsetTop;
|
||||
const itemBottom = itemTop + itemHeight;
|
||||
if (itemTop < promptDom.scrollTop || itemBottom > promptDom.scrollTop + containerHeight) {
|
||||
promptDom.scrollTop = itemTop;
|
||||
}
|
||||
|
||||
// ------------------ TAB key replaces `{q}` tag content -------------------------------
|
||||
// feat: https://github.com/lencx/ChatGPT/issues/54
|
||||
if (event.keyCode === 9 && !window.__CHAT_STATUS__) {
|
||||
const strGroup = window.__CHAT_CMD_PROMPT__.match(/\{([^{}]*)\}/) || [];
|
||||
|
||||
if (strGroup[1]) {
|
||||
searchInput.value = `/${window.__CHAT_CMD__}` + ` {${strGroup[1]}}` + ' |-> ';
|
||||
window.__CHAT_STATUS__ = 1;
|
||||
} else {
|
||||
searchInput.value = window.__CHAT_CMD_PROMPT__;
|
||||
initDom();
|
||||
}
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (window.__CHAT_STATUS__ === 1 && event.keyCode === 9) {
|
||||
// TAB
|
||||
const data = searchInput.value.split('|->');
|
||||
if (data[1]?.trim()) {
|
||||
setPrompt(data[1]);
|
||||
window.__CHAT_STATUS__ = 2;
|
||||
}
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
// input text
|
||||
if (window.__CHAT_STATUS__ === 2 && event.keyCode === 9) {
|
||||
// TAB
|
||||
searchInput.value = window.__CHAT_CMD_PROMPT__;
|
||||
promptDom.innerHTML = '';
|
||||
delete window.__CHAT_STATUS__;
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
// ------------------ type in a space to complete the fill ------------------------------------
|
||||
if (event.keyCode === 32) {
|
||||
searchInput.value = window.__CHAT_CMD_PROMPT__;
|
||||
promptDom.innerHTML = '';
|
||||
delete window.__CHAT_CMD_PROMPT__;
|
||||
}
|
||||
|
||||
// ------------------ send --------------------------------------------------------------------
|
||||
if (event.keyCode === 13 && window.__CHAT_CMD_PROMPT__) {
|
||||
// Enter
|
||||
const data = searchInput.value.split('|->');
|
||||
setPrompt(data[1]);
|
||||
|
||||
searchInput.value = window.__CHAT_CMD_PROMPT__;
|
||||
|
||||
initDom();
|
||||
|
||||
event.preventDefault();
|
||||
}
|
||||
}
|
||||
searchInput.removeEventListener('keydown', cmdKeydown, { capture: true });
|
||||
searchInput.addEventListener('keydown', cmdKeydown, { capture: true });
|
||||
|
||||
function cmdInput() {
|
||||
if (searchInput.value === '') {
|
||||
initDom();
|
||||
}
|
||||
|
||||
if (window.__CHAT_STATUS__) return;
|
||||
|
||||
const query = searchInput.value;
|
||||
if (!query || !/^\//.test(query)) {
|
||||
initDom();
|
||||
return;
|
||||
}
|
||||
|
||||
// all cmd result
|
||||
if (query === '/') {
|
||||
renderList(data);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = data.filter((i) => new RegExp(query.substring(1)).test(i.cmd));
|
||||
if (result.length > 0) {
|
||||
renderList(result);
|
||||
} else {
|
||||
initDom();
|
||||
}
|
||||
}
|
||||
searchInput.removeEventListener('input', cmdInput);
|
||||
searchInput.addEventListener('input', cmdInput);
|
||||
}
|
||||
}
|
||||
|
||||
function initDom() {
|
||||
const promptDom = document.querySelector('.chat-prompt-cmd-list');
|
||||
if (promptDom) {
|
||||
promptDom.innerHTML = '';
|
||||
}
|
||||
delete window.__CHAT_CMD_PROMPT__;
|
||||
delete window.__CHAT_CMD__;
|
||||
delete window.__CHAT_STATUS__;
|
||||
delete window.__cmd_list;
|
||||
delete window.__cmd_index;
|
||||
}
|
||||
}
|
||||
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
cmdInit();
|
||||
} else {
|
||||
document.addEventListener('DOMContentLoaded', cmdInit);
|
||||
}
|
||||
229
scripts/core.js
@ -1,229 +0,0 @@
|
||||
/**
|
||||
* @name core.js
|
||||
* @version 0.1.2
|
||||
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/core.js
|
||||
*/
|
||||
|
||||
function coreInit() {
|
||||
const uid = () => window.crypto.getRandomValues(new Uint32Array(1))[0];
|
||||
function transformCallback(callback = () => {}, once = false) {
|
||||
const identifier = uid();
|
||||
const prop = `_${identifier}`;
|
||||
Object.defineProperty(window, prop, {
|
||||
value: (result) => {
|
||||
if (once) {
|
||||
Reflect.deleteProperty(window, prop);
|
||||
}
|
||||
return callback(result);
|
||||
},
|
||||
writable: false,
|
||||
configurable: true,
|
||||
});
|
||||
return identifier;
|
||||
}
|
||||
|
||||
async function invoke(cmd, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!window.__TAURI_POST_MESSAGE__) reject('__TAURI_POST_MESSAGE__ does not exist!');
|
||||
const callback = transformCallback((e) => {
|
||||
resolve(e);
|
||||
Reflect.deleteProperty(window, `_${error}`);
|
||||
}, true);
|
||||
const error = transformCallback((e) => {
|
||||
reject(e);
|
||||
Reflect.deleteProperty(window, `_${callback}`);
|
||||
}, true);
|
||||
window.__TAURI_POST_MESSAGE__({
|
||||
cmd,
|
||||
callback,
|
||||
error,
|
||||
...args,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function message(message) {
|
||||
invoke('messageDialog', {
|
||||
__tauriModule: 'Dialog',
|
||||
message: {
|
||||
cmd: 'messageDialog',
|
||||
message: message.toString(),
|
||||
title: null,
|
||||
type: null,
|
||||
buttonLabel: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
window.uid = uid;
|
||||
window.invoke = invoke;
|
||||
window.message = message;
|
||||
window.transformCallback = transformCallback;
|
||||
|
||||
async function init() {
|
||||
if (__TAURI_METADATA__.__currentWindow.label === 'tray') {
|
||||
document.getElementsByTagName('html')[0].style['font-size'] = '70%';
|
||||
}
|
||||
|
||||
async function platform() {
|
||||
return invoke('platform', {
|
||||
__tauriModule: 'Os',
|
||||
message: { cmd: 'platform' },
|
||||
});
|
||||
}
|
||||
|
||||
if (__TAURI_METADATA__.__currentWindow.label !== 'tray') {
|
||||
const _platform = await platform();
|
||||
const chatConf = (await invoke('get_app_conf')) || {};
|
||||
if (/darwin/.test(_platform) && !chatConf.titlebar) {
|
||||
const topStyleDom = document.createElement('style');
|
||||
topStyleDom.innerHTML = `#chatgpt-app-window-top{position:fixed;top:0;z-index:999999999;width:100%;height:24px;background:transparent;cursor:grab;cursor:-webkit-grab;user-select:none;-webkit-user-select:none;}#chatgpt-app-window-top:active {cursor:grabbing;cursor:-webkit-grabbing;}`;
|
||||
document.head.appendChild(topStyleDom);
|
||||
const topDom = document.createElement('div');
|
||||
topDom.id = 'chatgpt-app-window-top';
|
||||
document.body.appendChild(topDom);
|
||||
|
||||
if (window.location.host === 'chat.openai.com') {
|
||||
const intervalId = setInterval(function () {
|
||||
const nav = document.body.querySelector('nav');
|
||||
if (nav) {
|
||||
nav.style.paddingTop = '25px';
|
||||
clearInterval(intervalId);
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
topDom.addEventListener('mousedown', () => invoke('drag_window'));
|
||||
topDom.addEventListener('touchstart', () => invoke('drag_window'));
|
||||
topDom.addEventListener('dblclick', () => invoke('fullscreen'));
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('click', (e) => {
|
||||
const origin = e.target.closest('a');
|
||||
if (!origin || !origin.target) return;
|
||||
if (origin && origin.href && origin.target !== '_self') {
|
||||
invoke('open_link', { url: origin.href });
|
||||
}
|
||||
});
|
||||
|
||||
// Fix Chinese input method "Enter" on Safari
|
||||
document.addEventListener(
|
||||
'keydown',
|
||||
(e) => {
|
||||
if (e.keyCode == 229) e.stopPropagation();
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
if (window.location.host === 'chat.openai.com') {
|
||||
window.__sync_prompts = async function () {
|
||||
await invoke('sync_prompts', { time: Date.now() });
|
||||
};
|
||||
}
|
||||
|
||||
coreZoom();
|
||||
|
||||
window.__LoadingMask = LoadingMask;
|
||||
}
|
||||
|
||||
function coreZoom() {
|
||||
const styleDom = document.createElement('style');
|
||||
styleDom.innerHTML = `
|
||||
#ZoomTopTip {
|
||||
display: none;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 20px;
|
||||
background: #2a2a2a;
|
||||
color: #fafafa;
|
||||
padding: 20px 15px;
|
||||
border-bottom-left-radius: 5px;
|
||||
border-bottom-right-radius: 5px;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
z-index: 999999;
|
||||
box-shadow: 0 2px 2px 2px #d8d8d8;
|
||||
}
|
||||
.ZoomTopTipAni {
|
||||
transition: opacity 200ms, display 200ms;
|
||||
display: none;
|
||||
opacity: 0;
|
||||
}
|
||||
`;
|
||||
document.head.append(styleDom);
|
||||
const zoomTipDom = document.createElement('div');
|
||||
zoomTipDom.id = 'ZoomTopTip';
|
||||
document.body.appendChild(zoomTipDom);
|
||||
function zoom(callback) {
|
||||
if (window.zoomSetTimeout) clearTimeout(window.zoomSetTimeout);
|
||||
const htmlZoom = window.localStorage.getItem('htmlZoom') || '100%';
|
||||
const html = document.getElementsByTagName('html')[0];
|
||||
const zoom = callback(htmlZoom);
|
||||
html.style.zoom = zoom;
|
||||
window.localStorage.setItem('htmlZoom', zoom);
|
||||
zoomTipDom.innerHTML = zoom;
|
||||
zoomTipDom.style.display = 'block';
|
||||
zoomTipDom.classList.remove('ZoomTopTipAni');
|
||||
window.zoomSetTimeout = setTimeout(() => {
|
||||
zoomTipDom.classList.add('ZoomTopTipAni');
|
||||
}, 2500);
|
||||
}
|
||||
function zoomDefault() {
|
||||
const htmlZoom = window.localStorage.getItem('htmlZoom');
|
||||
if (htmlZoom) {
|
||||
document.getElementsByTagName('html')[0].style.zoom = htmlZoom;
|
||||
}
|
||||
}
|
||||
function zoomIn() {
|
||||
zoom((htmlZoom) => `${Math.min(parseInt(htmlZoom) + 10, 200)}%`);
|
||||
}
|
||||
function zoomOut() {
|
||||
zoom((htmlZoom) => `${Math.max(parseInt(htmlZoom) - 10, 30)}%`);
|
||||
}
|
||||
function zoom0() {
|
||||
zoom(() => `100%`);
|
||||
}
|
||||
zoomDefault();
|
||||
window.__zoomIn = zoomIn;
|
||||
window.__zoomOut = zoomOut;
|
||||
window.__zoom0 = zoom0;
|
||||
}
|
||||
|
||||
function LoadingMask(text = 'Loading...') {
|
||||
// 创建遮罩元素
|
||||
const loadingOverlay = document.createElement('div');
|
||||
|
||||
function startLoading() {
|
||||
loadingOverlay.style = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0,0,0,.5);
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;`;
|
||||
loadingOverlay.innerHTML = `<div style="color:#fff;font-weight:bold">${text}</div>`;
|
||||
document.body.style.overflow = 'hidden';
|
||||
document.body.appendChild(loadingOverlay);
|
||||
}
|
||||
|
||||
function stopLoading() {
|
||||
document.body.style.overflow = null;
|
||||
loadingOverlay.remove();
|
||||
}
|
||||
|
||||
return { startLoading, stopLoading };
|
||||
}
|
||||
|
||||
init();
|
||||
}
|
||||
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
coreInit();
|
||||
} else {
|
||||
document.addEventListener('DOMContentLoaded', coreInit);
|
||||
}
|
||||
@ -1,309 +0,0 @@
|
||||
/**
|
||||
* @name export.js
|
||||
* @version 0.1.5
|
||||
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/export.js
|
||||
*/
|
||||
|
||||
async function exportInit() {
|
||||
const SELECTOR = 'main div.group';
|
||||
const USER_INPUT_SELECTOR = 'div.empty\\:hidden';
|
||||
const Format = {
|
||||
PNG: 'png',
|
||||
PDF: 'pdf',
|
||||
};
|
||||
|
||||
function processNode(node, replaceInUserInput = false) {
|
||||
let j = node.cloneNode(true);
|
||||
if (/dark\:bg-gray-800/.test(node.getAttribute('class'))) {
|
||||
j.innerHTML = `<blockquote>${node.innerHTML}</blockquote>`;
|
||||
}
|
||||
|
||||
if (replaceInUserInput) {
|
||||
const userInputBlocks = j.querySelectorAll(USER_INPUT_SELECTOR);
|
||||
userInputBlocks.forEach((block) => {
|
||||
//For quicker testing use js fiddle: https://jsfiddle.net/xtraeme/x34ao9jp/13/
|
||||
block.innerHTML = block.innerHTML
|
||||
.replace(/ |\u00A0/g, ' ') //Replace =C2=A0 (nbsp non-breaking space) /w breaking-space
|
||||
.replace(/\t/g, ' ') // Replace tab with 4 non-breaking spaces
|
||||
.replace(/^ +/gm, function (match) {
|
||||
return ' '.repeat(match.length);
|
||||
}) //Add =C2=A0
|
||||
.replace(/\n/g, '<br/>');
|
||||
});
|
||||
}
|
||||
|
||||
return j.innerHTML;
|
||||
}
|
||||
|
||||
async function exportMarkdown() {
|
||||
const allBlocks = document.querySelectorAll(SELECTOR);
|
||||
const nodes = Array.from(allBlocks);
|
||||
|
||||
//<code> blocks with leading spaces mess up ExportMD markdown conversion. ex/
|
||||
// <code ...> import package
|
||||
//becomes (spaces are moved to the front of the ''' line)):
|
||||
// '''Python import package
|
||||
//so we remove whitespace after <code> tags and add <br/> and/or \n
|
||||
allBlocks.forEach((block) => {
|
||||
block.innerHTML = block.innerHTML.replace(/(<code[^>]*>)\s*/g, '$1<br\\/>\n'); // Add \n or <br/> after opening code tag
|
||||
});
|
||||
|
||||
const updatedContent = nodes.map((i) => processNode(i, true)).join('');
|
||||
|
||||
const data = ExportMD.turndown(updatedContent);
|
||||
const { id, filename } = getName();
|
||||
await invoke('save_file', { name: `notes/${id}.md`, content: data });
|
||||
await invoke('download_list', { pathname: 'chat.notes.json', filename, id, dir: 'notes' });
|
||||
}
|
||||
|
||||
async function downloadThread({ as = Format.PNG } = {}) {
|
||||
const { startLoading, stopLoading } = new window.__LoadingMask('Exporting in progress...');
|
||||
startLoading();
|
||||
const elements = new Elements();
|
||||
await elements.fixLocation();
|
||||
const pixelRatio = window.devicePixelRatio;
|
||||
const minRatio = as === Format.PDF ? 2 : 2.5;
|
||||
window.devicePixelRatio = Math.max(pixelRatio, minRatio);
|
||||
|
||||
html2canvas(elements.thread, {
|
||||
letterRendering: true,
|
||||
useCORS: true,
|
||||
}).then((canvas) => {
|
||||
elements.restoreLocation();
|
||||
window.devicePixelRatio = pixelRatio;
|
||||
const imgData = canvas.toDataURL('image/png');
|
||||
requestAnimationFrame(async () => {
|
||||
if (as === Format.PDF) {
|
||||
await handlePdf(imgData, canvas, pixelRatio);
|
||||
} else {
|
||||
await handleImg(imgData);
|
||||
}
|
||||
stopLoading();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function handleImg(imgData) {
|
||||
const binaryData = atob(imgData.split('base64,')[1]);
|
||||
const data = [];
|
||||
for (let i = 0; i < binaryData.length; i++) {
|
||||
data.push(binaryData.charCodeAt(i));
|
||||
}
|
||||
const name = `ChatGPT_${formatDateTime()}.png`;
|
||||
await invoke('download_file', { name: name, blob: data });
|
||||
}
|
||||
|
||||
async function handlePdf(imgData, canvas, pixelRatio) {
|
||||
const { jsPDF } = window.jspdf;
|
||||
const orientation = canvas.width > canvas.height ? 'l' : 'p';
|
||||
var pdf = new jsPDF(orientation, 'pt', [canvas.width / pixelRatio, canvas.height / pixelRatio]);
|
||||
var pdfWidth = pdf.internal.pageSize.getWidth();
|
||||
var pdfHeight = pdf.internal.pageSize.getHeight();
|
||||
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight, '', 'FAST');
|
||||
const data = pdf.__private__.getArrayBuffer(pdf.__private__.buildDocument());
|
||||
|
||||
const name = `ChatGPT_${formatDateTime()}.pdf`;
|
||||
await invoke('download_file', { name: name, blob: Array.from(new Uint8Array(data)) });
|
||||
}
|
||||
|
||||
class Elements {
|
||||
constructor() {
|
||||
this.init();
|
||||
}
|
||||
init() {
|
||||
this.spacer = document.querySelector("main div[class*='h-'].flex-shrink-0");
|
||||
this.thread = document.querySelector(
|
||||
"[class*='react-scroll-to-bottom']>[class*='react-scroll-to-bottom']>div",
|
||||
);
|
||||
|
||||
// fix: old chat https://github.com/lencx/ChatGPT/issues/185
|
||||
if (!this.thread) {
|
||||
this.thread = document.querySelector('main .overflow-y-auto');
|
||||
}
|
||||
|
||||
// h-full overflow-y-auto
|
||||
this.positionForm = document.querySelector('form').parentNode;
|
||||
this.scroller = Array.from(document.querySelectorAll('[class*="react-scroll-to"]')).filter(
|
||||
(el) => el.classList.contains('h-full'),
|
||||
)[0];
|
||||
|
||||
// fix: old chat
|
||||
if (!this.scroller) {
|
||||
this.scroller = document.querySelector('main .overflow-y-auto');
|
||||
}
|
||||
|
||||
this.hiddens = Array.from(document.querySelectorAll('.overflow-hidden'));
|
||||
this.images = Array.from(document.querySelectorAll('img[srcset]'));
|
||||
this.chatImages = Array.from(document.querySelectorAll('main img[src]'));
|
||||
}
|
||||
async fixLocation() {
|
||||
this.hiddens.forEach((el) => {
|
||||
el.classList.remove('overflow-hidden');
|
||||
});
|
||||
this.spacer.style.display = 'none';
|
||||
this.thread.style.maxWidth = '960px';
|
||||
this.thread.style.marginInline = 'auto';
|
||||
this.positionForm.style.display = 'none';
|
||||
this.scroller.classList.remove('h-full');
|
||||
this.scroller.style.minHeight = '100vh';
|
||||
this.images.forEach((img) => {
|
||||
const srcset = img.getAttribute('srcset');
|
||||
img.setAttribute('srcset_old', srcset);
|
||||
img.setAttribute('srcset', '');
|
||||
});
|
||||
|
||||
// const chatImagePromises = this.chatImages.map(async (img) => {
|
||||
// const src = img.getAttribute('src');
|
||||
// if (!/^http/.test(src)) return;
|
||||
// if (['fileserviceuploadsperm.blob.core.windows.net'].includes(new URL(src)?.host)) return;
|
||||
// const data = await invoke('fetch_image', { url: src });
|
||||
// const blob = new Blob([new Uint8Array(data)], { type: 'image/png' });
|
||||
// img.src = URL.createObjectURL(blob);
|
||||
// });
|
||||
// await Promise.all(chatImagePromises);
|
||||
document.body.style.lineHeight = '0.5';
|
||||
}
|
||||
async restoreLocation() {
|
||||
this.hiddens.forEach((el) => {
|
||||
el.classList.add('overflow-hidden');
|
||||
});
|
||||
this.spacer.style.display = null;
|
||||
this.thread.style.maxWidth = null;
|
||||
this.thread.style.marginInline = null;
|
||||
this.positionForm.style.display = null;
|
||||
this.scroller.classList.add('h-full');
|
||||
this.scroller.style.minHeight = null;
|
||||
}
|
||||
}
|
||||
|
||||
function formatDateTime() {
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(now.getDate()).padStart(2, '0');
|
||||
const hours = String(now.getHours()).padStart(2, '0');
|
||||
const minutes = String(now.getMinutes()).padStart(2, '0');
|
||||
const seconds = String(now.getSeconds()).padStart(2, '0');
|
||||
const formattedDateTime = `${year}_${month}_${day}-${hours}${minutes}${seconds}`;
|
||||
return formattedDateTime;
|
||||
}
|
||||
|
||||
// function sanitizeFilename(filename) {
|
||||
// if (!filename || filename === '') return '';
|
||||
|
||||
// // Replace whitespaces with underscores
|
||||
// let sanitizedFilename = filename.replace(/\s/g, '_');
|
||||
|
||||
// // Replace invalid filename characters with #
|
||||
// const invalidCharsRegex = /[<>:"/\\|?*\x00-\x1F]/g;
|
||||
// sanitizedFilename = sanitizedFilename.replace(invalidCharsRegex, '#');
|
||||
|
||||
// // Check for filenames ending with period or space (Windows)
|
||||
// if (sanitizedFilename && /[\s.]$/.test(sanitizedFilename)) {
|
||||
// sanitizedFilename = sanitizedFilename.slice(0, -1) + '#';
|
||||
// }
|
||||
// //console.log(sanitizedFilename);
|
||||
// return sanitizedFilename;
|
||||
// }
|
||||
|
||||
function btnInit() {
|
||||
const intervalId = setInterval(function () {
|
||||
const navActionArea = document.querySelector('nav .border-t > div');
|
||||
const addArea = document.querySelector('#chatgpt-nav-action-area');
|
||||
if (!navActionArea || addArea) return;
|
||||
const cloneNode = document.createElement('div');
|
||||
cloneNode.id = 'chatgpt-nav-action-area';
|
||||
cloneNode.classList = `${navActionArea.className} border-b border-white/20 mb-2 pb-2`;
|
||||
cloneNode.appendChild(addBtn('png'));
|
||||
cloneNode.appendChild(addBtn('pdf'));
|
||||
cloneNode.appendChild(addBtn('md'));
|
||||
cloneNode.appendChild(addBtn('refresh'));
|
||||
navActionArea.parentNode.insertBefore(cloneNode, navActionArea);
|
||||
clearInterval(intervalId);
|
||||
|
||||
function debounce(func, wait) {
|
||||
let timeout;
|
||||
return function () {
|
||||
const context = this;
|
||||
const args = arguments;
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(() => {
|
||||
func.apply(context, args);
|
||||
}, wait);
|
||||
};
|
||||
}
|
||||
const target = document.querySelector('nav');
|
||||
const debouncedFunction = debounce(function () {
|
||||
btnInit();
|
||||
}, 300);
|
||||
const observer = new MutationObserver(debouncedFunction);
|
||||
const config = { attributes: true, childList: true, characterData: true, subtree: true };
|
||||
observer.observe(target, config);
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function addBtn(type) {
|
||||
const btn = document.createElement('button');
|
||||
btn.className = `btn dark:text-gray-500 hover:dark:text-gray-300`;
|
||||
btn.title = {
|
||||
png: 'Export PNG',
|
||||
pdf: 'Export PDF',
|
||||
md: 'Export Markdown',
|
||||
refresh: 'Refresh the Page',
|
||||
}[type];
|
||||
btn.innerHTML = setIcon(type);
|
||||
btn.onclick = () => {
|
||||
const content = document.querySelector('main .group');
|
||||
if (!content && type !== 'refresh') {
|
||||
alert('Please open a thread first.');
|
||||
return;
|
||||
}
|
||||
switch (type) {
|
||||
case 'png':
|
||||
downloadThread();
|
||||
break;
|
||||
case 'pdf':
|
||||
downloadThread({ as: 'pdf' });
|
||||
break;
|
||||
case 'md':
|
||||
exportMarkdown();
|
||||
break;
|
||||
case 'refresh':
|
||||
window.location.reload();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
return btn;
|
||||
}
|
||||
|
||||
function setIcon(type) {
|
||||
return {
|
||||
png: `<svg class="chatappico png" viewBox="0 0 1024 1024"><path d="M264.258065 338.580645c16.780387 0 31.281548-6.144 43.536516-18.398968 12.254968-12.221935 18.398968-26.756129 18.398967-43.536516s-6.144-31.281548-18.398967-43.536516A59.524129 59.524129 0 0 0 264.258065 214.709677c-16.780387 0-31.281548 6.144-43.536517 18.398968-12.254968 12.221935-18.398968 26.756129-18.398967 43.536516s6.144 31.281548 18.398967 43.536516c12.221935 12.254968 26.756129 18.398968 43.536517 18.398968zM883.612903 28.903226H140.387097a119.345548 119.345548 0 0 0-87.568516 36.302451A119.345548 119.345548 0 0 0 16.516129 152.774194v743.225806c0 34.188387 12.089806 63.388903 36.302452 87.568516a119.345548 119.345548 0 0 0 87.568516 36.302452h743.225806a119.345548 119.345548 0 0 0 87.568516-36.302452A119.345548 119.345548 0 0 0 1007.483871 896v-743.225806a119.345548 119.345548 0 0 0-36.302452-87.568517A119.345548 119.345548 0 0 0 883.612903 28.903226zM264.258065 152.774194c34.188387 0 63.388903 12.089806 87.568516 36.302451a119.345548 119.345548 0 0 1 36.302451 87.568516 119.345548 119.345548 0 0 1-36.302451 87.568516A119.345548 119.345548 0 0 1 264.258065 400.516129a119.345548 119.345548 0 0 1-87.568517-36.302452A119.345548 119.345548 0 0 1 140.387097 276.645161c0-34.188387 12.089806-63.388903 36.302451-87.568516A119.345548 119.345548 0 0 1 264.258065 152.774194zM140.387097 957.935484c-16.780387 0-31.281548-6.144-43.536516-18.398968a59.524129 59.524129 0 0 1-18.398968-43.536516v-29.035355l245.793032-220.655484L635.870968 957.935484h-495.483871z m805.16129-61.935484c0 16.780387-6.144 31.281548-18.398968 43.536516-12.221935 12.254968-26.756129 18.398968-43.536516 18.398968h-159.677935l-228.385033-231.291871L759.741935 462.451613l185.806452 185.806452v247.741935z" fill="currentColor"></path></svg>`,
|
||||
pdf: `<svg class="chatappico pdf" viewBox="0 0 1024 1024"><path d="M821.457602 118.382249H205.725895c-48.378584 0-87.959995 39.583368-87.959996 87.963909v615.731707c0 48.378584 39.581411 87.959995 87.959996 87.959996h615.733664c48.380541 0 87.961952-39.581411 87.961952-87.959996V206.346158c-0.001957-48.378584-39.583368-87.963909-87.963909-87.963909zM493.962468 457.544987c-10.112054 32.545237-21.72487 82.872662-38.806571 124.248336-8.806957 22.378397-8.380404 18.480717-15.001764 32.609808l5.71738-1.851007c58.760658-16.443827 99.901532-20.519564 138.162194-27.561607-7.67796-6.06371-14.350194-10.751884-19.631237-15.586807-26.287817-29.101504-35.464584-34.570387-70.440002-111.862636v0.003913z m288.36767 186.413594c-7.476424 8.356924-20.670227 13.191847-40.019704 13.191847-33.427694 0-63.808858-9.229597-107.79277-31.660824-75.648648 8.356924-156.097 17.214754-201.399704 31.729308-2.199293 0.876587-4.832967 1.759043-7.916674 3.077836-54.536215 93.237125-95.031389 132.767663-130.621199 131.19646-11.286054-0.49895-27.694661-7.044-32.973748-10.11988l-6.52157-6.196764-2.29517-4.353583c-3.07588-7.91863-3.954423-15.395054-2.197337-23.751977 4.838837-23.309771 29.907651-60.251638 82.686779-93.237126 8.356924-6.159587 27.430511-15.897917 45.020944-24.25484 13.311204-21.177004 19.45905-34.744531 36.341171-72.259702 19.102937-45.324228 36.505531-99.492589 47.500041-138.191543v-0.44025c-16.267727-53.219378-25.945401-89.310095-9.67376-147.80856 3.958337-16.71189 18.46702-33.864031 34.748444-33.864031h10.552304c10.115967 0 19.791684 3.520043 26.829814 10.552304 29.029107 29.031064 15.39114 103.824649 0.8805 162.323113-0.8805 2.63563-1.322707 4.832967-1.761 6.153717 17.59239 49.697378 45.400538 98.774492 73.108895 121.647926 11.436717 8.791304 22.638634 18.899444 36.71098 26.814161 19.791684-2.20125 37.517128-4.11487 55.547812-4.11487 54.540128 0 87.525615 9.67963 100.279169 30.351814 4.400543 7.034217 6.595923 15.389184 5.281043 24.1844-0.44025 10.996467-4.39663 21.112434-12.31526 29.031064z m-27.796407-36.748157c-4.394673-4.398587-17.024957-16.936907-78.601259-16.936907-3.073923 0-10.622744-0.784623-14.57521 3.612007 32.104987 14.072347 62.830525 24.757704 83.058545 24.757703 3.083707 0 5.72325-0.442207 8.356923-0.876586h1.759044c2.20125-0.8805 3.520043-1.324663 3.960293-5.71738-0.87463-1.324663-1.757087-3.083707-3.958336-4.838837z m-387.124553 63.041845c-9.237424 5.27713-16.71189 10.112054-21.112433 13.634053-31.226444 28.586901-51.018128 57.616008-53.217422 74.331812 19.789727-6.59788 45.737084-35.626987 74.329855-87.961952v-0.003913z m125.574957-297.822284l2.197336-1.761c3.079793-14.072347 5.232127-29.189554 7.87167-38.869184l1.318794-7.036174c4.39663-25.070771 2.71781-39.720334-4.76057-50.272637l-6.59788-2.20125a57.381208 57.381208 0 0 0-3.079794 5.27713c-7.474467 18.47289-7.063567 55.283661 3.0524 94.865072l-0.001956-0.001957z" fill="currentColor"></path></svg>`,
|
||||
md: `<svg class="chatappico md" viewBox="0 0 1024 1024"><path d="M128 128h768a42.666667 42.666667 0 0 1 42.666667 42.666667v682.666666a42.666667 42.666667 0 0 1-42.666667 42.666667H128a42.666667 42.666667 0 0 1-42.666667-42.666667V170.666667a42.666667 42.666667 0 0 1 42.666667-42.666667z m170.666667 533.333333v-170.666666l85.333333 85.333333 85.333333-85.333333v170.666666h85.333334v-298.666666h-85.333334l-85.333333 85.333333-85.333333-85.333333H213.333333v298.666666h85.333334z m469.333333-128v-170.666666h-85.333333v170.666666h-85.333334l128 128 128-128h-85.333333z" fill="currentColor"></path></svg>`,
|
||||
refresh: `<svg class="chatappico refresh" viewBox="0 0 1024 1024"><path d="M512 63.5C264.3 63.5 63.5 264.3 63.5 512S264.3 960.5 512 960.5 960.5 759.7 960.5 512 759.7 63.5 512 63.5zM198 509.6h87.6c0-136.3 102.3-243.4 233.7-238.5 43.8 0 82.8 14.6 121.7 34.1L597.2 349c-24.4-9.8-53.6-19.5-82.8-19.5-92.5 0-170.4 77.9-170.4 180.1h87.6L314.8 631.3 198 509.6z m540.3-0.1c0 131.4-102.2 243.4-228.8 243.4-43.8 0-82.8-19.4-121.7-38.9l43.8-43.8c24.4 9.8 53.6 19.5 82.8 19.5 92.5 0 170.4-77.9 170.4-180.1h-92.5l116.9-121.7L826 509.5h-87.7z" fill="currentColor"></path></svg>`,
|
||||
}[type];
|
||||
}
|
||||
|
||||
function getName() {
|
||||
const id = window.crypto.getRandomValues(new Uint32Array(1))[0].toString(36);
|
||||
const name =
|
||||
document.querySelector('nav .overflow-y-auto a.hover\\:bg-gray-800')?.innerText?.trim() || '';
|
||||
// clean_name = sanitizeFilename(name);
|
||||
return {
|
||||
id,
|
||||
filename: name ? name : id,
|
||||
pathname: 'chat.download.json',
|
||||
};
|
||||
}
|
||||
|
||||
btnInit();
|
||||
}
|
||||
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
exportInit();
|
||||
} else {
|
||||
document.addEventListener('DOMContentLoaded', exportInit);
|
||||
}
|
||||
@ -1,5 +0,0 @@
|
||||
// *** ChatGPT User Script ***
|
||||
// @github: https://github.com/lencx/ChatGPT
|
||||
// @path: $HOME/.chatgpt/scripts/main.js
|
||||
|
||||
console.log('Hello, ChatGPT!');
|
||||
@ -1,28 +0,0 @@
|
||||
{
|
||||
"name": "ChatGPT Scripts",
|
||||
"author": "lencx",
|
||||
"description": "ChatGPT Desktop Application Core Extension Scripts.",
|
||||
"url": "https://github.com/lencx/ChatGPT/tree/main/scripts",
|
||||
"scripts": [
|
||||
{
|
||||
"name": "chat.js",
|
||||
"version": "0.1.4"
|
||||
},
|
||||
{
|
||||
"name": "cmd.js",
|
||||
"version": "0.1.2"
|
||||
},
|
||||
{
|
||||
"name": "core.js",
|
||||
"version": "0.1.2"
|
||||
},
|
||||
{
|
||||
"name": "export.js",
|
||||
"version": "0.1.5"
|
||||
},
|
||||
{
|
||||
"name": "markdown.export.js",
|
||||
"version": "0.1.0"
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,52 +0,0 @@
|
||||
/**
|
||||
* @name markdown.export.js
|
||||
* @version 0.1.0
|
||||
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/markdown.export.js
|
||||
*/
|
||||
|
||||
var ExportMD = (function () {
|
||||
if (!TurndownService || !turndownPluginGfm) return;
|
||||
const hljsREG = /^.*(hljs).*(language-[a-z0-9]+).*$/i;
|
||||
const gfm = turndownPluginGfm.gfm;
|
||||
const turndownService = new TurndownService({
|
||||
hr: '---',
|
||||
})
|
||||
.use(gfm)
|
||||
.addRule('code', {
|
||||
filter(node) {
|
||||
if (node.nodeName === 'CODE' && hljsREG.test(node.classList.value)) {
|
||||
return 'code';
|
||||
}
|
||||
},
|
||||
replacement(content, node) {
|
||||
const classStr = node.getAttribute('class');
|
||||
if (hljsREG.test(classStr)) {
|
||||
const lang = classStr.match(/.*language-(\w+)/)[1];
|
||||
if (lang) {
|
||||
return `\`\`\`${lang}\n${content}\n\`\`\``;
|
||||
}
|
||||
return `\`\`\`\n${content}\n\`\`\``;
|
||||
}
|
||||
},
|
||||
})
|
||||
.addRule('ignore-text', {
|
||||
filter: (node) => {
|
||||
if (node.nodeName === 'DIV' && node.classList.contains('!invisible')) {
|
||||
return 'ignore-text';
|
||||
}
|
||||
},
|
||||
replacement: () => '',
|
||||
})
|
||||
.addRule('ignore', {
|
||||
filter: ['button', 'img', 'svg'],
|
||||
replacement: () => '',
|
||||
})
|
||||
.addRule('table', {
|
||||
filter: 'table',
|
||||
replacement(content, node) {
|
||||
return `\`\`\`${content}\n\`\`\``;
|
||||
},
|
||||
});
|
||||
|
||||
return turndownService;
|
||||
})({});
|
||||
44
sponsor.html
@ -1,44 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>ChatGPT</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
|
||||
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
p {
|
||||
margin: 0;
|
||||
padding: 5px 10px;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: #686868;
|
||||
}
|
||||
a {
|
||||
margin: 20px 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
img {
|
||||
width: 240px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<p>🙏 Thank you for your support, which can help ChatGPT Free version to develop better!</p>
|
||||
<p>🙏 感谢您的支持,可以让 ChatGPT 免费版更好的发展!</p>
|
||||
<a target="_blank" href="https://www.buymeacoffee.com/lencx">
|
||||
<img style="width: 160px" src="/bmc.png" />
|
||||
</a>
|
||||
<img src="/wxp.png" />
|
||||
</body>
|
||||
</html>
|
||||
7
src-tauri/.gitignore
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
|
||||
# Generated by Tauri
|
||||
# will have schema files for capabilities auto-completion
|
||||
/gen/schemas
|
||||
@ -1,43 +1,29 @@
|
||||
[package]
|
||||
name = "chatgpt"
|
||||
version = "0.0.0"
|
||||
description = "ChatGPT Desktop Application (Unofficial)"
|
||||
authors = ["lencx <cxin1314@gmail.com>"]
|
||||
description = "ChatGPT Desktop Application"
|
||||
repository = "https://github.com/lencx/ChatGPT"
|
||||
license = "MIT"
|
||||
license = "AGPL-3.0"
|
||||
edition = "2021"
|
||||
rust-version = "1.64"
|
||||
rust-version = "1.77.1"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = {version = "1.4.0", features = [] }
|
||||
tauri-build = { version = "2.0.0-beta", features = [] }
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.66"
|
||||
serde_json = "1.0"
|
||||
log = "0.4.17"
|
||||
csv = "1.1.6"
|
||||
thiserror = "1.0.38"
|
||||
walkdir = "2.3.2"
|
||||
regex = "1.7.0"
|
||||
reqwest = "0.11.13"
|
||||
dark-light = "1.0.0"
|
||||
wry = "0.*"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
tokio = { version = "1.23.0", features = ["macros"] }
|
||||
tauri = { version = "1.5.2", features = ["devtools", "dialog-all", "fs-create-dir", "fs-exists", "fs-read-dir", "fs-read-file", "fs-remove-dir", "fs-remove-file", "fs-write-file", "global-shortcut", "global-shortcut-all", "os-all", "path-all", "process-all", "shell-all", "shell-open-api", "system-tray", "updater"] }
|
||||
tauri-plugin-positioner = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1", features = ["system-tray"] }
|
||||
tauri-plugin-log = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1", features = ["colored"] }
|
||||
tauri-plugin-autostart = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
|
||||
tauri-plugin-window-state = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
|
||||
|
||||
# sqlx = { version = "0.6.2", features = ["runtime-tokio-rustls", "sqlite"] }
|
||||
|
||||
[features]
|
||||
# by default Tauri runs in production mode
|
||||
# when `tauri dev` runs, it is executed with `cargo run --no-default-features` if `devPath` is an URL
|
||||
default = [ "custom-protocol" ]
|
||||
# this feature is used for production builds where `devPath` points to the filesystem
|
||||
# DO NOT remove this
|
||||
custom-protocol = [ "tauri/custom-protocol" ]
|
||||
tauri = { version = "2.0.0-beta", features = ["unstable", "devtools"] }
|
||||
tokio = { version = "1.37.0", features = ["macros"] }
|
||||
tauri-plugin-shell = "2.0.0-beta"
|
||||
tauri-plugin-dialog = "2.0.0-beta"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
once_cell = "1.19.0"
|
||||
log = "0.4.21"
|
||||
anyhow = "1.0.83"
|
||||
dark-light = "1.1.1"
|
||||
regex = "1.10.4"
|
||||
semver = "1.0.23"
|
||||
tauri-plugin-os = "2.0.0-beta.4"
|
||||
|
||||
19
src-tauri/Info.plist
Normal file
@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSExceptionDomains</key>
|
||||
<dict>
|
||||
<key>chatgpt.com</key>
|
||||
<dict>
|
||||
<key>NSExceptionAllowsInsecureHTTPLoads</key>
|
||||
<true />
|
||||
<key>NSIncludesSubdomains</key>
|
||||
<true />
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
@ -1,3 +1,6 @@
|
||||
// src-tauri/build.rs
|
||||
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
println!("cargo:rustc-env=MACOSX_DEPLOYMENT_TARGET=10.13");
|
||||
tauri_build::build()
|
||||
}
|
||||
|
||||
44
src-tauri/capabilities/desktop.json
Normal file
@ -0,0 +1,44 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "desktop-capability",
|
||||
"windows": [
|
||||
"*"
|
||||
],
|
||||
"remote": {
|
||||
"urls": [
|
||||
"https://chatgpt.com/*"
|
||||
]
|
||||
},
|
||||
"platforms": [
|
||||
"linux",
|
||||
"macOS",
|
||||
"windows"
|
||||
],
|
||||
"permissions": [
|
||||
"window:default",
|
||||
"window:allow-create",
|
||||
"window:allow-start-dragging",
|
||||
"window:allow-toggle-maximize",
|
||||
"window:allow-minimize",
|
||||
"window:allow-close",
|
||||
"webview:default",
|
||||
"webview:allow-internal-toggle-devtools",
|
||||
"webview:allow-set-webview-zoom",
|
||||
"webview:allow-create-webview",
|
||||
"webview:allow-create-webview-window",
|
||||
"event:default",
|
||||
"event:allow-emit",
|
||||
"event:allow-emit-to",
|
||||
"event:allow-listen",
|
||||
"event:allow-unlisten",
|
||||
"shell:default",
|
||||
"shell:allow-execute",
|
||||
"shell:allow-open",
|
||||
"os:allow-arch",
|
||||
"os:allow-platform",
|
||||
"os:allow-version",
|
||||
"os:allow-os-type",
|
||||
"os:default",
|
||||
"shell:default"
|
||||
]
|
||||
}
|
||||
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 33 KiB After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 8.4 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 39 KiB After Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 3.5 KiB After Width: | Height: | Size: 2.7 KiB |
|
Before Width: | Height: | Size: 6.4 KiB After Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 8.5 KiB After Width: | Height: | Size: 6.6 KiB |
|
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 36 KiB |
|
Before Width: | Height: | Size: 104 KiB After Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 92 KiB |
|
Before Width: | Height: | Size: 76 KiB |
33
src-tauri/scripts/ask.js
Normal file
@ -0,0 +1,33 @@
|
||||
/**
|
||||
* @name ask.js
|
||||
* @version 0.1.0
|
||||
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/ask.js
|
||||
*/
|
||||
|
||||
class ChatAsk {
|
||||
static sync(message) {
|
||||
const inputElement = document.querySelector('textarea');
|
||||
if (inputElement) {
|
||||
const nativeTextareaSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set;
|
||||
nativeTextareaSetter.call(inputElement, message);
|
||||
const inputEvent = new InputEvent('input', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
inputElement.dispatchEvent(inputEvent);
|
||||
}
|
||||
}
|
||||
|
||||
static submit() {
|
||||
const btns = document.querySelectorAll('main form button');
|
||||
const btn = btns[btns.length - 1];
|
||||
|
||||
if (btn) {
|
||||
btn.focus();
|
||||
btn.disabled = false;
|
||||
btn.click();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.ChatAsk = ChatAsk;
|
||||
@ -1,89 +0,0 @@
|
||||
use crate::utils;
|
||||
use log::error;
|
||||
use std::{fs, path::PathBuf};
|
||||
use tauri::{api, command, AppHandle, Manager};
|
||||
|
||||
#[command]
|
||||
pub fn drag_window(app: AppHandle) {
|
||||
app.get_window("core").unwrap().start_dragging().unwrap();
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn fullscreen(app: AppHandle) {
|
||||
let win = app.get_window("core").unwrap();
|
||||
if win.is_fullscreen().unwrap() {
|
||||
win.set_fullscreen(false).unwrap();
|
||||
} else {
|
||||
win.set_fullscreen(true).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
// #[command]
|
||||
// pub fn download(app: AppHandle, name: String, blob: Vec<u8>) {
|
||||
// let win = app.app_handle().get_window("core");
|
||||
// let path = utils::app_root().join(PathBuf::from(name));
|
||||
// utils::create_file(&path).unwrap();
|
||||
// fs::write(&path, blob).unwrap();
|
||||
// tauri::api::dialog::message(
|
||||
// win.as_ref(),
|
||||
// "Save File",
|
||||
// format!("PATH: {}", path.display()),
|
||||
// );
|
||||
// }
|
||||
|
||||
#[command]
|
||||
pub fn save_file(_app: AppHandle, name: String, content: String) {
|
||||
// let win = app.app_handle().get_window("core");
|
||||
let path = utils::app_root().join(PathBuf::from(name));
|
||||
utils::create_file(&path).unwrap();
|
||||
fs::write(&path, content).unwrap();
|
||||
utils::open_file(path);
|
||||
// tauri::api::dialog::message(
|
||||
// win.as_ref(),
|
||||
// "Save File",
|
||||
// format!("PATH: {}", path.display()),
|
||||
// );
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn open_link(app: AppHandle, url: String) {
|
||||
api::shell::open(&app.shell_scope(), url, None).unwrap();
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn run_check_update(app: AppHandle, silent: bool, has_msg: Option<bool>) {
|
||||
utils::run_check_update(app, silent, has_msg);
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn open_file(path: PathBuf) {
|
||||
utils::open_file(path);
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn download_file(name: String, blob: Vec<u8>) {
|
||||
let file = tauri::api::path::download_dir().unwrap().join(name);
|
||||
fs::write(&file, blob).unwrap();
|
||||
utils::open_file(file);
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn get_data(app: AppHandle, url: String, is_msg: Option<bool>) -> Option<String> {
|
||||
let is_msg = is_msg.unwrap_or(false);
|
||||
let res = if is_msg {
|
||||
utils::get_data(&url, Some(&app)).await
|
||||
} else {
|
||||
utils::get_data(&url, None).await
|
||||
};
|
||||
res.unwrap_or_else(|err| {
|
||||
error!("chatgpt_client_http: {}", err);
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn fetch_image(url: String) -> Vec<u8> {
|
||||
let response = reqwest::get(url).await.unwrap();
|
||||
let bytes = response.bytes().await.unwrap();
|
||||
bytes.to_vec()
|
||||
}
|
||||
@ -1,124 +0,0 @@
|
||||
// https://github.com/tauri-apps/tauri-plugin-fs-extra/blob/dev/src/lib.rs
|
||||
|
||||
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{ser::Serializer, Serialize};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use tauri::command;
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
impl Serialize for Error {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.to_string().as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Permissions {
|
||||
readonly: bool,
|
||||
#[cfg(unix)]
|
||||
mode: u32,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct UnixMetadata {
|
||||
dev: u64,
|
||||
ino: u64,
|
||||
mode: u32,
|
||||
nlink: u64,
|
||||
uid: u32,
|
||||
gid: u32,
|
||||
rdev: u64,
|
||||
blksize: u64,
|
||||
blocks: u64,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Metadata {
|
||||
accessed_at_ms: u64,
|
||||
pub created_at_ms: u64,
|
||||
modified_at_ms: u64,
|
||||
is_dir: bool,
|
||||
is_file: bool,
|
||||
is_symlink: bool,
|
||||
size: u64,
|
||||
permissions: Permissions,
|
||||
#[cfg(unix)]
|
||||
#[serde(flatten)]
|
||||
unix: UnixMetadata,
|
||||
#[cfg(windows)]
|
||||
file_attributes: u32,
|
||||
}
|
||||
|
||||
pub fn system_time_to_ms(time: std::io::Result<SystemTime>) -> u64 {
|
||||
time
|
||||
.map(|t| {
|
||||
let duration_since_epoch = t.duration_since(UNIX_EPOCH).unwrap();
|
||||
duration_since_epoch.as_millis() as u64
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn metadata(path: PathBuf) -> Result<Metadata> {
|
||||
let metadata = std::fs::metadata(path)?;
|
||||
let file_type = metadata.file_type();
|
||||
let permissions = metadata.permissions();
|
||||
Ok(Metadata {
|
||||
accessed_at_ms: system_time_to_ms(metadata.accessed()),
|
||||
created_at_ms: system_time_to_ms(metadata.created()),
|
||||
modified_at_ms: system_time_to_ms(metadata.modified()),
|
||||
is_dir: file_type.is_dir(),
|
||||
is_file: file_type.is_file(),
|
||||
is_symlink: file_type.is_symlink(),
|
||||
size: metadata.len(),
|
||||
permissions: Permissions {
|
||||
readonly: permissions.readonly(),
|
||||
#[cfg(unix)]
|
||||
mode: permissions.mode(),
|
||||
},
|
||||
#[cfg(unix)]
|
||||
unix: UnixMetadata {
|
||||
dev: metadata.dev(),
|
||||
ino: metadata.ino(),
|
||||
mode: metadata.mode(),
|
||||
nlink: metadata.nlink(),
|
||||
uid: metadata.uid(),
|
||||
gid: metadata.gid(),
|
||||
rdev: metadata.rdev(),
|
||||
blksize: metadata.blksize(),
|
||||
blocks: metadata.blocks(),
|
||||
},
|
||||
#[cfg(windows)]
|
||||
file_attributes: metadata.file_attributes(),
|
||||
})
|
||||
}
|
||||
|
||||
// #[command]
|
||||
// pub async fn exists(path: PathBuf) -> bool {
|
||||
// path.exists()
|
||||
// }
|
||||
@ -1,305 +0,0 @@
|
||||
use crate::{
|
||||
app::{fs_extra, window},
|
||||
conf::GITHUB_PROMPTS_CSV_URL,
|
||||
utils,
|
||||
};
|
||||
use log::{error, info};
|
||||
use regex::Regex;
|
||||
use std::{collections::HashMap, fs, path::PathBuf, vec};
|
||||
use tauri::{api, command, AppHandle, Manager};
|
||||
use walkdir::WalkDir;
|
||||
|
||||
#[command]
|
||||
pub fn get_chat_prompt_cmd() -> serde_json::Value {
|
||||
let path = utils::app_root().join("chat.prompt.cmd.json");
|
||||
let content = fs::read_to_string(path).unwrap_or_else(|_| r#"{"data":[]}"#.to_string());
|
||||
serde_json::from_str(&content).unwrap()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PromptBaseRecord {
|
||||
pub cmd: Option<String>,
|
||||
pub act: String,
|
||||
pub prompt: String,
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn parse_prompt(data: String) -> Option<Vec<PromptBaseRecord>> {
|
||||
let mut rdr = csv::Reader::from_reader(data.as_bytes());
|
||||
let mut list = vec![];
|
||||
|
||||
for result in rdr.deserialize::<PromptBaseRecord>() {
|
||||
match result {
|
||||
Ok(record) => {
|
||||
if !record.act.is_empty() {
|
||||
list.push(record);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
error!("parse_prompt: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if list.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(list)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||
pub struct PromptRecord {
|
||||
pub cmd: String,
|
||||
pub act: String,
|
||||
pub prompt: String,
|
||||
pub tags: Vec<String>,
|
||||
pub enable: bool,
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn cmd_list() -> Vec<PromptRecord> {
|
||||
let mut list = vec![];
|
||||
for entry in WalkDir::new(utils::app_root().join("cache_prompts"))
|
||||
.into_iter()
|
||||
.filter_map(|e| e.ok())
|
||||
{
|
||||
let file = fs::read_to_string(entry.path().display().to_string());
|
||||
if let Ok(v) = file {
|
||||
let data: Vec<PromptRecord> = serde_json::from_str(&v).unwrap_or_else(|_| vec![]);
|
||||
let enable_list = data.into_iter().filter(|v| v.enable);
|
||||
list.extend(enable_list)
|
||||
}
|
||||
}
|
||||
// dbg!(&list);
|
||||
list.sort_by(|a, b| a.cmd.len().cmp(&b.cmd.len()));
|
||||
list
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||
pub struct FileMetadata {
|
||||
pub name: String,
|
||||
pub ext: String,
|
||||
pub created: u64,
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_download_list(pathname: &str) -> (Vec<serde_json::Value>, PathBuf) {
|
||||
info!("get_download_list: {}", pathname);
|
||||
let download_path = utils::app_root().join(PathBuf::from(pathname));
|
||||
let content = fs::read_to_string(&download_path).unwrap_or_else(|err| {
|
||||
error!("download_list: {}", err);
|
||||
fs::write(&download_path, "[]").unwrap();
|
||||
"[]".to_string()
|
||||
});
|
||||
let list = serde_json::from_str::<Vec<serde_json::Value>>(&content).unwrap_or_else(|err| {
|
||||
error!("download_list_parse: {}", err);
|
||||
vec![]
|
||||
});
|
||||
|
||||
(list, download_path)
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn download_list(pathname: &str, dir: &str, filename: Option<String>, id: Option<String>) {
|
||||
info!("download_list: {}", pathname);
|
||||
let data = get_download_list(pathname);
|
||||
let mut list = vec![];
|
||||
let mut idmap = HashMap::new();
|
||||
utils::vec_to_hashmap(data.0.into_iter(), "id", &mut idmap);
|
||||
|
||||
for entry in WalkDir::new(utils::app_root().join(dir))
|
||||
.into_iter()
|
||||
.filter_entry(|e| !utils::is_hidden(e))
|
||||
.filter_map(|e| e.ok())
|
||||
{
|
||||
let metadata = entry.metadata().unwrap();
|
||||
if metadata.is_file() {
|
||||
let file_path = entry.path().display().to_string();
|
||||
let re = Regex::new(r"(?P<id>[\d\w]+).(?P<ext>\w+)$").unwrap();
|
||||
let caps = re.captures(&file_path).unwrap();
|
||||
let fid = &caps["id"];
|
||||
let fext = &caps["ext"];
|
||||
|
||||
let mut file_data = FileMetadata {
|
||||
name: fid.to_string(),
|
||||
id: fid.to_string(),
|
||||
ext: fext.to_string(),
|
||||
created: fs_extra::system_time_to_ms(metadata.created()),
|
||||
};
|
||||
|
||||
if idmap.get(fid).is_some() {
|
||||
let name = idmap.get(fid).unwrap().get("name").unwrap().clone();
|
||||
match name {
|
||||
serde_json::Value::String(v) => {
|
||||
file_data.name = v.clone();
|
||||
v
|
||||
}
|
||||
_ => "".to_string(),
|
||||
};
|
||||
}
|
||||
|
||||
if filename.is_some() && id.is_some() {
|
||||
if let Some(ref v) = id {
|
||||
if fid == v {
|
||||
if let Some(ref v2) = filename {
|
||||
file_data.name = v2.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
list.push(serde_json::to_value(file_data).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
// dbg!(&list);
|
||||
list.sort_by(|a, b| {
|
||||
let a1 = a.get("created").unwrap().as_u64().unwrap();
|
||||
let b1 = b.get("created").unwrap().as_u64().unwrap();
|
||||
a1.cmp(&b1).reverse()
|
||||
});
|
||||
|
||||
fs::write(data.1, serde_json::to_string_pretty(&list).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn sync_prompts(app: AppHandle, time: u64) -> Option<Vec<PromptRecord>> {
|
||||
let res = utils::get_data(GITHUB_PROMPTS_CSV_URL, Some(&app))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
if let Some(v) = res {
|
||||
if let Some(data) = parse_prompt(v) {
|
||||
let transformed_data = data
|
||||
.iter()
|
||||
.map(|i| PromptRecord {
|
||||
cmd: if let Some(cmd) = &i.cmd {
|
||||
cmd.clone()
|
||||
} else {
|
||||
utils::gen_cmd(i.act.clone())
|
||||
},
|
||||
act: i.act.clone(),
|
||||
prompt: i.prompt.clone(),
|
||||
tags: vec!["awesome-chatgpt-prompts".to_string()],
|
||||
enable: true,
|
||||
})
|
||||
.collect::<Vec<PromptRecord>>();
|
||||
|
||||
let prompts = utils::app_root().join("chat.prompt.json");
|
||||
let prompt_cmd = utils::app_root().join("chat.prompt.cmd.json");
|
||||
let chatgpt_prompts = utils::app_root()
|
||||
.join("cache_prompts")
|
||||
.join("chatgpt_prompts.json");
|
||||
|
||||
if !utils::exists(&prompts) {
|
||||
fs::write(
|
||||
&prompts,
|
||||
serde_json::json!({
|
||||
"name": "ChatGPT Prompts",
|
||||
"link": "https://github.com/lencx/ChatGPT"
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// chatgpt_prompts.json
|
||||
fs::write(
|
||||
chatgpt_prompts,
|
||||
serde_json::to_string_pretty(&transformed_data).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let cmd_data = cmd_list();
|
||||
|
||||
// chat.prompt.cmd.json
|
||||
fs::write(
|
||||
prompt_cmd,
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"name": "ChatGPT CMD",
|
||||
"last_updated": time,
|
||||
"data": cmd_data,
|
||||
}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut kv = HashMap::new();
|
||||
kv.insert(
|
||||
"sync_prompts".to_string(),
|
||||
serde_json::json!({ "id": "chatgpt_prompts", "last_updated": time }),
|
||||
);
|
||||
let prompts_data = utils::merge(
|
||||
&serde_json::from_str(&fs::read_to_string(&prompts).unwrap()).unwrap(),
|
||||
&kv,
|
||||
);
|
||||
|
||||
// chat.prompt.json
|
||||
fs::write(
|
||||
prompts,
|
||||
serde_json::to_string_pretty(&prompts_data).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// refresh window
|
||||
api::dialog::message(
|
||||
app.get_window("core").as_ref(),
|
||||
"Sync Prompts",
|
||||
"Prompts data has been synchronized!",
|
||||
);
|
||||
window::cmd::window_reload(app.clone(), "core");
|
||||
window::cmd::window_reload(app, "tray");
|
||||
|
||||
return Some(transformed_data);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn sync_user_prompts(url: String, data_type: String) -> Option<Vec<PromptRecord>> {
|
||||
info!("sync_user_prompts: url => {}", url);
|
||||
let res = utils::get_data(&url, None).await.unwrap_or_else(|err| {
|
||||
error!("chatgpt_http: {}", err);
|
||||
None
|
||||
});
|
||||
|
||||
if let Some(v) = res {
|
||||
let data: Option<Vec<PromptBaseRecord>> = if data_type == "csv" {
|
||||
info!("chatgpt_http_csv_parse");
|
||||
parse_prompt(v)
|
||||
} else if data_type == "json" {
|
||||
info!("chatgpt_http_json_parse");
|
||||
match serde_json::from_str::<Vec<PromptBaseRecord>>(&v) {
|
||||
Ok(parsed) => Some(parsed),
|
||||
Err(err) => {
|
||||
error!("chatgpt_http_json_parse: {}", err);
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
error!("chatgpt_http_unknown_type");
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(base_records) = data {
|
||||
let data = base_records
|
||||
.iter()
|
||||
.map(|i| PromptRecord {
|
||||
cmd: i
|
||||
.cmd
|
||||
.clone()
|
||||
.unwrap_or_else(|| utils::gen_cmd(i.act.clone())),
|
||||
act: i.act.clone(),
|
||||
prompt: i.prompt.clone(),
|
||||
tags: vec!["user-sync".to_string()],
|
||||
enable: true,
|
||||
})
|
||||
.collect::<Vec<PromptRecord>>();
|
||||
|
||||
return Some(data);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
@ -1,476 +0,0 @@
|
||||
use crate::{
|
||||
app::window,
|
||||
conf::{self, AppConf},
|
||||
utils,
|
||||
};
|
||||
use tauri::{
|
||||
AppHandle, CustomMenuItem, Manager, Menu, MenuItem, Submenu, SystemTray, SystemTrayEvent,
|
||||
SystemTrayMenu, SystemTrayMenuItem, WindowMenuEvent,
|
||||
};
|
||||
use tauri_plugin_positioner::{on_tray_event, Position, WindowExt};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use tauri::AboutMetadata;
|
||||
|
||||
// --- Menu
|
||||
pub fn init() -> Menu {
|
||||
let app_conf = AppConf::read();
|
||||
let name = "ChatGPT";
|
||||
let app_menu = Submenu::new(
|
||||
name,
|
||||
Menu::with_items([
|
||||
#[cfg(target_os = "macos")]
|
||||
MenuItem::About(name.into(), AboutMetadata::default()).into(),
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
CustomMenuItem::new("about", "About ChatGPT").into(),
|
||||
CustomMenuItem::new("check_update", "Check for Updates").into(),
|
||||
MenuItem::Services.into(),
|
||||
MenuItem::Hide.into(),
|
||||
MenuItem::HideOthers.into(),
|
||||
MenuItem::ShowAll.into(),
|
||||
MenuItem::Separator.into(),
|
||||
MenuItem::Quit.into(),
|
||||
]),
|
||||
);
|
||||
|
||||
let stay_on_top = CustomMenuItem::new("stay_on_top", "Stay On Top").accelerator("CmdOrCtrl+T");
|
||||
let stay_on_top_menu = if app_conf.stay_on_top {
|
||||
stay_on_top.selected()
|
||||
} else {
|
||||
stay_on_top
|
||||
};
|
||||
|
||||
let theme_light = CustomMenuItem::new("theme_light", "Light");
|
||||
let theme_dark = CustomMenuItem::new("theme_dark", "Dark");
|
||||
let theme_system = CustomMenuItem::new("theme_system", "System");
|
||||
let is_dark = app_conf.clone().theme_check("dark");
|
||||
let is_system = app_conf.clone().theme_check("system");
|
||||
|
||||
let update_prompt = CustomMenuItem::new("update_prompt", "Prompt");
|
||||
let update_silent = CustomMenuItem::new("update_silent", "Silent");
|
||||
// let _update_disable = CustomMenuItem::new("update_disable", "Disable");
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
let titlebar = CustomMenuItem::new("titlebar", "Titlebar").accelerator("CmdOrCtrl+B");
|
||||
#[cfg(target_os = "macos")]
|
||||
let titlebar_menu = if app_conf.titlebar {
|
||||
titlebar.selected()
|
||||
} else {
|
||||
titlebar
|
||||
};
|
||||
|
||||
let system_tray = CustomMenuItem::new("system_tray", "System Tray");
|
||||
let system_tray_menu = if app_conf.tray {
|
||||
system_tray.selected()
|
||||
} else {
|
||||
system_tray
|
||||
};
|
||||
let hide_dock_icon = CustomMenuItem::new("hide_dock_icon", "Hide Dock Icon");
|
||||
let hide_dock_icon_menu = if app_conf.tray {
|
||||
hide_dock_icon
|
||||
} else {
|
||||
hide_dock_icon.disabled()
|
||||
};
|
||||
|
||||
let auto_update = app_conf.get_auto_update();
|
||||
let preferences_menu = Submenu::new(
|
||||
"Preferences",
|
||||
Menu::with_items([
|
||||
CustomMenuItem::new("control_center", "Control Center")
|
||||
.accelerator("CmdOrCtrl+Shift+P")
|
||||
.into(),
|
||||
MenuItem::Separator.into(),
|
||||
stay_on_top_menu.into(),
|
||||
#[cfg(target_os = "macos")]
|
||||
titlebar_menu.into(),
|
||||
#[cfg(target_os = "macos")]
|
||||
hide_dock_icon_menu.into(),
|
||||
system_tray_menu.into(),
|
||||
MenuItem::Separator.into(),
|
||||
Submenu::new(
|
||||
"Theme",
|
||||
Menu::new()
|
||||
.add_item(if is_dark || is_system {
|
||||
theme_light
|
||||
} else {
|
||||
theme_light.selected()
|
||||
})
|
||||
.add_item(if is_dark {
|
||||
theme_dark.selected()
|
||||
} else {
|
||||
theme_dark
|
||||
})
|
||||
.add_item(if is_system {
|
||||
theme_system.selected()
|
||||
} else {
|
||||
theme_system
|
||||
}),
|
||||
)
|
||||
.into(),
|
||||
Submenu::new(
|
||||
"Auto Update",
|
||||
Menu::new()
|
||||
.add_item(if auto_update == "prompt" {
|
||||
update_prompt.selected()
|
||||
} else {
|
||||
update_prompt
|
||||
})
|
||||
.add_item(if auto_update == "silent" {
|
||||
update_silent.selected()
|
||||
} else {
|
||||
update_silent
|
||||
}), // .add_item(if auto_update == "disable" {
|
||||
// update_disable.selected()
|
||||
// } else {
|
||||
// update_disable
|
||||
// })
|
||||
)
|
||||
.into(),
|
||||
MenuItem::Separator.into(),
|
||||
CustomMenuItem::new("sync_prompts", "Sync Prompts").into(),
|
||||
MenuItem::Separator.into(),
|
||||
CustomMenuItem::new("go_conf", "Go to Config")
|
||||
.accelerator("CmdOrCtrl+Shift+G")
|
||||
.into(),
|
||||
CustomMenuItem::new("restart", "Restart ChatGPT")
|
||||
.accelerator("CmdOrCtrl+Shift+R")
|
||||
.into(),
|
||||
CustomMenuItem::new("clear_conf", "Clear Config").into(),
|
||||
MenuItem::Separator.into(),
|
||||
CustomMenuItem::new("chatgpt_sponsors", "ChatGPT Sponsors").into(),
|
||||
MenuItem::Separator.into(),
|
||||
CustomMenuItem::new("nofwl", "NoFWL Desktop Application").into(),
|
||||
CustomMenuItem::new("sponsor", "Sponsor Author").into(),
|
||||
]),
|
||||
);
|
||||
|
||||
let edit_menu = Submenu::new(
|
||||
"Edit",
|
||||
Menu::new()
|
||||
.add_native_item(MenuItem::Undo)
|
||||
.add_native_item(MenuItem::Redo)
|
||||
.add_native_item(MenuItem::Separator)
|
||||
.add_native_item(MenuItem::Cut)
|
||||
.add_native_item(MenuItem::Copy)
|
||||
.add_native_item(MenuItem::Paste)
|
||||
.add_native_item(MenuItem::SelectAll),
|
||||
);
|
||||
|
||||
let view_menu = Submenu::new(
|
||||
"View",
|
||||
Menu::new()
|
||||
.add_item(CustomMenuItem::new("go_back", "Go Back").accelerator("CmdOrCtrl+["))
|
||||
.add_item(CustomMenuItem::new("go_forward", "Go Forward").accelerator("CmdOrCtrl+]"))
|
||||
.add_item(
|
||||
CustomMenuItem::new("scroll_top", "Scroll to Top of Screen").accelerator("CmdOrCtrl+Up"),
|
||||
)
|
||||
.add_item(
|
||||
CustomMenuItem::new("scroll_bottom", "Scroll to Bottom of Screen")
|
||||
.accelerator("CmdOrCtrl+Down"),
|
||||
)
|
||||
.add_native_item(MenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("zoom_0", "Zoom to Actual Size").accelerator("CmdOrCtrl+0"))
|
||||
.add_item(CustomMenuItem::new("zoom_out", "Zoom Out").accelerator("CmdOrCtrl+-"))
|
||||
.add_item(CustomMenuItem::new("zoom_in", "Zoom In").accelerator("CmdOrCtrl+Plus"))
|
||||
.add_native_item(MenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("reload", "Refresh the Screen").accelerator("CmdOrCtrl+R")),
|
||||
);
|
||||
|
||||
let window_menu = Submenu::new(
|
||||
"Window",
|
||||
Menu::new()
|
||||
.add_item(CustomMenuItem::new("app_website", "ChatGPT User's Guide"))
|
||||
.add_native_item(MenuItem::Separator)
|
||||
.add_native_item(MenuItem::Minimize)
|
||||
.add_native_item(MenuItem::Zoom),
|
||||
);
|
||||
|
||||
let help_menu = Submenu::new(
|
||||
"Help",
|
||||
Menu::new()
|
||||
.add_item(CustomMenuItem::new("chatgpt_log", "ChatGPT Log"))
|
||||
.add_item(CustomMenuItem::new("update_log", "Update Log"))
|
||||
.add_item(CustomMenuItem::new("report_bug", "Report Bug"))
|
||||
.add_item(
|
||||
CustomMenuItem::new("dev_tools", "Toggle Developer Tools").accelerator("CmdOrCtrl+Shift+I"),
|
||||
),
|
||||
);
|
||||
|
||||
Menu::new()
|
||||
.add_submenu(app_menu)
|
||||
.add_submenu(preferences_menu)
|
||||
.add_submenu(window_menu)
|
||||
.add_submenu(edit_menu)
|
||||
.add_submenu(view_menu)
|
||||
.add_submenu(help_menu)
|
||||
}
|
||||
|
||||
// --- Menu Event
|
||||
pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
|
||||
let win = Some(event.window()).unwrap();
|
||||
let app = win.app_handle();
|
||||
let menu_id = event.menu_item_id();
|
||||
let menu_handle = win.menu_handle();
|
||||
|
||||
match menu_id {
|
||||
// App
|
||||
"about" => {
|
||||
let tauri_conf = utils::get_tauri_conf().unwrap();
|
||||
tauri::api::dialog::message(
|
||||
app.get_window("core").as_ref(),
|
||||
"ChatGPT",
|
||||
format!("Version {}", tauri_conf.package.version.unwrap()),
|
||||
);
|
||||
}
|
||||
"check_update" => {
|
||||
utils::run_check_update(app, false, None);
|
||||
}
|
||||
// Preferences
|
||||
"control_center" => window::cmd::control_window(app, "control".into()),
|
||||
"restart" => tauri::api::process::restart(&app.env()),
|
||||
"go_conf" => utils::open_file(utils::app_root()),
|
||||
"clear_conf" => utils::clear_conf(&app),
|
||||
"app_website" => window::cmd::wa_window(
|
||||
app,
|
||||
"app_website".into(),
|
||||
"ChatGPT User's Guide".into(),
|
||||
conf::APP_WEBSITE.into(),
|
||||
None,
|
||||
),
|
||||
"nofwl" => open(&app, conf::NOFWL_APP),
|
||||
"chatgpt_sponsors" => window::cmd::wa_window(
|
||||
app,
|
||||
"chatgpt_sponsors".into(),
|
||||
"Sponsors".into(),
|
||||
conf::APP_SPONSORS.into(),
|
||||
None,
|
||||
),
|
||||
"sponsor" => window::sponsor_window(app),
|
||||
"sync_prompts" => {
|
||||
tauri::api::dialog::ask(
|
||||
app.get_window("core").as_ref(),
|
||||
"Sync Prompts",
|
||||
"Data sync will enable all prompts, are you sure you want to sync?",
|
||||
move |is_restart| {
|
||||
if is_restart {
|
||||
app
|
||||
.get_window("core")
|
||||
.unwrap()
|
||||
.eval("window.__sync_prompts && window.__sync_prompts()")
|
||||
.unwrap()
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
"hide_dock_icon" => {
|
||||
AppConf::read()
|
||||
.amend(serde_json::json!({ "hide_dock_icon": true }))
|
||||
.write()
|
||||
.restart(app);
|
||||
}
|
||||
"titlebar" => {
|
||||
let app_conf = AppConf::read();
|
||||
app_conf
|
||||
.clone()
|
||||
.amend(serde_json::json!({ "titlebar": !app_conf.titlebar }))
|
||||
.write()
|
||||
.restart(app);
|
||||
}
|
||||
"system_tray" => {
|
||||
let app_conf = AppConf::read();
|
||||
app_conf
|
||||
.clone()
|
||||
.amend(serde_json::json!({ "tray": !app_conf.tray }))
|
||||
.write()
|
||||
.restart(app);
|
||||
}
|
||||
"theme_light" | "theme_dark" | "theme_system" => {
|
||||
let theme = match menu_id {
|
||||
"theme_dark" => "dark",
|
||||
"theme_system" => "system",
|
||||
_ => "light",
|
||||
};
|
||||
AppConf::read()
|
||||
.amend(serde_json::json!({ "theme": theme }))
|
||||
.write()
|
||||
.restart(app);
|
||||
}
|
||||
"update_prompt" | "update_silent" | "update_disable" => {
|
||||
// for id in ["update_prompt", "update_silent", "update_disable"] {
|
||||
for id in ["update_prompt", "update_silent"] {
|
||||
menu_handle.get_item(id).set_selected(false).unwrap();
|
||||
}
|
||||
let auto_update = match menu_id {
|
||||
"update_silent" => {
|
||||
menu_handle
|
||||
.get_item("update_silent")
|
||||
.set_selected(true)
|
||||
.unwrap();
|
||||
"silent"
|
||||
}
|
||||
"update_disable" => {
|
||||
menu_handle
|
||||
.get_item("update_disable")
|
||||
.set_selected(true)
|
||||
.unwrap();
|
||||
"disable"
|
||||
}
|
||||
_ => {
|
||||
menu_handle
|
||||
.get_item("update_prompt")
|
||||
.set_selected(true)
|
||||
.unwrap();
|
||||
"prompt"
|
||||
}
|
||||
};
|
||||
AppConf::read()
|
||||
.amend(serde_json::json!({ "auto_update": auto_update }))
|
||||
.write();
|
||||
}
|
||||
"stay_on_top" => {
|
||||
let app_conf = AppConf::read();
|
||||
let stay_on_top = !app_conf.stay_on_top;
|
||||
menu_handle
|
||||
.get_item(menu_id)
|
||||
.set_selected(stay_on_top)
|
||||
.unwrap();
|
||||
win.set_always_on_top(stay_on_top).unwrap();
|
||||
app_conf
|
||||
.amend(serde_json::json!({ "stay_on_top": stay_on_top }))
|
||||
.write();
|
||||
}
|
||||
// View
|
||||
"zoom_0" => win.eval("window.__zoom0 && window.__zoom0()").unwrap(),
|
||||
"zoom_out" => win.eval("window.__zoomOut && window.__zoomOut()").unwrap(),
|
||||
"zoom_in" => win.eval("window.__zoomIn && window.__zoomIn()").unwrap(),
|
||||
"reload" => win.eval("window.location.reload()").unwrap(),
|
||||
"go_back" => win.eval("window.history.go(-1)").unwrap(),
|
||||
"go_forward" => win.eval("window.history.go(1)").unwrap(),
|
||||
"scroll_top" => win
|
||||
.eval(
|
||||
r#"window.scroll({
|
||||
top: 0,
|
||||
left: 0,
|
||||
behavior: "smooth"
|
||||
})"#,
|
||||
)
|
||||
.unwrap(),
|
||||
"scroll_bottom" => win
|
||||
.eval(
|
||||
r#"window.scroll({
|
||||
top: document.body.scrollHeight,
|
||||
left: 0,
|
||||
behavior: "smooth"})"#,
|
||||
)
|
||||
.unwrap(),
|
||||
// Help
|
||||
"chatgpt_log" => utils::open_file(utils::app_root().join("chatgpt.log")),
|
||||
"update_log" => open(&app, conf::UPDATE_LOG_URL),
|
||||
"report_bug" => open(&app, conf::ISSUES_URL),
|
||||
"dev_tools" => {
|
||||
win.open_devtools();
|
||||
win.close_devtools();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
// --- SystemTray Menu
|
||||
pub fn tray_menu() -> SystemTray {
|
||||
if cfg!(target_os = "macos") {
|
||||
let mut tray_menu = SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("control_center", "Control Center"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator);
|
||||
|
||||
if AppConf::read().hide_dock_icon {
|
||||
tray_menu = tray_menu.add_item(CustomMenuItem::new("show_dock_icon", "Show Dock Icon"));
|
||||
} else {
|
||||
tray_menu = tray_menu
|
||||
.add_item(CustomMenuItem::new("hide_dock_icon", "Hide Dock Icon"))
|
||||
.add_item(CustomMenuItem::new("show_core", "Show Window"));
|
||||
}
|
||||
|
||||
SystemTray::new().with_menu(
|
||||
tray_menu
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit", "Quit")),
|
||||
)
|
||||
} else {
|
||||
SystemTray::new().with_menu(
|
||||
SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("control_center", "Control Center"))
|
||||
.add_item(CustomMenuItem::new("show_core", "Show Window"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit", "Quit")),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// --- SystemTray Event
|
||||
pub fn tray_handler(handle: &AppHandle, event: SystemTrayEvent) {
|
||||
on_tray_event(handle, &event);
|
||||
|
||||
let app = handle.clone();
|
||||
|
||||
app
|
||||
.get_window("tray")
|
||||
.unwrap()
|
||||
.move_window(Position::TrayCenter)
|
||||
.unwrap();
|
||||
|
||||
match event {
|
||||
SystemTrayEvent::LeftClick { .. } => {
|
||||
let app_conf = AppConf::read();
|
||||
|
||||
if !app_conf.hide_dock_icon {
|
||||
if let Some(core_win) = handle.get_window("core") {
|
||||
core_win.minimize().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(tray_win) = handle.get_window("tray") {
|
||||
if tray_win.is_visible().unwrap() {
|
||||
tray_win.hide().unwrap();
|
||||
} else {
|
||||
tray_win.show().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
|
||||
"control_center" => window::cmd::control_window(app, "control".into()),
|
||||
"restart" => tauri::api::process::restart(&handle.env()),
|
||||
"show_dock_icon" => {
|
||||
AppConf::read()
|
||||
.amend(serde_json::json!({ "hide_dock_icon": false }))
|
||||
.write()
|
||||
.restart(app);
|
||||
}
|
||||
"hide_dock_icon" => {
|
||||
let app_conf = AppConf::read();
|
||||
if !app_conf.hide_dock_icon {
|
||||
app_conf
|
||||
.amend(serde_json::json!({ "hide_dock_icon": true }))
|
||||
.write()
|
||||
.restart(app);
|
||||
}
|
||||
}
|
||||
"show_core" => {
|
||||
if let Some(core_win) = app.get_window("core") {
|
||||
let tray_win = app.get_window("tray").unwrap();
|
||||
if !core_win.is_visible().unwrap() {
|
||||
core_win.show().unwrap();
|
||||
core_win.set_focus().unwrap();
|
||||
tray_win.hide().unwrap();
|
||||
}
|
||||
};
|
||||
}
|
||||
"quit" => std::process::exit(0),
|
||||
_ => (),
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open(app: &AppHandle, path: &str) {
|
||||
tauri::api::shell::open(&app.shell_scope(), path, None).unwrap();
|
||||
}
|
||||
@ -1,8 +0,0 @@
|
||||
pub mod cmd;
|
||||
pub mod fs_extra;
|
||||
pub mod gpt;
|
||||
pub mod menu;
|
||||
pub mod script;
|
||||
pub mod setup;
|
||||
pub mod template;
|
||||
pub mod window;
|
||||
@ -1,191 +0,0 @@
|
||||
use crate::utils::{app_root, create_file, exists};
|
||||
use log::error;
|
||||
use log::info;
|
||||
use regex::Regex;
|
||||
use serde_json::{from_str, json, Value};
|
||||
use std::fs;
|
||||
use tauri::Manager;
|
||||
|
||||
use crate::{conf::SCRIPTS_DIR, window};
|
||||
|
||||
pub async fn init_script(app: tauri::AppHandle) -> anyhow::Result<(), reqwest::Error> {
|
||||
let body = reqwest::get(format!("{}{}", SCRIPTS_DIR, "manifest.json"))
|
||||
.await?
|
||||
.text()
|
||||
.await?;
|
||||
|
||||
if exist_scripts("manifest.json".into()) {
|
||||
let compare = compare_nested_json_objects(
|
||||
&fs::read_to_string(app_root().join("scripts").join("manifest.json")).unwrap(),
|
||||
&body,
|
||||
);
|
||||
if !compare {
|
||||
info!("update_scripts_manifest");
|
||||
create_chatgpt_scripts("manifest.json".into(), body);
|
||||
|
||||
if let Some(v) = app.get_window("core") {
|
||||
tauri::api::dialog::ask(Some(&v), "Scripts Update", "There are new available scripts. Please go to 'Preferences -> Control Center -> Scripts' to check for updates.", |is_ok| {
|
||||
if is_ok {
|
||||
info!("update_scripts_manifest_ok");
|
||||
// TODO: goto scripts page
|
||||
window::cmd::control_window(app, "scripts".into())
|
||||
} else {
|
||||
info!("update_scripts_manifest_cancel");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
create_chatgpt_scripts("manifest.json".into(), body);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn parse_script(name: String) -> Option<serde_json::Value> {
|
||||
let script_file = app_root().join("scripts").join(name);
|
||||
let code = match fs::read_to_string(&script_file) {
|
||||
Ok(content) => content,
|
||||
Err(_) => {
|
||||
error!("parse_script_error: {}", script_file.display());
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// let code = &fs::read_to_string(name).unwrap();
|
||||
let re_name = Regex::new(r"@name\s+(.*?)\n").unwrap();
|
||||
let re_version = Regex::new(r"@version\s+(.*?)\n").unwrap();
|
||||
let re_url = Regex::new(r"@url\s+(.*?)\n").unwrap();
|
||||
|
||||
let mut name = String::new();
|
||||
let mut version = String::new();
|
||||
let mut url = String::new();
|
||||
|
||||
if let Some(capture) = re_name.captures(&code) {
|
||||
name = capture.get(1).unwrap().as_str().trim().to_owned();
|
||||
}
|
||||
|
||||
if let Some(capture) = re_version.captures(&code) {
|
||||
version = capture.get(1).unwrap().as_str().trim().to_owned();
|
||||
}
|
||||
|
||||
if let Some(capture) = re_url.captures(&code) {
|
||||
url = capture.get(1).unwrap().as_str().trim().to_owned();
|
||||
}
|
||||
|
||||
let json_data = json!({
|
||||
"name": name,
|
||||
"version": version,
|
||||
"url": url,
|
||||
});
|
||||
|
||||
Some(json_data)
|
||||
}
|
||||
|
||||
pub fn exist_scripts(file: String) -> bool {
|
||||
let script_file = app_root().join("scripts").join(file);
|
||||
exists(&script_file)
|
||||
}
|
||||
|
||||
pub fn create_chatgpt_scripts(file: String, body: String) {
|
||||
let script_file = app_root().join("scripts").join(file);
|
||||
match create_file(&script_file) {
|
||||
Ok(_) => {
|
||||
info!("script_file: {:?}", script_file);
|
||||
fs::write(&script_file, body).unwrap();
|
||||
}
|
||||
Err(e) => {
|
||||
error!("create_file, {}: {}", script_file.display(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compare_nested_json_objects(json1: &str, json2: &str) -> bool {
|
||||
let value1: Value = from_str(json1).unwrap_or_else(|err| {
|
||||
error!("json_parse_1_error: {}", err);
|
||||
json!({})
|
||||
});
|
||||
let value2: Value = from_str(json2).unwrap_or_else(|err| {
|
||||
error!("json_parse_2_error: {}", err);
|
||||
json!({})
|
||||
});
|
||||
|
||||
compare_json_objects(&value1, &value2)
|
||||
}
|
||||
|
||||
pub fn compare_json_objects(obj1: &Value, obj2: &Value) -> bool {
|
||||
match (obj1, obj2) {
|
||||
(Value::Object(obj1), Value::Object(obj2)) => {
|
||||
if obj1.len() != obj2.len() {
|
||||
return false;
|
||||
}
|
||||
for (key, value) in obj1 {
|
||||
if !obj2.contains_key(key) || !compare_json_objects(value, obj2.get(key).unwrap()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
(Value::Array(arr1), Value::Array(arr2)) => {
|
||||
if arr1.len() != arr2.len() {
|
||||
return false;
|
||||
}
|
||||
for (value1, value2) in arr1.iter().zip(arr2.iter()) {
|
||||
if !compare_json_objects(value1, value2) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => obj1 == obj2,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod cmd {
|
||||
use super::{create_chatgpt_scripts, parse_script};
|
||||
use crate::conf::SCRIPTS_DIR;
|
||||
use log::{error, info};
|
||||
use tauri::Manager;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_script_info(name: String) -> Option<serde_json::Value> {
|
||||
parse_script(name)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn sync_scripts(app: tauri::AppHandle, name: String) -> bool {
|
||||
let res = reqwest::get(format!("{}{}", SCRIPTS_DIR, name)).await;
|
||||
|
||||
info!("sync_scripts: {}", name);
|
||||
let body = match res {
|
||||
Ok(response) => match response.text().await {
|
||||
Ok(text) => text,
|
||||
Err(err) => {
|
||||
error!("sync_scripts_result_error: {}", err);
|
||||
if let Some(v) = app.get_window("core") {
|
||||
tauri::api::dialog::message(
|
||||
Some(&v),
|
||||
"Sync Scripts Error",
|
||||
format!("sync_scripts_result_error: {}", err),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
error!("sync_scripts_response_error: {}", err);
|
||||
if let Some(v) = app.get_window("core") {
|
||||
tauri::api::dialog::message(
|
||||
Some(&v),
|
||||
"Sync Scripts Error",
|
||||
format!("sync_scripts_response_error: {}", err),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
create_chatgpt_scripts(name, body);
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@ -1,119 +0,0 @@
|
||||
use crate::{
|
||||
app,
|
||||
conf::AppConf,
|
||||
utils::{self, load_script},
|
||||
};
|
||||
use log::{error, info};
|
||||
use tauri::{utils::config::WindowUrl, window::WindowBuilder, App, GlobalShortcutManager, Manager};
|
||||
use wry::application::accelerator::Accelerator;
|
||||
|
||||
pub fn init(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
|
||||
info!("stepup");
|
||||
|
||||
let app_conf = AppConf::read();
|
||||
let url = app_conf.main_origin.to_string();
|
||||
let theme = AppConf::theme_mode();
|
||||
|
||||
app::template::Template::new(utils::app_root().join("scripts"));
|
||||
|
||||
let handle = app.app_handle();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
app::script::init_script(handle)
|
||||
.await
|
||||
.unwrap_or_else(|err| {
|
||||
error!("script_init_error: {}", err);
|
||||
});
|
||||
});
|
||||
|
||||
let handle = app.app_handle();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
info!("stepup_tray");
|
||||
app::window::tray_window(&handle);
|
||||
});
|
||||
|
||||
if let Some(v) = app_conf.clone().global_shortcut {
|
||||
info!("global_shortcut: `{}`", v);
|
||||
match v.parse::<Accelerator>() {
|
||||
Ok(_) => {
|
||||
info!("global_shortcut_register");
|
||||
let handle = app.app_handle();
|
||||
let mut shortcut = app.global_shortcut_manager();
|
||||
shortcut
|
||||
.register(&v, move || {
|
||||
if let Some(w) = handle.get_window("core") {
|
||||
if w.is_visible().unwrap() {
|
||||
w.hide().unwrap();
|
||||
} else {
|
||||
w.show().unwrap();
|
||||
w.set_focus().unwrap();
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|err| {
|
||||
error!("global_shortcut_register_error: {}", err);
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
error!("global_shortcut_parse_error: {}", err);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
info!("global_shortcut_unregister");
|
||||
};
|
||||
|
||||
let app_conf2 = app_conf.clone();
|
||||
if app_conf.hide_dock_icon {
|
||||
#[cfg(target_os = "macos")]
|
||||
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
|
||||
} else {
|
||||
let app = app.handle();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let url2 = &url;
|
||||
let mut main_win = WindowBuilder::new(&app, "core", WindowUrl::App(url2.into()))
|
||||
.title("ChatGPT")
|
||||
.resizable(true)
|
||||
.fullscreen(false)
|
||||
.inner_size(app_conf2.main_width, app_conf2.main_height)
|
||||
.theme(Some(theme))
|
||||
.always_on_top(app_conf2.stay_on_top)
|
||||
.initialization_script(&utils::user_script())
|
||||
.initialization_script(&load_script("core.js"))
|
||||
.user_agent(&app_conf2.ua_window);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
main_win = main_win
|
||||
.title_bar_style(app_conf2.clone().titlebar())
|
||||
.hidden_title(true);
|
||||
}
|
||||
|
||||
if url == "https://chat.openai.com" {
|
||||
main_win = main_win
|
||||
.initialization_script(include_str!("../vendors/floating-ui-core.js"))
|
||||
.initialization_script(include_str!("../vendors/floating-ui-dom.js"))
|
||||
.initialization_script(include_str!("../vendors/html2canvas.js"))
|
||||
.initialization_script(include_str!("../vendors/jspdf.js"))
|
||||
.initialization_script(include_str!("../vendors/turndown.js"))
|
||||
.initialization_script(include_str!("../vendors/turndown-plugin-gfm.js"))
|
||||
.initialization_script(&load_script("export.js"))
|
||||
.initialization_script(&load_script("markdown.export.js"))
|
||||
.initialization_script(&load_script("cmd.js"))
|
||||
.initialization_script(&load_script("chat.js"))
|
||||
}
|
||||
|
||||
if let Err(err) = main_win.build() {
|
||||
error!("core_build_error: {}", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// auto_update
|
||||
let auto_update = app_conf.get_auto_update();
|
||||
if auto_update != "disable" {
|
||||
info!("run_check_update");
|
||||
let app = app.handle();
|
||||
utils::run_check_update(app, auto_update == "silent", None);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@ -1,102 +0,0 @@
|
||||
use anyhow::Result;
|
||||
use log::{error, info};
|
||||
use std::{
|
||||
fs::{self, File},
|
||||
io::Write,
|
||||
path::Path,
|
||||
};
|
||||
|
||||
pub static SCRIPT_MAIN: &[u8] = include_bytes!("../../../scripts/main.js");
|
||||
pub static SCRIPT_CORE: &[u8] = include_bytes!("../../../scripts/core.js");
|
||||
pub static SCRIPT_CHAT: &[u8] = include_bytes!("../../../scripts/chat.js");
|
||||
pub static SCRIPT_CMD: &[u8] = include_bytes!("../../../scripts/cmd.js");
|
||||
pub static SCRIPT_EXPORT: &[u8] = include_bytes!("../../../scripts/export.js");
|
||||
pub static SCRIPT_MD_EXPORT: &[u8] = include_bytes!("../../../scripts/markdown.export.js");
|
||||
pub static SCRIPT_MANIFEST: &[u8] = include_bytes!("../../../scripts/manifest.json");
|
||||
pub static SCRIPT_README: &[u8] = include_bytes!("../../../scripts/README.md");
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Template {
|
||||
pub main: Vec<u8>,
|
||||
pub core: Vec<u8>,
|
||||
pub chat: Vec<u8>,
|
||||
pub cmd: Vec<u8>,
|
||||
pub export: Vec<u8>,
|
||||
pub markdown_export: Vec<u8>,
|
||||
pub manifest: Vec<u8>,
|
||||
pub readme: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Template {
|
||||
pub fn new<P: AsRef<Path>>(template_dir: P) -> Self {
|
||||
let template_dir = template_dir.as_ref();
|
||||
let mut template = Template::default();
|
||||
|
||||
{
|
||||
let files = vec![
|
||||
(template_dir.join("main.js"), &mut template.main),
|
||||
(template_dir.join("core.js"), &mut template.core),
|
||||
(template_dir.join("chat.js"), &mut template.chat),
|
||||
(template_dir.join("cmd.js"), &mut template.cmd),
|
||||
(template_dir.join("export.js"), &mut template.export),
|
||||
(
|
||||
template_dir.join("markdown.export.js"),
|
||||
&mut template.markdown_export,
|
||||
),
|
||||
(template_dir.join("README.md"), &mut template.readme),
|
||||
(template_dir.join("manifest.json"), &mut template.manifest),
|
||||
];
|
||||
|
||||
for (filename, dest) in files {
|
||||
if !filename.exists() {
|
||||
match create_dir(&filename) {
|
||||
Ok(_) => {
|
||||
if let Err(e) = write_file_contents(&filename, dest) {
|
||||
error!("write_script, {}: {}", filename.display(), e);
|
||||
} else {
|
||||
info!("write_script: {}", filename.display());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!("create_file, {}: {}", filename.display(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Template {
|
||||
fn default() -> Template {
|
||||
Template {
|
||||
main: Vec::from(SCRIPT_MAIN),
|
||||
core: Vec::from(SCRIPT_CORE),
|
||||
chat: Vec::from(SCRIPT_CHAT),
|
||||
cmd: Vec::from(SCRIPT_CMD),
|
||||
export: Vec::from(SCRIPT_EXPORT),
|
||||
markdown_export: Vec::from(SCRIPT_MD_EXPORT),
|
||||
manifest: Vec::from(SCRIPT_MANIFEST),
|
||||
readme: Vec::from(SCRIPT_README),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create_dir<P: AsRef<Path>>(filename: P) -> Result<()> {
|
||||
let filename = filename.as_ref();
|
||||
if let Some(parent) = filename.parent() {
|
||||
if !parent.exists() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_file_contents<P: AsRef<Path>>(filename: P, data: &[u8]) -> Result<()> {
|
||||
let filename = filename.as_ref();
|
||||
let mut file = File::create(filename)?;
|
||||
file.write_all(data)?;
|
||||
Ok(())
|
||||
}
|
||||
@ -1,127 +0,0 @@
|
||||
use crate::{
|
||||
conf::AppConf,
|
||||
utils::{self, load_script},
|
||||
};
|
||||
use tauri::{utils::config::WindowUrl, window::WindowBuilder, Manager};
|
||||
|
||||
pub fn tray_window(handle: &tauri::AppHandle) {
|
||||
let app_conf = AppConf::read();
|
||||
let theme = AppConf::theme_mode();
|
||||
let app = handle.clone();
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let link = if app_conf.tray_dashboard {
|
||||
"index.html"
|
||||
} else {
|
||||
&app_conf.tray_origin
|
||||
};
|
||||
let mut tray_win = WindowBuilder::new(&app, "tray", WindowUrl::App(link.into()))
|
||||
.title("ChatGPT")
|
||||
.resizable(false)
|
||||
.fullscreen(false)
|
||||
.inner_size(app_conf.tray_width, app_conf.tray_height)
|
||||
.decorations(false)
|
||||
.always_on_top(true)
|
||||
.theme(Some(theme))
|
||||
.initialization_script(&utils::user_script())
|
||||
.initialization_script(&load_script("core.js"))
|
||||
.user_agent(&app_conf.ua_tray);
|
||||
|
||||
if app_conf.tray_origin == "https://chat.openai.com" && !app_conf.tray_dashboard {
|
||||
tray_win = tray_win
|
||||
.initialization_script(include_str!("../vendors/floating-ui-core.js"))
|
||||
.initialization_script(include_str!("../vendors/floating-ui-dom.js"))
|
||||
.initialization_script(&load_script("cmd.js"))
|
||||
.initialization_script(&load_script("chat.js"))
|
||||
}
|
||||
|
||||
tray_win.build().unwrap().hide().unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
pub fn sponsor_window(handle: tauri::AppHandle) {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if let Some(win) = handle.get_window("sponsor") {
|
||||
win.show().unwrap()
|
||||
} else {
|
||||
WindowBuilder::new(&handle, "sponsor", WindowUrl::App("sponsor.html".into()))
|
||||
.title("Sponsor")
|
||||
.resizable(true)
|
||||
.fullscreen(false)
|
||||
.inner_size(600.0, 600.0)
|
||||
.min_inner_size(600.0, 600.0)
|
||||
.build()
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub mod cmd {
|
||||
use super::*;
|
||||
use log::info;
|
||||
use tauri::{command, utils::config::WindowUrl, window::WindowBuilder, Manager};
|
||||
|
||||
#[tauri::command]
|
||||
pub fn control_window(handle: tauri::AppHandle, win_type: String) {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if handle.get_window("main").is_none() {
|
||||
WindowBuilder::new(
|
||||
&handle,
|
||||
"main",
|
||||
WindowUrl::App(format!("index.html?type={}", win_type).into()),
|
||||
)
|
||||
.title("Control Center")
|
||||
.resizable(true)
|
||||
.fullscreen(false)
|
||||
.inner_size(1200.0, 700.0)
|
||||
.min_inner_size(1000.0, 600.0)
|
||||
.build()
|
||||
.unwrap();
|
||||
} else {
|
||||
let main_win = handle.get_window("main").unwrap();
|
||||
main_win.show().unwrap();
|
||||
main_win.set_focus().unwrap();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn wa_window(
|
||||
app: tauri::AppHandle,
|
||||
label: String,
|
||||
title: String,
|
||||
url: String,
|
||||
script: Option<String>,
|
||||
) {
|
||||
info!("wa_window: {} :=> {}", title, url);
|
||||
let win = app.get_window(&label);
|
||||
if win.is_none() {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
tauri::WindowBuilder::new(&app, label, tauri::WindowUrl::App(url.parse().unwrap()))
|
||||
.initialization_script(&script.unwrap_or_default())
|
||||
.initialization_script(&load_script("core.js"))
|
||||
.title(title)
|
||||
.inner_size(960.0, 700.0)
|
||||
.resizable(true)
|
||||
.build()
|
||||
.unwrap();
|
||||
});
|
||||
} else if let Some(v) = win {
|
||||
if !v.is_visible().unwrap() {
|
||||
v.show().unwrap();
|
||||
}
|
||||
v.eval("window.location.reload()").unwrap();
|
||||
v.set_focus().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn window_reload(app: tauri::AppHandle, label: &str) {
|
||||
app
|
||||
.app_handle()
|
||||
.get_window(label)
|
||||
.unwrap()
|
||||
.eval("window.location.reload()")
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
@ -1,245 +0,0 @@
|
||||
use log::{error, info};
|
||||
use serde_json::Value;
|
||||
use std::{collections::BTreeMap, path::PathBuf};
|
||||
use tauri::{Manager, Theme};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use tauri::TitleBarStyle;
|
||||
|
||||
use crate::utils::{app_root, create_file, exists};
|
||||
|
||||
pub const APP_WEBSITE: &str = "https://lencx.github.io/app/";
|
||||
pub const APP_SPONSORS: &str = "https://lencx.github.io/app/sponsors";
|
||||
pub const ISSUES_URL: &str = "https://github.com/lencx/ChatGPT/issues";
|
||||
pub const NOFWL_APP: &str = "https://github.com/lencx/nofwl";
|
||||
pub const UPDATE_LOG_URL: &str = "https://github.com/lencx/ChatGPT/blob/main/UPDATE_LOG.md";
|
||||
// pub const BUY_COFFEE: &str = "https://www.buymeacoffee.com/lencx";
|
||||
pub const GITHUB_PROMPTS_CSV_URL: &str =
|
||||
"https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv";
|
||||
pub const SCRIPTS_DIR: &str = "https://raw.githubusercontent.com/lencx/ChatGPT/main/scripts/";
|
||||
|
||||
pub const APP_CONF_PATH: &str = "chat.conf.json";
|
||||
pub const CHATGPT_URL: &str = "https://chat.openai.com";
|
||||
pub const UA_MOBILE: &str = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1";
|
||||
|
||||
macro_rules! pub_struct {
|
||||
($name:ident {$($field:ident: $t:ty,)*}) => {
|
||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||
pub struct $name {
|
||||
$(pub $field: $t),*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub_struct!(AppConf {
|
||||
titlebar: bool,
|
||||
hide_dock_icon: bool,
|
||||
// macOS and Windows: light / dark / system
|
||||
theme: String,
|
||||
// auto update policy: prompt / silent / disable
|
||||
auto_update: String,
|
||||
stay_on_top: bool,
|
||||
save_window_state: bool,
|
||||
global_shortcut: Option<String>,
|
||||
default_origin: String,
|
||||
|
||||
// Main Window
|
||||
isinit: bool,
|
||||
main_close: bool,
|
||||
main_dashboard: bool,
|
||||
main_origin: String,
|
||||
ua_window: String,
|
||||
main_width: f64,
|
||||
main_height: f64,
|
||||
|
||||
// Tray Window
|
||||
tray_width: f64,
|
||||
tray_height: f64,
|
||||
tray: bool,
|
||||
tray_dashboard: bool,
|
||||
tray_origin: String,
|
||||
ua_tray: String,
|
||||
});
|
||||
|
||||
impl AppConf {
|
||||
pub fn new() -> Self {
|
||||
info!("conf_init");
|
||||
Self {
|
||||
titlebar: !cfg!(target_os = "macos"),
|
||||
hide_dock_icon: false,
|
||||
save_window_state: true,
|
||||
theme: "light".into(),
|
||||
auto_update: "prompt".into(),
|
||||
tray: true,
|
||||
isinit: true,
|
||||
main_close: false,
|
||||
stay_on_top: false,
|
||||
main_dashboard: false,
|
||||
tray_dashboard: false,
|
||||
main_width: 800.0,
|
||||
main_height: 600.0,
|
||||
tray_width: 360.0,
|
||||
tray_height: 540.0,
|
||||
main_origin: CHATGPT_URL.into(),
|
||||
tray_origin: CHATGPT_URL.into(),
|
||||
default_origin: CHATGPT_URL.into(),
|
||||
ua_tray: UA_MOBILE.into(),
|
||||
ua_window: "".into(),
|
||||
global_shortcut: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn file_path() -> PathBuf {
|
||||
app_root().join(APP_CONF_PATH)
|
||||
}
|
||||
|
||||
pub fn read() -> Self {
|
||||
match std::fs::read_to_string(Self::file_path()) {
|
||||
Ok(v) => {
|
||||
if let Ok(v2) = serde_json::from_str::<AppConf>(&v) {
|
||||
v2
|
||||
} else {
|
||||
error!("conf_read_parse_error");
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
error!("conf_read_error: {}", err);
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(self) -> Self {
|
||||
let path = &Self::file_path();
|
||||
if !exists(path) {
|
||||
create_file(path).unwrap();
|
||||
info!("conf_create");
|
||||
}
|
||||
if let Ok(v) = serde_json::to_string_pretty(&self) {
|
||||
std::fs::write(path, v).unwrap_or_else(|err| {
|
||||
error!("conf_write: {}", err);
|
||||
Self::default().write();
|
||||
});
|
||||
} else {
|
||||
error!("conf_ser");
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn amend(self, json: Value) -> Self {
|
||||
let val = serde_json::to_value(&self).unwrap();
|
||||
let mut config: BTreeMap<String, Value> = serde_json::from_value(val).unwrap();
|
||||
let new_json: BTreeMap<String, Value> = serde_json::from_value(json).unwrap();
|
||||
|
||||
for (k, v) in new_json {
|
||||
config.insert(k, v);
|
||||
}
|
||||
|
||||
match serde_json::to_string_pretty(&config) {
|
||||
Ok(v) => match serde_json::from_str::<AppConf>(&v) {
|
||||
Ok(v) => v,
|
||||
Err(err) => {
|
||||
error!("conf_amend_parse: {}", err);
|
||||
self
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
error!("conf_amend_str: {}", err);
|
||||
self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn titlebar(self) -> TitleBarStyle {
|
||||
if self.titlebar {
|
||||
TitleBarStyle::Transparent
|
||||
} else {
|
||||
TitleBarStyle::Overlay
|
||||
}
|
||||
}
|
||||
|
||||
pub fn theme_mode() -> Theme {
|
||||
match Self::get_theme().as_str() {
|
||||
"system" => match dark_light::detect() {
|
||||
// Dark mode
|
||||
dark_light::Mode::Dark => Theme::Dark,
|
||||
// Light mode
|
||||
dark_light::Mode::Light => Theme::Light,
|
||||
// Unspecified
|
||||
dark_light::Mode::Default => Theme::Light,
|
||||
},
|
||||
"dark" => Theme::Dark,
|
||||
_ => Theme::Light,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_theme() -> String {
|
||||
Self::read().theme.to_lowercase()
|
||||
}
|
||||
|
||||
pub fn get_auto_update(self) -> String {
|
||||
self.auto_update.to_lowercase()
|
||||
}
|
||||
|
||||
pub fn theme_check(self, mode: &str) -> bool {
|
||||
self.theme.to_lowercase() == mode
|
||||
}
|
||||
|
||||
pub fn restart(self, app: tauri::AppHandle) {
|
||||
tauri::api::process::restart(&app.env());
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AppConf {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub mod cmd {
|
||||
use super::AppConf;
|
||||
use tauri::{command, AppHandle, Manager};
|
||||
|
||||
#[command]
|
||||
pub fn get_app_conf() -> AppConf {
|
||||
AppConf::read()
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn reset_app_conf() -> AppConf {
|
||||
AppConf::default().write()
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn get_theme() -> String {
|
||||
AppConf::get_theme()
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn form_confirm(_app: AppHandle, data: serde_json::Value) {
|
||||
AppConf::read().amend(serde_json::json!(data)).write();
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn form_cancel(app: AppHandle, label: &str, title: &str, msg: &str) {
|
||||
let win = app.app_handle().get_window(label).unwrap();
|
||||
tauri::api::dialog::ask(
|
||||
app.app_handle().get_window(label).as_ref(),
|
||||
title,
|
||||
msg,
|
||||
move |is_cancel| {
|
||||
if is_cancel {
|
||||
win.close().unwrap();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn form_msg(app: AppHandle, label: &str, title: &str, msg: &str) {
|
||||
let win = app.app_handle().get_window(label);
|
||||
tauri::api::dialog::message(win.as_ref(), title, msg);
|
||||
}
|
||||
}
|
||||
161
src-tauri/src/core/cmd.rs
Normal file
@ -0,0 +1,161 @@
|
||||
use tauri::{command, AppHandle, LogicalPosition, Manager, PhysicalSize};
|
||||
|
||||
use crate::core::{
|
||||
conf::AppConf,
|
||||
constant::{ASK_HEIGHT, TITLEBAR_HEIGHT},
|
||||
};
|
||||
|
||||
#[command]
|
||||
pub fn view_reload(app: AppHandle) {
|
||||
app.get_window("core")
|
||||
.unwrap()
|
||||
.get_webview("main")
|
||||
.unwrap()
|
||||
.eval("window.location.reload()")
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn view_url(app: AppHandle) -> tauri::Url {
|
||||
app.get_window("core")
|
||||
.unwrap()
|
||||
.get_webview("main")
|
||||
.unwrap()
|
||||
.url()
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn view_go_forward(app: AppHandle) {
|
||||
app.get_window("core")
|
||||
.unwrap()
|
||||
.get_webview("main")
|
||||
.unwrap()
|
||||
.eval("window.history.forward()")
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn view_go_back(app: AppHandle) {
|
||||
app.get_window("core")
|
||||
.unwrap()
|
||||
.get_webview("main")
|
||||
.unwrap()
|
||||
.eval("window.history.back()")
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn window_pin(app: AppHandle, pin: bool) {
|
||||
let conf = AppConf::load(&app).unwrap();
|
||||
conf.amend(serde_json::json!({"stay_on_top": pin}))
|
||||
.unwrap()
|
||||
.save(&app)
|
||||
.unwrap();
|
||||
|
||||
app.get_window("core")
|
||||
.unwrap()
|
||||
.set_always_on_top(pin)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn ask_sync(app: AppHandle, message: String) {
|
||||
app.get_window("core")
|
||||
.unwrap()
|
||||
.get_webview("main")
|
||||
.unwrap()
|
||||
.eval(&format!("ChatAsk.sync({})", message))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn ask_send(app: AppHandle) {
|
||||
app.get_window("core")
|
||||
.unwrap()
|
||||
.get_webview("main")
|
||||
.unwrap()
|
||||
.eval("ChatAsk.submit()")
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn set_theme(app: AppHandle, theme: String) {
|
||||
let conf = AppConf::load(&app).unwrap();
|
||||
conf.amend(serde_json::json!({"theme": theme}))
|
||||
.unwrap()
|
||||
.save(&app)
|
||||
.unwrap();
|
||||
|
||||
app.restart();
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn get_app_conf(app: AppHandle) -> AppConf {
|
||||
AppConf::load(&app).unwrap()
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn set_view_ask(app: AppHandle, enabled: bool) {
|
||||
let conf = AppConf::load(&app).unwrap();
|
||||
conf.amend(serde_json::json!({"ask_mode": enabled}))
|
||||
.unwrap()
|
||||
.save(&app)
|
||||
.unwrap();
|
||||
|
||||
let core_window = app.get_window("core").unwrap();
|
||||
let ask_mode_height = if enabled { ASK_HEIGHT } else { 0.0 };
|
||||
let scale_factor = core_window.scale_factor().unwrap();
|
||||
let titlebar_height = (scale_factor * TITLEBAR_HEIGHT).round() as u32;
|
||||
let ask_height = (scale_factor * ask_mode_height).round() as u32;
|
||||
let win_size = core_window.inner_size().expect("Failed to get window size");
|
||||
let main_area_height = core_window.inner_size().unwrap().height - titlebar_height;
|
||||
|
||||
let main_view = core_window
|
||||
.get_webview("main")
|
||||
.expect("[view:main] Failed to get webview window");
|
||||
let titlebar_view = core_window
|
||||
.get_webview("titlebar")
|
||||
.expect("[view:titlebar] Failed to get webview window");
|
||||
let ask_view = core_window
|
||||
.get_webview("ask")
|
||||
.expect("[view:ask] Failed to get webview window");
|
||||
|
||||
if enabled {
|
||||
ask_view.set_focus().unwrap();
|
||||
} else {
|
||||
main_view.set_focus().unwrap();
|
||||
}
|
||||
|
||||
main_view
|
||||
.set_position(LogicalPosition::new(0.0, TITLEBAR_HEIGHT))
|
||||
.unwrap();
|
||||
main_view
|
||||
.set_size(PhysicalSize::new(
|
||||
core_window.inner_size().unwrap().width,
|
||||
main_area_height - ask_height,
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
titlebar_view
|
||||
.set_position(LogicalPosition::new(0, 0))
|
||||
.unwrap();
|
||||
titlebar_view
|
||||
.set_size(PhysicalSize::new(
|
||||
core_window.inner_size().unwrap().width,
|
||||
titlebar_height,
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
ask_view
|
||||
.set_position(LogicalPosition::new(
|
||||
0.0,
|
||||
(win_size.height as f64 / scale_factor) - ask_mode_height,
|
||||
))
|
||||
.unwrap();
|
||||
ask_view
|
||||
.set_size(PhysicalSize::new(
|
||||
core_window.inner_size().unwrap().width,
|
||||
ask_height,
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
109
src-tauri/src/core/conf.rs
Normal file
@ -0,0 +1,109 @@
|
||||
use log::error;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
fs::{self, File},
|
||||
io::{Read, Write},
|
||||
path::PathBuf,
|
||||
};
|
||||
use tauri::{AppHandle, Manager, Theme};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct AppConf {
|
||||
pub theme: String,
|
||||
pub stay_on_top: bool,
|
||||
pub ask_mode: bool,
|
||||
}
|
||||
|
||||
impl AppConf {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
theme: "system".to_string(),
|
||||
stay_on_top: false,
|
||||
ask_mode: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_conf_path(app: &AppHandle) -> Result<PathBuf, Box<dyn std::error::Error>> {
|
||||
let config_dir = app
|
||||
.path()
|
||||
.config_dir()?
|
||||
.join("com.nofwl.chatgpt")
|
||||
.join("config.json");
|
||||
Ok(config_dir)
|
||||
}
|
||||
|
||||
pub fn get_scripts_path(app: &AppHandle) -> Result<PathBuf, Box<dyn std::error::Error>> {
|
||||
let scripts_dir = app
|
||||
.path()
|
||||
.config_dir()?
|
||||
.join("com.nofwl.chatgpt")
|
||||
.join("scripts");
|
||||
Ok(scripts_dir)
|
||||
}
|
||||
|
||||
pub fn load_script(app: &AppHandle, filename: &str) -> String {
|
||||
let script_file = Self::get_scripts_path(app).unwrap().join(filename);
|
||||
fs::read_to_string(script_file).unwrap_or_else(|_| "".to_string())
|
||||
}
|
||||
|
||||
pub fn load(app: &AppHandle) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let path = Self::get_conf_path(app)?;
|
||||
|
||||
if !path.exists() {
|
||||
let config = Self::new();
|
||||
config.save(app)?;
|
||||
return Ok(config);
|
||||
}
|
||||
|
||||
let mut file = File::open(path)?;
|
||||
let mut contents = String::new();
|
||||
file.read_to_string(&mut contents)?;
|
||||
let config = serde_json::from_str(&contents)?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub fn save(&self, app: &AppHandle) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let path = Self::get_conf_path(app)?;
|
||||
|
||||
if let Some(dir) = path.parent() {
|
||||
fs::create_dir_all(dir)?;
|
||||
}
|
||||
|
||||
let mut file = File::create(path)?;
|
||||
let contents = serde_json::to_string_pretty(self)?;
|
||||
// dbg!(&contents);
|
||||
file.write_all(contents.as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn amend(self, json: Value) -> Result<Self, serde_json::Error> {
|
||||
let val = serde_json::to_value(self)?;
|
||||
let mut config: BTreeMap<String, Value> = serde_json::from_value(val)?;
|
||||
let new_json: BTreeMap<String, Value> = serde_json::from_value(json)?;
|
||||
|
||||
for (k, v) in new_json {
|
||||
config.insert(k, v);
|
||||
}
|
||||
|
||||
let config_str = serde_json::to_string_pretty(&config)?;
|
||||
serde_json::from_str::<AppConf>(&config_str).map_err(|err| {
|
||||
error!("conf_amend_parse: {}", err);
|
||||
err
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_theme(app: &AppHandle) -> Theme {
|
||||
let theme = Self::load(app).unwrap().theme;
|
||||
match theme.as_str() {
|
||||
"system" => match dark_light::detect() {
|
||||
dark_light::Mode::Dark => Theme::Dark,
|
||||
dark_light::Mode::Light => Theme::Light,
|
||||
dark_light::Mode::Default => Theme::Light,
|
||||
},
|
||||
"dark" => Theme::Dark,
|
||||
_ => Theme::Light,
|
||||
}
|
||||
}
|
||||
}
|
||||
43
src-tauri/src/core/constant.rs
Normal file
@ -0,0 +1,43 @@
|
||||
pub static TITLEBAR_HEIGHT: f64 = 28.0;
|
||||
pub static ASK_HEIGHT: f64 = 120.0;
|
||||
|
||||
pub static INIT_SCRIPT: &str = r#"
|
||||
window.addEventListener('DOMContentLoaded', function() {
|
||||
function handleUrlChange() {
|
||||
const url = window.location.href;
|
||||
if (url !== 'about:blank') {
|
||||
console.log('URL changed:', url);
|
||||
window.__TAURI__.webviewWindow.WebviewWindow.getByLabel('titlebar').emit('change:url', { url });
|
||||
}
|
||||
}
|
||||
|
||||
function handleLinkClick(event) {
|
||||
const target = event.target;
|
||||
if (target.tagName === 'A' && target.target && target.target !== '_blank') {
|
||||
target.target = '_blank';
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('click', handleLinkClick, true);
|
||||
window.addEventListener('popstate', handleUrlChange);
|
||||
window.addEventListener('pushState', handleUrlChange);
|
||||
window.addEventListener('replaceState', handleUrlChange);
|
||||
|
||||
const originalPushState = history.pushState;
|
||||
const originalReplaceState = history.replaceState;
|
||||
|
||||
history.pushState = function() {
|
||||
originalPushState.apply(this, arguments);
|
||||
console.log('pushState called');
|
||||
handleUrlChange();
|
||||
};
|
||||
|
||||
history.replaceState = function() {
|
||||
originalReplaceState.apply(this, arguments);
|
||||
console.log('replaceState called');
|
||||
handleUrlChange();
|
||||
};
|
||||
|
||||
handleUrlChange();
|
||||
});
|
||||
"#;
|
||||
5
src-tauri/src/core/mod.rs
Normal file
@ -0,0 +1,5 @@
|
||||
pub mod cmd;
|
||||
pub mod conf;
|
||||
pub mod constant;
|
||||
pub mod setup;
|
||||
pub mod template;
|
||||
192
src-tauri/src/core/setup.rs
Normal file
@ -0,0 +1,192 @@
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use tauri::{
|
||||
webview::DownloadEvent, App, LogicalPosition, Manager, PhysicalSize, TitleBarStyle,
|
||||
WebviewBuilder, WebviewUrl, WindowBuilder, WindowEvent,
|
||||
};
|
||||
use tauri_plugin_shell::ShellExt;
|
||||
|
||||
use crate::core::{
|
||||
conf::AppConf,
|
||||
constant::{ASK_HEIGHT, INIT_SCRIPT, TITLEBAR_HEIGHT},
|
||||
template,
|
||||
};
|
||||
|
||||
pub fn init(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let handle = app.handle();
|
||||
|
||||
let conf = &AppConf::load(handle).unwrap();
|
||||
let ask_mode_height = if conf.ask_mode { ASK_HEIGHT } else { 0.0 };
|
||||
|
||||
template::Template::new(AppConf::get_scripts_path(handle)?);
|
||||
|
||||
tauri::async_runtime::spawn({
|
||||
let handle = handle.clone();
|
||||
async move {
|
||||
let core_window = WindowBuilder::new(&handle, "core")
|
||||
.hidden_title(true)
|
||||
.title_bar_style(TitleBarStyle::Overlay)
|
||||
.resizable(true)
|
||||
.inner_size(800.0, 600.0)
|
||||
.min_inner_size(300.0, 200.0)
|
||||
.theme(Some(AppConf::get_theme(&handle)))
|
||||
.build()
|
||||
.expect("Failed to create window");
|
||||
|
||||
let win_size = core_window.inner_size().expect("Failed to get window size");
|
||||
let window = Arc::new(Mutex::new(core_window)); // Wrap the window in Arc<Mutex<_>> to manage ownership across threads
|
||||
|
||||
let main_view =
|
||||
WebviewBuilder::new("main", WebviewUrl::App("https://chatgpt.com".into()))
|
||||
.auto_resize()
|
||||
.on_download({
|
||||
let app_handle = handle.clone();
|
||||
let download_path = Arc::new(Mutex::new(PathBuf::new()));
|
||||
move |_, event| {
|
||||
match event {
|
||||
DownloadEvent::Requested { destination, .. } => {
|
||||
let download_dir = app_handle
|
||||
.path()
|
||||
.download_dir()
|
||||
.expect("[download] Failed to get download directory");
|
||||
let mut locked_path = download_path
|
||||
.lock()
|
||||
.expect("[download] Failed to lock download path");
|
||||
*locked_path = download_dir.join(&destination);
|
||||
*destination = locked_path.clone();
|
||||
}
|
||||
DownloadEvent::Finished { success, .. } => {
|
||||
let final_path = download_path
|
||||
.lock()
|
||||
.expect("[download] Failed to lock download path")
|
||||
.clone();
|
||||
|
||||
if success {
|
||||
app_handle
|
||||
.shell()
|
||||
.open(final_path.to_string_lossy(), None)
|
||||
.expect("[download] Failed to open file");
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
true
|
||||
}
|
||||
})
|
||||
.initialization_script("console.log('Hello from the initialization script!');")
|
||||
.initialization_script(&AppConf::load_script(&handle, "ask.js"))
|
||||
.initialization_script(INIT_SCRIPT);
|
||||
|
||||
let titlebar_view = WebviewBuilder::new(
|
||||
"titlebar",
|
||||
WebviewUrl::App("index.html?type=titlebar".into()),
|
||||
)
|
||||
.auto_resize();
|
||||
|
||||
let ask_view =
|
||||
WebviewBuilder::new("ask", WebviewUrl::App("index.html?type=ask".into()))
|
||||
.auto_resize();
|
||||
|
||||
let window_clone = Arc::clone(&window);
|
||||
let win = window.lock().unwrap();
|
||||
let scale_factor = win.scale_factor().unwrap();
|
||||
let titlebar_height = (scale_factor * TITLEBAR_HEIGHT).round() as u32;
|
||||
let ask_height = (scale_factor * ask_mode_height).round() as u32;
|
||||
let main_area_height = win_size.height - titlebar_height;
|
||||
|
||||
win.add_child(
|
||||
titlebar_view,
|
||||
LogicalPosition::new(0, 0),
|
||||
PhysicalSize::new(win_size.width, titlebar_height),
|
||||
)
|
||||
.unwrap();
|
||||
win.add_child(
|
||||
ask_view,
|
||||
LogicalPosition::new(
|
||||
0.0,
|
||||
(win_size.height as f64 / scale_factor) - ask_mode_height,
|
||||
),
|
||||
PhysicalSize::new(win_size.width, ask_height),
|
||||
)
|
||||
.unwrap();
|
||||
win.add_child(
|
||||
main_view,
|
||||
LogicalPosition::new(0.0, TITLEBAR_HEIGHT),
|
||||
PhysicalSize::new(win_size.width, main_area_height - ask_height),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// {
|
||||
// let get_ask_view = win
|
||||
// .get_webview("ask")
|
||||
// .expect("Failed to get webview window");
|
||||
// get_ask_view.open_devtools();
|
||||
// }
|
||||
// {
|
||||
// let get_main_view = win
|
||||
// .get_webview("main")
|
||||
// .expect("Failed to get webview window");
|
||||
// // dbg!(get_main_view);
|
||||
// // get_main_view.open_devtools();
|
||||
// }
|
||||
|
||||
win.on_window_event(move |event| {
|
||||
let conf = &AppConf::load(&handle).unwrap();
|
||||
let ask_mode_height = if conf.ask_mode { ASK_HEIGHT } else { 0.0 };
|
||||
let ask_height = (scale_factor * ask_mode_height).round() as u32;
|
||||
|
||||
if let WindowEvent::Resized(size) = event {
|
||||
let win = window_clone.lock().unwrap();
|
||||
let main_area_height = win.inner_size().unwrap().height - titlebar_height;
|
||||
|
||||
let main_view = win
|
||||
.get_webview("main")
|
||||
.expect("[view:main] Failed to get webview window");
|
||||
let titlebar_view = win
|
||||
.get_webview("titlebar")
|
||||
.expect("[view:titlebar] Failed to get webview window");
|
||||
let ask_view = win
|
||||
.get_webview("ask")
|
||||
.expect("[view:ask] Failed to get webview window");
|
||||
|
||||
main_view
|
||||
.set_position(LogicalPosition::new(0.0, TITLEBAR_HEIGHT))
|
||||
.unwrap();
|
||||
main_view
|
||||
.set_size(PhysicalSize::new(
|
||||
win.inner_size().unwrap().width,
|
||||
main_area_height - ask_height,
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
titlebar_view
|
||||
.set_position(LogicalPosition::new(0, 0))
|
||||
.unwrap();
|
||||
titlebar_view
|
||||
.set_size(PhysicalSize::new(
|
||||
win.inner_size().unwrap().width,
|
||||
titlebar_height,
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
ask_view
|
||||
.set_position(LogicalPosition::new(
|
||||
0.0,
|
||||
(size.height as f64 / scale_factor) - ask_mode_height,
|
||||
))
|
||||
.unwrap();
|
||||
ask_view
|
||||
.set_size(PhysicalSize::new(
|
||||
win.inner_size().unwrap().width,
|
||||
ask_height,
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
167
src-tauri/src/core/template.rs
Normal file
@ -0,0 +1,167 @@
|
||||
use anyhow::{Context, Result};
|
||||
use log::{error, info};
|
||||
use regex::Regex;
|
||||
use semver::Version;
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
fs::{self, File},
|
||||
io::{Read, Write},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
pub static SCRIPT_ASK: &[u8] = include_bytes!("../../scripts/ask.js");
|
||||
|
||||
/// Struct representing the template with the script data.
|
||||
#[derive(Debug)]
|
||||
pub struct Template {
|
||||
pub ask: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Template {
|
||||
/// Creates a new Template instance, initializing it with the script data.
|
||||
pub fn new<P: AsRef<Path>>(template_dir: P) -> Self {
|
||||
let template_dir = template_dir.as_ref();
|
||||
let mut template = Template::default();
|
||||
|
||||
let files = vec![(template_dir.join("ask.js"), &mut template.ask)];
|
||||
|
||||
for (filename, _) in files {
|
||||
match update_or_create_file(&filename, SCRIPT_ASK) {
|
||||
Ok(updated) => {
|
||||
if updated {
|
||||
info!("Script updated or created: {}", filename.display());
|
||||
} else {
|
||||
info!("Script is up-to-date: {}", filename.display());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to process script, {}: {}", filename.display(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Template {
|
||||
fn default() -> Template {
|
||||
Template {
|
||||
ask: Vec::from(SCRIPT_ASK),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the version information from the given data.
|
||||
fn read_version_info(data: &[u8]) -> Result<serde_json::Value> {
|
||||
let content = String::from_utf8_lossy(data);
|
||||
let re_name = Regex::new(r"@name\s+(.*?)\n").context("Failed to compile name regex")?;
|
||||
let re_version =
|
||||
Regex::new(r"@version\s+(.*?)\n").context("Failed to compile version regex")?;
|
||||
let re_url = Regex::new(r"@url\s+(.*?)\n").context("Failed to compile url regex")?;
|
||||
|
||||
let name = re_name
|
||||
.captures(&content)
|
||||
.and_then(|cap| cap.get(1))
|
||||
.map_or(String::new(), |m| m.as_str().trim().to_string());
|
||||
|
||||
let version = re_version
|
||||
.captures(&content)
|
||||
.and_then(|cap| cap.get(1))
|
||||
.map_or(String::new(), |m| m.as_str().trim().to_string());
|
||||
|
||||
let url = re_url
|
||||
.captures(&content)
|
||||
.and_then(|cap| cap.get(1))
|
||||
.map_or(String::new(), |m| m.as_str().trim().to_string());
|
||||
|
||||
let json_data = json!({
|
||||
"name": name,
|
||||
"version": version,
|
||||
"url": url,
|
||||
});
|
||||
|
||||
Ok(json_data)
|
||||
}
|
||||
|
||||
/// Reads the contents of the given file.
|
||||
fn read_file_contents<P: AsRef<Path>>(filename: P) -> Result<Vec<u8>> {
|
||||
let filename = filename.as_ref();
|
||||
let mut file = File::open(filename)?;
|
||||
let mut contents = Vec::new();
|
||||
file.read_to_end(&mut contents)?;
|
||||
Ok(contents)
|
||||
}
|
||||
|
||||
/// Writes the given data to the specified file.
|
||||
fn write_file_contents<P: AsRef<Path>>(filename: P, data: &[u8]) -> Result<()> {
|
||||
let filename = filename.as_ref();
|
||||
let mut file = File::create(filename)?;
|
||||
file.write_all(data)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates the necessary directories for the specified file path.
|
||||
fn create_dir<P: AsRef<Path>>(filename: P) -> Result<()> {
|
||||
let filename = filename.as_ref();
|
||||
if let Some(parent) = filename.parent() {
|
||||
if !parent.exists() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Updates the file if the new data has a newer version or if version info is missing,
|
||||
/// or creates the file if it doesn't exist.
|
||||
fn update_or_create_file<P: AsRef<Path>>(filename: P, new_data: &[u8]) -> Result<bool> {
|
||||
let filename = filename.as_ref();
|
||||
|
||||
// Ensure directory exists
|
||||
create_dir(filename)?;
|
||||
|
||||
let current_data = read_file_contents(filename);
|
||||
|
||||
match current_data {
|
||||
Ok(current_data) => {
|
||||
let new_info = read_version_info(new_data)?;
|
||||
let current_info = read_version_info(¤t_data);
|
||||
|
||||
match (
|
||||
new_info.get("version").and_then(|v| v.as_str()),
|
||||
current_info,
|
||||
) {
|
||||
(Some(new_version), Ok(current_info)) => {
|
||||
let current_version = current_info
|
||||
.get("version")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
|
||||
if current_version.is_empty()
|
||||
|| Version::parse(new_version)? > Version::parse(current_version)?
|
||||
{
|
||||
write_file_contents(filename, new_data)?;
|
||||
info!("{} → {}", current_version, new_version);
|
||||
Ok(true)
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
// If there is an error reading current version info, update the file
|
||||
(Some(_), Err(_)) => {
|
||||
write_file_contents(filename, new_data)?;
|
||||
Ok(true)
|
||||
}
|
||||
(None, _) => {
|
||||
// If there is an error reading new version info, don't update the file
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
// If there is an error reading the current file, create a new file
|
||||
write_file_contents(filename, new_data)?;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,133 +1,27 @@
|
||||
#![cfg_attr(
|
||||
all(not(debug_assertions), target_os = "windows"),
|
||||
windows_subsystem = "windows"
|
||||
)]
|
||||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
mod app;
|
||||
mod conf;
|
||||
mod utils;
|
||||
mod core;
|
||||
use core::{cmd, setup};
|
||||
|
||||
use app::{cmd, fs_extra, gpt, menu, script, setup, window};
|
||||
use conf::AppConf;
|
||||
use tauri_plugin_autostart::MacosLauncher;
|
||||
use tauri_plugin_log::{
|
||||
fern::colors::{Color, ColoredLevelConfig},
|
||||
LogTarget,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let app_conf = AppConf::read().write();
|
||||
// If the file does not exist, creating the file will block menu synchronization
|
||||
utils::create_chatgpt_prompts();
|
||||
let context = tauri::generate_context!();
|
||||
|
||||
gpt::download_list("chat.download.json", "download", None, None);
|
||||
gpt::download_list("chat.notes.json", "notes", None, None);
|
||||
|
||||
let mut log = tauri_plugin_log::Builder::default()
|
||||
.targets([
|
||||
// LogTarget::LogDir,
|
||||
// LOG PATH: ~/.chatgpt/ChatGPT.log
|
||||
LogTarget::Folder(utils::app_root()),
|
||||
LogTarget::Stdout,
|
||||
LogTarget::Webview,
|
||||
])
|
||||
.level(log::LevelFilter::Debug);
|
||||
|
||||
if cfg!(debug_assertions) {
|
||||
log = log.with_colors(ColoredLevelConfig {
|
||||
error: Color::Red,
|
||||
warn: Color::Yellow,
|
||||
debug: Color::Blue,
|
||||
info: Color::BrightGreen,
|
||||
trace: Color::Cyan,
|
||||
});
|
||||
}
|
||||
|
||||
let mut builder = tauri::Builder::default()
|
||||
.plugin(log.build())
|
||||
.plugin(tauri_plugin_positioner::init())
|
||||
.plugin(tauri_plugin_autostart::init(
|
||||
MacosLauncher::LaunchAgent,
|
||||
None,
|
||||
))
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
cmd::drag_window,
|
||||
cmd::fullscreen,
|
||||
cmd::save_file,
|
||||
cmd::open_link,
|
||||
cmd::run_check_update,
|
||||
cmd::open_file,
|
||||
cmd::download_file,
|
||||
cmd::get_data,
|
||||
cmd::fetch_image,
|
||||
gpt::get_chat_prompt_cmd,
|
||||
gpt::parse_prompt,
|
||||
gpt::sync_prompts,
|
||||
gpt::sync_user_prompts,
|
||||
gpt::cmd_list,
|
||||
gpt::download_list,
|
||||
gpt::get_download_list,
|
||||
fs_extra::metadata,
|
||||
conf::cmd::get_app_conf,
|
||||
conf::cmd::reset_app_conf,
|
||||
conf::cmd::get_theme,
|
||||
conf::cmd::form_confirm,
|
||||
conf::cmd::form_cancel,
|
||||
conf::cmd::form_msg,
|
||||
script::cmd::sync_scripts,
|
||||
script::cmd::get_script_info,
|
||||
window::cmd::wa_window,
|
||||
window::cmd::control_window,
|
||||
window::cmd::window_reload,
|
||||
])
|
||||
.setup(setup::init)
|
||||
.menu(menu::init());
|
||||
|
||||
if app_conf.tray {
|
||||
builder = builder.system_tray(menu::tray_menu());
|
||||
}
|
||||
|
||||
if app_conf.save_window_state {
|
||||
builder = builder.plugin(tauri_plugin_window_state::Builder::default().build());
|
||||
}
|
||||
|
||||
builder
|
||||
.on_menu_event(menu::menu_handler)
|
||||
.on_system_tray_event(menu::tray_handler)
|
||||
.on_window_event(move |event| {
|
||||
if let tauri::WindowEvent::CloseRequested { api, .. } = event.event() {
|
||||
let win = event.window().clone();
|
||||
let app_conf = AppConf::read();
|
||||
if win.label() == "core" {
|
||||
if app_conf.isinit {
|
||||
tauri::api::dialog::ask(
|
||||
Some(event.window()),
|
||||
"",
|
||||
"Do you want to exit the application when you click the [x] button?",
|
||||
move |is_ok| {
|
||||
app_conf
|
||||
.amend(serde_json::json!({ "isinit" : false, "main_close": is_ok }))
|
||||
.write();
|
||||
if is_ok {
|
||||
std::process::exit(0);
|
||||
} else {
|
||||
win.minimize().unwrap();
|
||||
}
|
||||
},
|
||||
);
|
||||
} else if app_conf.main_close {
|
||||
std::process::exit(0);
|
||||
} else {
|
||||
win.minimize().unwrap();
|
||||
}
|
||||
} else {
|
||||
event.window().close().unwrap();
|
||||
}
|
||||
api.prevent_close();
|
||||
}
|
||||
})
|
||||
.run(context)
|
||||
.expect("error while running ChatGPT application");
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_os::init())
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
cmd::view_reload,
|
||||
cmd::view_url,
|
||||
cmd::view_go_forward,
|
||||
cmd::view_go_back,
|
||||
cmd::set_view_ask,
|
||||
cmd::get_app_conf,
|
||||
cmd::window_pin,
|
||||
cmd::ask_sync,
|
||||
cmd::ask_send,
|
||||
cmd::set_theme,
|
||||
])
|
||||
.setup(setup::init)
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running lencx/ChatGPT application");
|
||||
}
|
||||
|
||||
@ -1,270 +0,0 @@
|
||||
use anyhow::Result;
|
||||
use log::{error, info};
|
||||
use regex::Regex;
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
use tauri::updater::UpdateResponse;
|
||||
use tauri::{utils::config::Config, AppHandle, Manager, Wry};
|
||||
|
||||
pub fn app_root() -> PathBuf {
|
||||
tauri::api::path::home_dir().unwrap().join(".chatgpt")
|
||||
}
|
||||
|
||||
pub fn get_tauri_conf() -> Option<Config> {
|
||||
let config_file = include_str!("../tauri.conf.json");
|
||||
let config: Config = serde_json::from_str(config_file).expect("failed to parse tauri.conf.json");
|
||||
Some(config)
|
||||
}
|
||||
|
||||
pub fn exists(path: &Path) -> bool {
|
||||
Path::new(path).exists()
|
||||
}
|
||||
|
||||
pub fn create_file<P: AsRef<Path>>(filename: P) -> Result<()> {
|
||||
let filename = filename.as_ref();
|
||||
if let Some(parent) = filename.parent() {
|
||||
if !parent.exists() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
}
|
||||
fs::File::create(filename)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_chatgpt_prompts() {
|
||||
let sync_file = app_root()
|
||||
.join("cache_prompts")
|
||||
.join("chatgpt_prompts.json");
|
||||
if !exists(&sync_file) {
|
||||
create_file(&sync_file).unwrap();
|
||||
fs::write(&sync_file, "[]").unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn user_script() -> String {
|
||||
let user_script_file = app_root().join("scripts").join("main.js");
|
||||
let user_script_content = fs::read_to_string(user_script_file).unwrap_or_else(|_| "".to_string());
|
||||
format!(
|
||||
"window.addEventListener('DOMContentLoaded', function() {{\n{}\n}})",
|
||||
user_script_content
|
||||
)
|
||||
}
|
||||
|
||||
pub fn load_script(filename: &str) -> String {
|
||||
let script_file = app_root().join("scripts").join(filename);
|
||||
fs::read_to_string(script_file).unwrap_or_else(|_| "".to_string())
|
||||
}
|
||||
|
||||
pub fn open_file(path: PathBuf) {
|
||||
let pathname = convert_path(path.to_str().unwrap());
|
||||
info!("open_file: {}", pathname);
|
||||
#[cfg(target_os = "macos")]
|
||||
Command::new("open")
|
||||
.arg("-R")
|
||||
.arg(pathname)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
Command::new("explorer.exe")
|
||||
.arg("/select,")
|
||||
.arg(pathname)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
|
||||
// https://askubuntu.com/a/31071
|
||||
#[cfg(target_os = "linux")]
|
||||
Command::new("xdg-open").arg(pathname).spawn().unwrap();
|
||||
}
|
||||
|
||||
pub fn convert_path(path_str: &str) -> String {
|
||||
if cfg!(target_os = "windows") {
|
||||
path_str.replace('/', "\\")
|
||||
} else {
|
||||
String::from(path_str)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_conf(app: &tauri::AppHandle) {
|
||||
let root = app_root();
|
||||
let msg = format!(
|
||||
"Path: {}\n
|
||||
Are you sure you want to clear all ChatGPT configurations? Performing this operation data can not be restored, please back up in advance.\n
|
||||
Note: The application will exit automatically after the configuration cleanup!",
|
||||
root.to_string_lossy()
|
||||
);
|
||||
tauri::api::dialog::ask(
|
||||
app.get_window("core").as_ref(),
|
||||
"Clear Config",
|
||||
msg,
|
||||
move |is_ok| {
|
||||
if is_ok {
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
std::process::exit(0);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
pub fn merge(v: &Value, fields: &HashMap<String, Value>) -> Value {
|
||||
match v {
|
||||
Value::Object(m) => {
|
||||
let mut m = m.clone();
|
||||
for (k, v) in fields {
|
||||
m.insert(k.clone(), v.clone());
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
v => v.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn gen_cmd(name: String) -> String {
|
||||
let re = Regex::new(r"[^a-zA-Z0-9]").unwrap();
|
||||
re.replace_all(&name, "_").to_lowercase()
|
||||
}
|
||||
|
||||
pub async fn get_data(
|
||||
url: &str,
|
||||
app: Option<&tauri::AppHandle>,
|
||||
) -> Result<Option<String>, reqwest::Error> {
|
||||
let res = reqwest::get(url).await?;
|
||||
let is_ok = res.status() == 200;
|
||||
let body = res.text().await?;
|
||||
|
||||
if is_ok {
|
||||
Ok(Some(body))
|
||||
} else {
|
||||
error!("chatgpt_http: {}", body);
|
||||
if let Some(v) = app {
|
||||
tauri::api::dialog::message(v.get_window("core").as_ref(), "ChatGPT HTTP", body);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_check_update(app: AppHandle<Wry>, silent: bool, has_msg: Option<bool>) {
|
||||
info!("run_check_update: silent={} has_msg={:?}", silent, has_msg);
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if let Ok(update_resp) = app.updater().check().await {
|
||||
if update_resp.is_update_available() {
|
||||
if silent {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
silent_install(app, update_resp).await.unwrap();
|
||||
});
|
||||
} else {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
prompt_for_install(app, update_resp).await.unwrap();
|
||||
});
|
||||
}
|
||||
} else if let Some(v) = has_msg {
|
||||
if v {
|
||||
tauri::api::dialog::message(
|
||||
app.app_handle().get_window("core").as_ref(),
|
||||
"ChatGPT",
|
||||
"Your ChatGPT is up to date",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Copy private api in tauri/updater/mod.rs. TODO: refactor to public api
|
||||
// Prompt a dialog asking if the user want to install the new version
|
||||
// Maybe we should add an option to customize it in future versions.
|
||||
pub async fn prompt_for_install(app: AppHandle<Wry>, update: UpdateResponse<Wry>) -> Result<()> {
|
||||
info!("prompt_for_install");
|
||||
let windows = app.windows();
|
||||
let parent_window = windows.values().next();
|
||||
let package_info = app.package_info().clone();
|
||||
|
||||
let body = update.body().unwrap();
|
||||
// todo(lemarier): We should review this and make sure we have
|
||||
// something more conventional.
|
||||
let should_install = tauri::api::dialog::blocking::ask(
|
||||
parent_window,
|
||||
format!(r#"A new version of {} is available! "#, package_info.name),
|
||||
format!(
|
||||
r#"{} {} is now available -- you have {}.
|
||||
|
||||
Would you like to install it now?
|
||||
|
||||
Release Notes:
|
||||
{}"#,
|
||||
package_info.name,
|
||||
update.latest_version(),
|
||||
package_info.version,
|
||||
body
|
||||
),
|
||||
);
|
||||
|
||||
if should_install {
|
||||
// Launch updater download process
|
||||
// macOS we display the `Ready to restart dialog` asking to restart
|
||||
// Windows is closing the current App and launch the downloaded MSI when ready (the process stop here)
|
||||
// Linux we replace the AppImage by launching a new install, it start a new AppImage instance, so we're closing the previous. (the process stop here)
|
||||
update.download_and_install().await?;
|
||||
|
||||
// Ask user if we need to restart the application
|
||||
let should_exit = tauri::api::dialog::blocking::ask(
|
||||
parent_window,
|
||||
"Ready to Restart",
|
||||
"The installation was successful, do you want to restart the application now?",
|
||||
);
|
||||
if should_exit {
|
||||
app.restart();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn silent_install(app: AppHandle<Wry>, update: UpdateResponse<Wry>) -> Result<()> {
|
||||
info!("silent_install");
|
||||
let windows = app.windows();
|
||||
let parent_window = windows.values().next();
|
||||
|
||||
// Launch updater download process
|
||||
// macOS we display the `Ready to restart dialog` asking to restart
|
||||
// Windows is closing the current App and launch the downloaded MSI when ready (the process stop here)
|
||||
// Linux we replace the AppImage by launching a new install, it start a new AppImage instance, so we're closing the previous. (the process stop here)
|
||||
update.download_and_install().await?;
|
||||
|
||||
// Ask user if we need to restart the application
|
||||
let should_exit = tauri::api::dialog::blocking::ask(
|
||||
parent_window,
|
||||
"Ready to Restart",
|
||||
"The silent installation was successful, do you want to restart the application now?",
|
||||
);
|
||||
if should_exit {
|
||||
app.restart();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_hidden(entry: &walkdir::DirEntry) -> bool {
|
||||
entry
|
||||
.file_name()
|
||||
.to_str()
|
||||
.map(|s| s.starts_with('.'))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn vec_to_hashmap(
|
||||
vec: impl Iterator<Item = serde_json::Value>,
|
||||
key: &str,
|
||||
map: &mut HashMap<String, serde_json::Value>,
|
||||
) {
|
||||
for v in vec {
|
||||
if let Some(kval) = v.get(key).and_then(serde_json::Value::as_str) {
|
||||
map.insert(kval.to_string(), v);
|
||||
}
|
||||
}
|
||||
}
|
||||
1
src-tauri/src/vendors/floating-ui-core.js
vendored
1
src-tauri/src/vendors/floating-ui-dom.js
vendored
20
src-tauri/src/vendors/html2canvas.js
vendored
397
src-tauri/src/vendors/jspdf.js
vendored
164
src-tauri/src/vendors/turndown-plugin-gfm.js
vendored
@ -1,164 +0,0 @@
|
||||
var turndownPluginGfm = (function (exports) {
|
||||
'use strict';
|
||||
|
||||
var highlightRegExp = /highlight-(?:text|source)-([a-z0-9]+)/;
|
||||
|
||||
function highlightedCodeBlock (turndownService) {
|
||||
turndownService.addRule('highlightedCodeBlock', {
|
||||
filter: function (node) {
|
||||
var firstChild = node.firstChild;
|
||||
return (
|
||||
node.nodeName === 'DIV' &&
|
||||
highlightRegExp.test(node.className) &&
|
||||
firstChild &&
|
||||
firstChild.nodeName === 'PRE'
|
||||
)
|
||||
},
|
||||
replacement: function (content, node, options) {
|
||||
var className = node.className || '';
|
||||
var language = (className.match(highlightRegExp) || [null, ''])[1];
|
||||
|
||||
return (
|
||||
'\n\n' + options.fence + language + '\n' +
|
||||
node.firstChild.textContent +
|
||||
'\n' + options.fence + '\n\n'
|
||||
)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function strikethrough (turndownService) {
|
||||
turndownService.addRule('strikethrough', {
|
||||
filter: ['del', 's', 'strike'],
|
||||
replacement: function (content) {
|
||||
return '~' + content + '~'
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var indexOf = Array.prototype.indexOf;
|
||||
var every = Array.prototype.every;
|
||||
var rules = {};
|
||||
|
||||
rules.tableCell = {
|
||||
filter: ['th', 'td'],
|
||||
replacement: function (content, node) {
|
||||
return cell(content, node)
|
||||
}
|
||||
};
|
||||
|
||||
rules.tableRow = {
|
||||
filter: 'tr',
|
||||
replacement: function (content, node) {
|
||||
var borderCells = '';
|
||||
var alignMap = { left: ':--', right: '--:', center: ':-:' };
|
||||
|
||||
if (isHeadingRow(node)) {
|
||||
for (var i = 0; i < node.childNodes.length; i++) {
|
||||
var border = '---';
|
||||
var align = (
|
||||
node.childNodes[i].getAttribute('align') || ''
|
||||
).toLowerCase();
|
||||
|
||||
if (align) border = alignMap[align] || border;
|
||||
|
||||
borderCells += cell(border, node.childNodes[i]);
|
||||
}
|
||||
}
|
||||
return '\n' + content + (borderCells ? '\n' + borderCells : '')
|
||||
}
|
||||
};
|
||||
|
||||
rules.table = {
|
||||
// Only convert tables with a heading row.
|
||||
// Tables with no heading row are kept using `keep` (see below).
|
||||
filter: function (node) {
|
||||
return node.nodeName === 'TABLE' && isHeadingRow(node.rows[0])
|
||||
},
|
||||
|
||||
replacement: function (content) {
|
||||
// Ensure there are no blank lines
|
||||
content = content.replace('\n\n', '\n');
|
||||
return '\n\n' + content + '\n\n'
|
||||
}
|
||||
};
|
||||
|
||||
rules.tableSection = {
|
||||
filter: ['thead', 'tbody', 'tfoot'],
|
||||
replacement: function (content) {
|
||||
return content
|
||||
}
|
||||
};
|
||||
|
||||
// A tr is a heading row if:
|
||||
// - the parent is a THEAD
|
||||
// - or if its the first child of the TABLE or the first TBODY (possibly
|
||||
// following a blank THEAD)
|
||||
// - and every cell is a TH
|
||||
function isHeadingRow (tr) {
|
||||
var parentNode = tr.parentNode;
|
||||
return (
|
||||
parentNode.nodeName === 'THEAD' ||
|
||||
(
|
||||
parentNode.firstChild === tr &&
|
||||
(parentNode.nodeName === 'TABLE' || isFirstTbody(parentNode)) &&
|
||||
every.call(tr.childNodes, function (n) { return n.nodeName === 'TH' })
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
function isFirstTbody (element) {
|
||||
var previousSibling = element.previousSibling;
|
||||
return (
|
||||
element.nodeName === 'TBODY' && (
|
||||
!previousSibling ||
|
||||
(
|
||||
previousSibling.nodeName === 'THEAD' &&
|
||||
/^\s*$/i.test(previousSibling.textContent)
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
function cell (content, node) {
|
||||
var index = indexOf.call(node.parentNode.childNodes, node);
|
||||
var prefix = ' ';
|
||||
if (index === 0) prefix = '| ';
|
||||
return prefix + content + ' |'
|
||||
}
|
||||
|
||||
function tables (turndownService) {
|
||||
turndownService.keep(function (node) {
|
||||
return node.nodeName === 'TABLE' && !isHeadingRow(node.rows[0])
|
||||
});
|
||||
for (var key in rules) turndownService.addRule(key, rules[key]);
|
||||
}
|
||||
|
||||
function taskListItems (turndownService) {
|
||||
turndownService.addRule('taskListItems', {
|
||||
filter: function (node) {
|
||||
return node.type === 'checkbox' && node.parentNode.nodeName === 'LI'
|
||||
},
|
||||
replacement: function (content, node) {
|
||||
return (node.checked ? '[x]' : '[ ]') + ' '
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function gfm (turndownService) {
|
||||
turndownService.use([
|
||||
highlightedCodeBlock,
|
||||
strikethrough,
|
||||
tables,
|
||||
taskListItems
|
||||
]);
|
||||
}
|
||||
|
||||
exports.gfm = gfm;
|
||||
exports.highlightedCodeBlock = highlightedCodeBlock;
|
||||
exports.strikethrough = strikethrough;
|
||||
exports.tables = tables;
|
||||
exports.taskListItems = taskListItems;
|
||||
|
||||
return exports;
|
||||
}({}));
|
||||
1
src-tauri/src/vendors/turndown.js
vendored
@ -1,140 +1,29 @@
|
||||
{
|
||||
"productName": "ChatGPT",
|
||||
"version": "../package.json",
|
||||
"identifier": "com.nofwl.chatgpt",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev:fe",
|
||||
"beforeBuildCommand": "npm run build:fe",
|
||||
"devPath": "http://localhost:1420",
|
||||
"distDir": "../dist"
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
"devUrl": "http://localhost:1420",
|
||||
"beforeBuildCommand": "pnpm build",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"package": {
|
||||
"productName": "ChatGPT",
|
||||
"version": "1.1.0"
|
||||
},
|
||||
"tauri": {
|
||||
"allowlist": {
|
||||
"all": false,
|
||||
"globalShortcut": {
|
||||
"all": true
|
||||
},
|
||||
"shell": {
|
||||
"all": true
|
||||
},
|
||||
"fs": {
|
||||
"all": false,
|
||||
"readFile": true,
|
||||
"writeFile": true,
|
||||
"readDir": true,
|
||||
"createDir": true,
|
||||
"exists": true,
|
||||
"removeFile": true,
|
||||
"removeDir": true,
|
||||
"scope": [
|
||||
"$HOME/.chatgpt/**",
|
||||
"$DOWNLOAD/**"
|
||||
]
|
||||
},
|
||||
"path": {
|
||||
"all": true
|
||||
},
|
||||
"os": {
|
||||
"all": true
|
||||
},
|
||||
"dialog": {
|
||||
"all": true
|
||||
},
|
||||
"process": {
|
||||
"all": true,
|
||||
"exit": true,
|
||||
"relaunch": true,
|
||||
"relaunchDangerousAllowSymlinkMacos": true
|
||||
}
|
||||
},
|
||||
"systemTray": {
|
||||
"iconPath": "icons/tray-icon.png",
|
||||
"iconAsTemplate": true,
|
||||
"menuOnLeftClick": false
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"category": "DeveloperTool",
|
||||
"copyright": "",
|
||||
"deb": {
|
||||
"depends": []
|
||||
},
|
||||
"externalBin": [],
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"identifier": "com.lencx.chatgpt",
|
||||
"longDescription": "ChatGPT Desktop Application",
|
||||
"macOS": {
|
||||
"entitlements": null,
|
||||
"exceptionDomain": "",
|
||||
"frameworks": [],
|
||||
"providerShortName": null,
|
||||
"signingIdentity": null
|
||||
},
|
||||
"shortDescription": "ChatGPT",
|
||||
"targets": "all",
|
||||
"windows": {
|
||||
"certificateThumbprint": null,
|
||||
"digestAlgorithm": "sha256",
|
||||
"timestampUrl": "",
|
||||
"webviewInstallMode": {
|
||||
"silent": true,
|
||||
"type": "embedBootstrapper"
|
||||
}
|
||||
}
|
||||
},
|
||||
"app": {
|
||||
"withGlobalTauri": true,
|
||||
"windows": [],
|
||||
"security": {
|
||||
"csp": null,
|
||||
"dangerousRemoteDomainIpcAccess": [
|
||||
{
|
||||
"windows": [
|
||||
"core",
|
||||
"main",
|
||||
"tray"
|
||||
],
|
||||
"domain": "chat.openai.com",
|
||||
"enableTauriAPI": true
|
||||
},
|
||||
{
|
||||
"windows": [
|
||||
"core",
|
||||
"main"
|
||||
],
|
||||
"domain": "labs.openai.com",
|
||||
"enableTauriAPI": true
|
||||
},
|
||||
{
|
||||
"windows": [
|
||||
"core",
|
||||
"main",
|
||||
"tray"
|
||||
],
|
||||
"domain": "openai.com",
|
||||
"enableTauriAPI": true
|
||||
},
|
||||
{
|
||||
"windows": [
|
||||
"chatgpt_sponsors",
|
||||
"app_website"
|
||||
],
|
||||
"domain": "app.nofwl.com",
|
||||
"enableTauriAPI": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"updater": {
|
||||
"active": true,
|
||||
"dialog": false,
|
||||
"endpoints": [
|
||||
"https://lencx.github.io/ChatGPT/install.json"
|
||||
],
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEIxMjY4OUI5MTVFNjBEMDUKUldRRkRlWVZ1WWttc1NGWEE0RFNSb0RqdnhsekRJZTkwK2hVLzhBZTZnaHExSEZ1ZEdzWkpXTHkK"
|
||||
"csp": null
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
10
src/base.css
Normal file
@ -0,0 +1,10 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
html, body, #root {
|
||||
margin: 0;
|
||||
bottom: 0;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||