Full Code of NsLearning/LangHelper for AI

main acb30ca60b23 cached
128 files
958.2 KB
346.3k tokens
466 symbols
1 requests
Download .txt
Showing preview only (1,011K chars total). Download the full file or copy to clipboard to get everything.
Repository: NsLearning/LangHelper
Branch: main
Commit: acb30ca60b23
Files: 128
Total size: 958.2 KB

Directory structure:
gitextract_0flj9ssv/

├── ChatGPT/
│   ├── .gitattributes
│   ├── .gitignore
│   ├── .husky/
│   │   └── pre-commit
│   ├── .npmrc
│   ├── .prettierignore
│   ├── .prettierrc
│   ├── .vscode/
│   │   └── extensions.json
│   ├── Cargo.toml
│   ├── LICENSE
│   ├── README-ZH_CN.md
│   ├── README.md
│   ├── UPDATE_LOG.md
│   ├── casks/
│   │   └── chatgpt.rb
│   ├── index.html
│   ├── package.json
│   ├── rustfmt.toml
│   ├── src/
│   │   ├── components/
│   │   │   ├── FilePath/
│   │   │   │   └── index.tsx
│   │   │   ├── Markdown/
│   │   │   │   ├── Editor.tsx
│   │   │   │   ├── index.scss
│   │   │   │   └── index.tsx
│   │   │   ├── SwitchOrigin/
│   │   │   │   └── index.tsx
│   │   │   └── Tags/
│   │   │       └── index.tsx
│   │   ├── hooks/
│   │   │   ├── useChatModel.ts
│   │   │   ├── useColumns.tsx
│   │   │   ├── useData.ts
│   │   │   ├── useInit.ts
│   │   │   ├── useJson.ts
│   │   │   └── useTable.tsx
│   │   ├── icons/
│   │   │   └── SplitIcon.tsx
│   │   ├── layout/
│   │   │   ├── index.scss
│   │   │   └── index.tsx
│   │   ├── main.scss
│   │   ├── main.tsx
│   │   ├── routes.tsx
│   │   ├── utils.ts
│   │   ├── view/
│   │   │   ├── about/
│   │   │   │   ├── index.scss
│   │   │   │   └── index.tsx
│   │   │   ├── awesome/
│   │   │   │   ├── Form.tsx
│   │   │   │   ├── config.tsx
│   │   │   │   └── index.tsx
│   │   │   ├── dashboard/
│   │   │   │   ├── index.scss
│   │   │   │   └── index.tsx
│   │   │   ├── download/
│   │   │   │   ├── config.tsx
│   │   │   │   └── index.tsx
│   │   │   ├── markdown/
│   │   │   │   ├── index.scss
│   │   │   │   └── index.tsx
│   │   │   ├── model/
│   │   │   │   ├── SyncCustom/
│   │   │   │   │   ├── Form.tsx
│   │   │   │   │   ├── config.tsx
│   │   │   │   │   └── index.tsx
│   │   │   │   ├── SyncPrompts/
│   │   │   │   │   ├── config.tsx
│   │   │   │   │   ├── index.scss
│   │   │   │   │   └── index.tsx
│   │   │   │   ├── SyncRecord/
│   │   │   │   │   ├── config.tsx
│   │   │   │   │   └── index.tsx
│   │   │   │   └── UserCustom/
│   │   │   │       ├── Form.tsx
│   │   │   │       ├── config.tsx
│   │   │   │       └── index.tsx
│   │   │   ├── notes/
│   │   │   │   ├── config.tsx
│   │   │   │   └── index.tsx
│   │   │   └── settings/
│   │   │       ├── General.tsx
│   │   │       ├── LangHelper.tsx
│   │   │       ├── MainWindow.tsx
│   │   │       ├── Speakers.ts
│   │   │       ├── TrayWindow.tsx
│   │   │       └── index.tsx
│   │   └── vite-env.d.ts
│   ├── src-tauri/
│   │   ├── Cargo.toml
│   │   ├── build.rs
│   │   ├── icons/
│   │   │   └── icon.icns
│   │   ├── src/
│   │   │   ├── app/
│   │   │   │   ├── cmd.rs
│   │   │   │   ├── cors.rs
│   │   │   │   ├── fs_extra.rs
│   │   │   │   ├── gpt.rs
│   │   │   │   ├── menu.rs
│   │   │   │   ├── mod.rs
│   │   │   │   ├── setup.rs
│   │   │   │   └── window.rs
│   │   │   ├── conf.rs
│   │   │   ├── main.rs
│   │   │   ├── scripts/
│   │   │   │   ├── chat.js
│   │   │   │   ├── cmd.js
│   │   │   │   ├── core.js
│   │   │   │   ├── dalle2.js
│   │   │   │   ├── export.js
│   │   │   │   ├── markdown.export.js
│   │   │   │   └── popup.core.js
│   │   │   ├── utils.rs
│   │   │   └── vendors/
│   │   │       ├── floating-ui-core.js
│   │   │       ├── floating-ui-dom.js
│   │   │       ├── html2canvas.js
│   │   │       ├── jspdf.js
│   │   │       ├── turndown-plugin-gfm.js
│   │   │       └── turndown.js
│   │   └── tauri.conf.json
│   ├── tsconfig.json
│   ├── tsconfig.node.json
│   └── vite.config.ts
├── LICENSE
├── LangHelper/
│   ├── Assess/
│   │   ├── IflytekAssessment.py
│   │   ├── SpeechSuper.py
│   │   └── __init__.py
│   ├── Recognition/
│   │   ├── IflytekRec.py
│   │   └── __init__.py
│   ├── Resource/
│   │   ├── cn/
│   │   │   ├── read_sentence_cn.pcm
│   │   │   ├── read_sentence_cn.txt
│   │   │   ├── read_syllable_cn.pcm
│   │   │   └── read_syllable_cn.txt
│   │   ├── en/
│   │   │   ├── oral_translation_en.pcm
│   │   │   ├── oral_translation_en.txt
│   │   │   ├── picture_talk_en.pcm
│   │   │   ├── picture_talk_en.txt
│   │   │   ├── read_choice_en.pcm
│   │   │   ├── read_choice_en.txt
│   │   │   ├── read_sentence_en.pcm
│   │   │   ├── read_sentence_en.txt
│   │   │   ├── read_word_en.pcm
│   │   │   ├── read_word_en.txt
│   │   │   ├── retell_en.pcm
│   │   │   ├── retell_en.txt
│   │   │   ├── topic_en.pcm
│   │   │   └── topic_en.txt
│   │   ├── rec/
│   │   │   └── realtime.pcm
│   │   ├── speaker-info.txt
│   │   └── tts_models--en--vctk--vits/
│   │       ├── config.json
│   │       └── speaker_ids.json
│   ├── main.py
│   └── recoder.py
└── README.md

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

================================================
FILE: ChatGPT/.gitattributes
================================================
*.js linguist-vendored
*.tsx linguist-vendored
*.scss linguist-vendored
src/**/*.ts linguist-vendored

================================================
FILE: ChatGPT/.gitignore
================================================
package-lock.json
node_modules/

.yarn/*
.pnp.*

# rust
target/

# 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?


================================================
FILE: ChatGPT/.husky/pre-commit
================================================
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npm run pretty-quick
cargo fmt
git add .

================================================
FILE: ChatGPT/.npmrc
================================================
registry=https://registry.npmjs.org/
engine-strict=true

================================================
FILE: ChatGPT/.prettierignore
================================================
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

================================================
FILE: ChatGPT/.prettierrc
================================================
{
  "trailingComma": "all",
  "singleQuote": true,
  "semi": true,
  "tabWidth": 2,
  "printWidth": 100
}


================================================
FILE: ChatGPT/.vscode/extensions.json
================================================
{
  "recommendations": ["tauri-apps.tauri-vscode", "rust-lang.rust-analyzer"]
}


================================================
FILE: ChatGPT/Cargo.toml
================================================
[workspace]
members = ["src-tauri"]

# fix: mac v1.2.0 can not copy/paste
# https://github.com/tauri-apps/tauri/issues/5669
[profile.release]
strip = true
lto = true
opt-level = "s"


================================================
FILE: ChatGPT/LICENSE
================================================
                    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/>.

================================================
FILE: ChatGPT/README-ZH_CN.md
================================================
<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>

[![English badge](https://img.shields.io/badge/%E8%8B%B1%E6%96%87-English-blue)](./README.md)
[![简体中文 badge](https://img.shields.io/badge/%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87-Simplified%20Chinese-blue)](./README-ZH_CN.md)\
[![ChatGPT downloads](https://img.shields.io/github/downloads/lencx/ChatGPT/total.svg?style=flat-square)](https://github.com/lencx/ChatGPT/releases)
[![chat](https://img.shields.io/badge/chat-discord-blue?style=flat&logo=discord)](https://discord.gg/aPhCRf4zZr)
[![lencx](https://img.shields.io/badge/follow-lencx__-blue?style=flat&logo=Twitter)](https://twitter.com/lencx_)

<!-- [![lencx](https://img.shields.io/twitter/follow/lencx_.svg?style=social)](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_0.12.0_windows_x86_64.msi](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.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#issuecomment-0.12.0))**

### Mac

- [ChatGPT_0.12.0_macos_aarch64.dmg](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.0_macos_aarch64.dmg)
- [ChatGPT_0.12.0_macos_x86_64.dmg](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.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_0.12.0_linux_x86_64.deb](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.0_linux_x86_64.deb)
- [ChatGPT_0.12.0_linux_x86_64.AppImage.tar.gz](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.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`,来一键同步所有,如果你不想让某些提示出现在你的斜杠命令,你可以禁用它们。

![chatgpt cmd](./assets/chatgpt-cmd.png)
![chatgpt sync prompts](./assets/chatgpt-sync-prompts.png)

<!-- 数据导入完成后,可以重新启动应用来使配置生效(`Menu -> Preferences -> Restart ChatGPT`)。 -->

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

![chatgpt](assets/chatgpt.gif)
![chatgpt-cmd](assets/chatgpt-cmd.gif)

## ✨ 功能概览

- 跨平台: `macOS` `Linux` `Windows`
- 导出 ChatGPT 聊天记录 (支持 PNG, PDF 和生成分享链接)
- 主窗口和系统托盘支持自定义 URL,将任意网站包装成一个桌面应用
- 应用自动升级通知
- 丰富的快捷键
- 系统托盘悬浮窗
- 应用菜单功能强大
- 支持斜杠命令及其配置(可手动配置或从文件同步 [#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 支持
  - `Inject Script`: 用于修改网站的用户自定义脚本
  - `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` 防止网站安全检测,默认值为空
    - `Switch Origin` ([#14](https://github.com/lencx/ChatGPT/issues/14)): 切换网站源地址,默认为 `https://chat.openai.com`。需要注意的是镜像网站的 UI 需要和原网站一致,否则可能会导致某些功能不工作
  - `Go to Config`: 打开 ChatGPT 配置目录 (`path: ~/.chatgpt/*`)
  - `Clear Config`: 清除 ChatGPT 配置数据 (`path: ~/.chatgpt/*`), 这是危险操作,请提前备份数据
  - `Restart ChatGPT`: 重启应用。如果注入脚本编辑完成,或者应用可卡死可以通过此菜单重新启动应用
  - `Awesome ChatGPT`: 一个很棒的 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.model.json` - ChatGPT 输入提示,通过斜杠命令来快速完成输入,主要包含三部分:
    - `user_custom` - 需要手动录入 (**Control Conter -> Language Model -> User Custom**)
    - `sync_prompts` - 从 [f/awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts) 同步数据 (**Control Conter -> Language Model -> Sync Prompts**)
    - `sync_custom` - 同步自定义的 json 或 csv 文件数据,支持本地和远程 (**Control Conter -> Language Model -> Sync Custom**)
  - `chat.model.cmd.json` - 过滤(是否启用)和排序处理后的斜杠命令数据
  - `[cache_model]` - 缓存同步或录入的数据
    - `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"
```

## 👀 预览

<img width="320" src="./assets/install.png" alt="install"> <img width="320" src="./assets/chatgpt-control-center-general.png" alt="control center">
<img width="320" src="./assets/chatgpt-export.png" alt="export"> <img width="320" src="./assets/chatgpt-dalle2-tray.png" alt="dalle2 tray">
<img width="320" src="./assets/auto-update.png" alt="auto update">

## ❓ 常见问题

### 不能打开 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) 项目为这个应用自定义指令功能所带来的启发

---

[![Star History Chart](https://api.star-history.com/svg?repos=lencx/chatgpt&type=Timeline)](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


================================================
FILE: ChatGPT/README.md
================================================
adapted from [ChatGPT桌面版](https://github.com/lencx/ChatGPT)


================================================
FILE: ChatGPT/UPDATE_LOG.md
================================================
# UPDATE LOG

**🛑 URGENT NOTICE: A hacker has been found to take advantage of the heat of `lencx/ChatGPT` to plant a Trojan horse after the fork project and rebuild the installer. If you have friends around you who are using this desktop application, please remind them not to download unknown links freely. Now the project will remove other installation ways and only provide this download link https://github.com/lencx/ChatGPT/releases**

**🛑 紧急通知:目前发现有黑客利用 `lencx/ChatGPT` 的热度,在 fork 项目后植入木马,重新构建安装程序。如果你身边有朋友正在使用此桌面应用,请提醒 TA 们不要随意下载不明链接。现在项目将删除其他安装途径,仅提供此下载链接 https://github.com/lencx/ChatGPT/releases**

---

**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**

## 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


================================================
FILE: ChatGPT/casks/chatgpt.rb
================================================
cask "chatgpt" do
  version "0.12.0"
  arch = Hardware::CPU.arch.to_s
  sha256s = {
    "x86_64" => "d7f32d11f86ad8ac073dd451452124324e1c9154c318f15b77b5cd254000a3c4",
    "aarch64" => "c4c10eeb4a2c9a885da13047340372f461d411711c20472fc673fbf958bf6378"
  }
  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


================================================
FILE: ChatGPT/index.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>
  </body>
</html>


================================================
FILE: ChatGPT/package.json
================================================
{
  "name": "chatgpt",
  "version": "0.0.0",
  "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=52 --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"
  },
  "dependencies": {
    "@ant-design/icons": "^4.8.0",
    "@monaco-editor/react": "^4.4.6",
    "@tauri-apps/api": "^1.2.0",
    "antd": "^5.1.0",
    "clsx": "^1.2.1",
    "dayjs": "^1.11.7",
    "github-markdown-css": "^5.1.0",
    "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"
  },
  "devDependencies": {
    "@tauri-apps/cli": "^1.2.2",
    "@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-plugin-commonjs": "^0.6.2",
    "vite-tsconfig-paths": "^4.0.2"
  },
  "engines": {
    "node": "^14.18.0 || ^16.0.0 || ^18.0.0"
  }
}


================================================
FILE: ChatGPT/rustfmt.toml
================================================
max_width = 100
hard_tabs = false
tab_spaces = 2
newline_style = "Auto"
use_small_heuristics = "Default"
reorder_imports = true
reorder_modules = true
remove_nested_parens = true
edition = "2021"
merge_derives = true
use_try_shorthand = false
use_field_init_shorthand = false
force_explicit_abi = true
# imports_granularity = "Crate"

================================================
FILE: ChatGPT/src/components/FilePath/index.tsx
================================================
import { FC, useEffect, useState } from 'react';
import clsx from 'clsx';
import { path, shell } from '@tauri-apps/api';

import { chatRoot } from '@/utils';

interface FilePathProps {
  paths?: string;
  label?: string;
  className?: string;
  content?: string;
  url?: string;
}

const FilePath: FC<FilePathProps> = ({ className, label = 'PATH', paths = '', url, content }) => {
  const [filePath, setPath] = useState('');

  useEffect(() => {
    if (!path && !url) return;
    (async () => {
      if (url) {
        setPath(url);
        return;
      }
      setPath(await path.join(await chatRoot(), ...paths.split('/').filter((i) => !!i)));
    })();
  }, [url, paths]);

  return (
    <div className={clsx(className, 'chat-file-path')}>
      <div>
        {label}:{' '}
        <a onClick={() => shell.open(filePath)} title={filePath}>
          {content ? content : filePath}
        </a>
      </div>
    </div>
  );
};

export default FilePath;


================================================
FILE: ChatGPT/src/components/Markdown/Editor.tsx
================================================
import { FC, useEffect, useState } from 'react';
import Editor from '@monaco-editor/react';
import { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';

import Markdown from '@/components/Markdown';
import './index.scss';

interface MarkdownEditorProps {
  value?: string;
  onChange?: (v: string) => void;
  mode?: string;
}

const MarkdownEditor: FC<MarkdownEditorProps> = ({ value = '', onChange, mode = 'split' }) => {
  const [content, setContent] = useState(value);

  useEffect(() => {
    setContent(value);
    onChange && onChange(value);
  }, [value]);

  const handleEdit = (e: any) => {
    setContent(e);
    onChange && onChange(e);
  };

  const isSplit = mode === 'split';

  return (
    <div className="md-main">
      <PanelGroup direction="horizontal">
        {['md', 'split'].includes(mode) && (
          <Panel>
            <Editor language="markdown" value={content} onChange={handleEdit} />
          </Panel>
        )}
        {isSplit && <PanelResizeHandle className="resize-handle" />}
        {['doc', 'split'].includes(mode) && (
          <Panel>
            <Markdown className="edit-preview">{content}</Markdown>
          </Panel>
        )}
      </PanelGroup>
    </div>
  );
};

export default MarkdownEditor;


================================================
FILE: ChatGPT/src/components/Markdown/index.scss
================================================
.markdown-body {
  height: 100%;
  overflow: auto;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans', Helvetica, Arial,
    sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji';

  &.edit-preview {
    padding: 10px;
    font-size: 14px;
  }

  pre,
  code {
    font-family: monospace, monospace;
  }
}

.md-main {
  height: calc(100vh - 130px);
  overflow: hidden;
}

.resize-handle {
  width: 0.25rem;
  transition: 250ms linear background-color;
  background-color: #7f8082;
  outline: none;

  &:hover,
  &[data-resize-handle-active] {
    background-color: #5194eb;
  }
}


================================================
FILE: ChatGPT/src/components/Markdown/index.tsx
================================================
import { FC } from 'react';
import clsx from 'clsx';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import SyntaxHighlighter from 'react-syntax-highlighter';
import agate from 'react-syntax-highlighter/dist/esm/styles/hljs/agate';
import 'github-markdown-css';

import './index.scss';

interface MarkdownProps {
  children: string;
  className?: string;
}

const Markdown: FC<MarkdownProps> = ({ children, className }) => {
  return (
    <div className={clsx(className, 'markdown-body')}>
      <div>
        <ReactMarkdown
          children={children}
          linkTarget="_blank"
          remarkPlugins={[remarkGfm]}
          rehypePlugins={[rehypeRaw]}
          components={{
            code({ node, inline, className, children, ...props }) {
              const match = /language-(\w+)/.exec(className || '');
              return !inline && match ? (
                <SyntaxHighlighter
                  children={String(children).replace(/\n$/, '')}
                  style={agate as any}
                  language={match[1]}
                  showLineNumbers
                  lineNumberStyle={{ color: '#999' }}
                  PreTag="div"
                  {...props}
                />
              ) : (
                <code className={className} {...props}>
                  {children}
                </code>
              );
            },
          }}
        />
      </div>
    </div>
  );
};

export default Markdown;


================================================
FILE: ChatGPT/src/components/SwitchOrigin/index.tsx
================================================
import { FC } from 'react';
import { Link } from 'react-router-dom';
import { Form, Select, Tag, Tooltip, Switch } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';

import useJson from '@/hooks/useJson';
import { DISABLE_AUTO_COMPLETE, CHAT_AWESOME_JSON } from '@/utils';
interface SwitchOriginProps {
  name: string;
}

const SwitchOrigin: FC<SwitchOriginProps> = ({ name }) => {
  const { json: list = [] } = useJson<any[]>(CHAT_AWESOME_JSON);
  const form = Form.useFormInstance();

  const labelName = `(${name === 'main' ? 'Main' : 'SystemTray'})`;
  const dashboardName = `${name}_dashboard`;
  const originName = `${name}_origin`;
  const isEnable = Form.useWatch(dashboardName, form);

  let urlList = [{ title: 'ChatGPT', url: 'https://chat.openai.com', init: true }];
  if (Array.isArray(list)) {
    urlList = urlList.concat(list);
  }

  return (
    <>
      <Form.Item
        label={
          <span>
            Dashboard {labelName}{' '}
            <Tooltip
              title={
                <div>
                  <p>
                    <b>Set Dashboard as the application default window.</b>
                  </p>
                  <p>
                    If this is enabled, the <Tag color="blue">Switch Origin {labelName}</Tag>{' '}
                    setting will be invalid.
                  </p>
                  <p>
                    If you want to add a new URL to the dashboard, add it in the{' '}
                    <Link to="/awesome">Awesome</Link> menu and make sure it is enabled.
                  </p>
                </div>
              }
            >
              <QuestionCircleOutlined style={{ color: '#1677ff' }} />
            </Tooltip>
          </span>
        }
        name={dashboardName}
        valuePropName="checked"
      >
        <Switch />
      </Form.Item>
      <Form.Item
        label={
          <span>
            Switch Origin {labelName}{' '}
            <Tooltip
              title={
                <div>
                  <p>
                    <b>Set a single URL as the application default window.</b>
                  </p>
                  <p>
                    If you need to set a new URL as the application loading window, please add the
                    URL in the <Link to="/awesome">Awesome</Link> menu and then select it.
                  </p>
                </div>
              }
            >
              <QuestionCircleOutlined style={{ color: '#1677ff' }} />
            </Tooltip>
          </span>
        }
        name={originName}
      >
        <Select disabled={isEnable} showSearch {...DISABLE_AUTO_COMPLETE} optionLabelProp="url">
          {urlList.map((i, idx) => (
            <Select.Option
              key={`${idx}_${i.url}`}
              label={i.title}
              value={i.url}
              title={`${i.title}${i.init ? '(Built-in)' : ''}: ${i.url}`}
            >
              <Tag color={i.init ? 'orange' : 'geekblue'}>{i.title}</Tag> {i.url}
            </Select.Option>
          ))}
        </Select>
      </Form.Item>
    </>
  );
};

export default SwitchOrigin;


================================================
FILE: ChatGPT/src/components/Tags/index.tsx
================================================
import { FC, useEffect, useRef, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Input, Tag } from 'antd';
import type { InputRef } from 'antd';

import { DISABLE_AUTO_COMPLETE } from '@/utils';

interface TagsProps {
  value?: string[];
  onChange?: (v: string[]) => void;
  addTxt?: string;
  max?: number;
}

const Tags: FC<TagsProps> = ({ max = 99, value = [], onChange, addTxt = 'New Tag' }) => {
  const [tags, setTags] = useState<string[]>(value);
  const [inputVisible, setInputVisible] = useState<boolean>(false);
  const [inputValue, setInputValue] = useState('');
  const inputRef = useRef<InputRef>(null);

  useEffect(() => {
    setTags(value);
  }, [value]);

  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);

  const handleClose = (removedTag: string) => {
    const newTags = tags.filter((tag) => tag !== removedTag);
    setTags(newTags);
  };

  const showInput = () => {
    setInputVisible(true);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    if (inputValue && tags.indexOf(inputValue) === -1) {
      const val = [...tags, inputValue];
      setTags(val);
      onChange && onChange(val);
    }
    setInputVisible(false);
    setInputValue('');
  };

  const forMap = (tag: string) => {
    const tagElem = (
      <Tag
        closable
        onClose={(e) => {
          e.preventDefault();
          handleClose(tag);
        }}
      >
        {tag}
      </Tag>
    );
    return (
      <span key={tag} style={{ display: 'inline-block' }}>
        {tagElem}
      </span>
    );
  };

  const tagChild = tags.map(forMap);

  return (
    <>
      <span style={{ marginBottom: 16 }}>{tagChild}</span>
      {inputVisible && (
        <Input
          ref={inputRef}
          type="text"
          size="small"
          style={{ width: 78 }}
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
          {...DISABLE_AUTO_COMPLETE}
        />
      )}
      {!inputVisible && tags.length < max && (
        <Tag onClick={showInput} className="chat-tag-new">
          <PlusOutlined /> {addTxt}
        </Tag>
      )}
    </>
  );
};

export default Tags;


================================================
FILE: ChatGPT/src/hooks/useChatModel.ts
================================================
import { useState, useEffect } from 'react';
import { clone } from 'lodash';
import { invoke } from '@tauri-apps/api';

import { CHAT_MODEL_JSON, CHAT_MODEL_CMD_JSON, readJSON, writeJSON } from '@/utils';
import useInit from '@/hooks/useInit';

export default function useChatModel(key: string, file = CHAT_MODEL_JSON) {
  const [modelJson, setModelJson] = useState<Record<string, any>>({});

  useInit(async () => {
    const data = await readJSON(file, {
      defaultVal: { name: 'ChatGPT Model', [key]: null },
    });
    setModelJson(data);
  });

  const modelSet = async (data: Record<string, any>[] | Record<string, any>) => {
    const oData = clone(modelJson);
    oData[key] = data;
    await writeJSON(file, oData);
    setModelJson(oData);
  };

  return { modelJson, modelSet, modelData: modelJson?.[key] || [] };
}

export function useCacheModel(file = '') {
  const [modelCacheJson, setModelCacheJson] = useState<Record<string, any>[]>([]);

  useEffect(() => {
    if (!file) return;
    (async () => {
      const data = await readJSON(file, { isRoot: true, isList: true });
      setModelCacheJson(data);
    })();
  }, [file]);

  const modelCacheSet = async (data: Record<string, any>[], newFile = '') => {
    await writeJSON(newFile ? newFile : file, data, { isRoot: true });
    setModelCacheJson(data);
    await modelCacheCmd();
  };

  const modelCacheCmd = async () => {
    // Generate the `chat.model.cmd.json` file and refresh the page for the slash command to take effect.
    const list = await invoke('cmd_list');
    await writeJSON(CHAT_MODEL_CMD_JSON, {
      name: 'ChatGPT CMD',
      last_updated: Date.now(),
      data: list,
    });
    await invoke('window_reload', { label: 'core' });
    await invoke('window_reload', { label: 'tray' });
  };

  return { modelCacheJson, modelCacheSet, modelCacheCmd };
}


================================================
FILE: ChatGPT/src/hooks/useColumns.tsx
================================================
import { FC, useState, useCallback } from 'react';
import { Input } from 'antd';

import { DISABLE_AUTO_COMPLETE } from '@/utils';

export default function useColumns(columns: any[] = []) {
  const [opType, setOpType] = useState('');
  const [opRecord, setRecord] = useState<Record<string | symbol, any> | null>(null);
  const [opTime, setNow] = useState<number | null>(null);
  const [opExtra, setExtra] = useState<any>(null);

  const handleRecord = useCallback((row: Record<string, any> | null, type: string) => {
    setOpType(type);
    setRecord(row);
    setNow(Date.now());
  }, []);

  const resetRecord = useCallback(() => {
    setRecord(null);
    setOpType('');
    setNow(Date.now());
  }, []);

  const opNew = useCallback(() => handleRecord(null, 'new'), [handleRecord]);

  const cols = columns.map((i: any) => {
    if (i.render) {
      const opRender = i.render;
      i.render = (text: string, row: Record<string, any>) => {
        return opRender(text, row, { setRecord: handleRecord, setExtra });
      };
    }
    return i;
  });

  return {
    opTime,
    opType,
    opNew,
    columns: cols,
    opRecord,
    setRecord: handleRecord,
    resetRecord,
    setExtra,
    opExtra,
  };
}

interface EditRowProps {
  rowKey: string;
  row: Record<string, any>;
  actions: any;
}
export const EditRow: FC<EditRowProps> = ({ rowKey, row, actions }) => {
  const [isEdit, setEdit] = useState(false);
  const [val, setVal] = useState(row[rowKey] || '');
  const handleEdit = () => {
    setEdit(true);
  };
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setVal(e.target.value);
  };

  const handleSave = () => {
    setEdit(false);
    row[rowKey] = val?.trim();
    actions?.setRecord(row, 'rowedit');
  };

  return isEdit ? (
    <Input
      value={val}
      autoFocus
      onChange={handleChange}
      {...DISABLE_AUTO_COMPLETE}
      onPressEnter={handleSave}
    />
  ) : (
    <div className="rowedit" onClick={handleEdit}>
      {val}
    </div>
  );
};


================================================
FILE: ChatGPT/src/hooks/useData.ts
================================================
import { useState, useEffect } from 'react';
import { v4 } from 'uuid';

export const safeKey = Symbol('chat-id');

export default function useData(oData: any[]) {
  const [opData, setData] = useState<any[]>([]);

  useEffect(() => {
    opInit(oData);
  }, []);

  const opAdd = (val: any) => {
    const v = [val, ...opData];
    setData(v);
    return v;
  };

  const opInit = (val: any[] = []) => {
    if (!val || !Array.isArray(val)) return;
    const nData = val.map((i) => ({ [safeKey]: v4(), ...i }));
    setData(nData);
  };

  const opRemove = (id: string) => {
    const nData = opData.filter((i) => i[safeKey] !== id);
    setData(nData);
    return nData;
  };

  const opRemoveItems = (ids: string[]) => {
    const nData = opData.filter((i) => !ids.includes(i[safeKey]));
    setData(nData);
    return nData;
  };

  const opReplace = (id: string, data: any) => {
    const nData = [...opData];
    const idx = opData.findIndex((v) => v[safeKey] === id);
    nData[idx] = data;
    setData(nData);
    return nData;
  };

  const opReplaceItems = (ids: string[], data: any) => {
    const nData = [...opData];
    let count = 0;
    for (let i = 0; i < nData.length; i++) {
      const v = nData[i];
      if (ids.includes(v[safeKey])) {
        count++;
        nData[i] = { ...v, ...data };
      }
      if (count === ids.length) break;
    }
    setData(nData);
    return nData;
  };

  return {
    opSafeKey: safeKey,
    opInit,
    opReplace,
    opAdd,
    opRemove,
    opRemoveItems,
    opData,
    opReplaceItems,
  };
}


================================================
FILE: ChatGPT/src/hooks/useInit.ts
================================================
import { useRef, useEffect } from 'react';

// fix: Two interface requests will be made in development mode
export default function useInit(callback: () => void) {
  const isInit = useRef(true);
  useEffect(() => {
    if (isInit.current) {
      callback();
      isInit.current = false;
    }
  });
}


================================================
FILE: ChatGPT/src/hooks/useJson.ts
================================================
import { useState } from 'react';

import { readJSON, writeJSON } from '@/utils';
import useInit from '@/hooks/useInit';

export default function useJson<T>(file: string) {
  const [json, setData] = useState<T>();

  const refreshJson = async () => {
    const data = await readJSON(file);
    setData(data);
    return data;
  };

  const updateJson = async (data: any) => {
    await writeJSON(file, data);
    await refreshJson();
  };

  useInit(refreshJson);

  return { json, refreshJson, updateJson };
}


================================================
FILE: ChatGPT/src/hooks/useTable.tsx
================================================
import React, { useState } from 'react';
import { Table } from 'antd';
import type { TableRowSelection } from 'antd/es/table/interface';

import { safeKey } from '@/hooks/useData';

type rowSelectionOptions = {
  key: 'id' | string;
  rowType: 'id' | 'row' | 'all';
};
export function useTableRowSelection(options?: Partial<rowSelectionOptions>) {
  const { key = 'id', rowType = 'id' } = options || {};
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRowIDs, setSelectedRowIDs] = useState<string[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string | symbol, any>[]>([]);

  const onSelectChange = (
    newSelectedRowKeys: React.Key[],
    newSelectedRows: Record<string | symbol, any>[],
  ) => {
    const keys = newSelectedRows.map((i: any) => i[safeKey] || i[key]);
    setSelectedRowKeys(newSelectedRowKeys);
    if (rowType === 'id') {
      setSelectedRowIDs(keys);
    }
    if (rowType === 'row') {
      setSelectedRows(newSelectedRows);
    }
    if (rowType === 'all') {
      setSelectedRowIDs(keys);
      setSelectedRows(newSelectedRows);
    }
  };

  const rowReset = () => {
    setSelectedRowKeys([]);
    setSelectedRowIDs([]);
    setSelectedRows([]);
  };

  const rowSelection: TableRowSelection<Record<string, any>> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT, Table.SELECTION_NONE],
  };

  return { rowSelection, selectedRowIDs, selectedRows, rowReset };
}

export const TABLE_PAGINATION = {
  hideOnSinglePage: true,
  showSizeChanger: true,
  showQuickJumper: true,
  defaultPageSize: 10,
  pageSizeOptions: [5, 10, 15, 20],
  showTotal: (total: number) => <span>Total {total} items</span>,
};


================================================
FILE: ChatGPT/src/icons/SplitIcon.tsx
================================================
import Icon from '@ant-design/icons';
import type { CustomIconComponentProps } from '@ant-design/icons/lib/components/Icon';

interface IconProps {
  onClick: () => void;
}

export default function SplitIcon(props: Partial<CustomIconComponentProps & IconProps>) {
  return (
    <Icon
      {...props}
      component={() => (
        <svg
          className="chatico"
          viewBox="0 0 1024 1024"
          width="1em"
          height="1em"
          fill="currentColor"
        >
          <path d="M252.068571 906.496h520.283429c89.581714 0 134.144-44.562286 134.144-132.845714V250.331429c0-88.283429-44.562286-132.845714-134.144-132.845715H252.068571c-89.142857 0-134.582857 44.141714-134.582857 132.845715V773.668571c0 88.704 45.44 132.845714 134.582857 132.845715z m1.28-68.992c-42.843429 0-66.852571-22.710857-66.852571-67.291429V253.805714c0-44.580571 24.009143-67.291429 66.852571-67.291428h222.866286v651.008z m517.723429-651.008c42.422857 0 66.432 22.710857 66.432 67.291429V770.194286c0 44.580571-24.009143 67.291429-66.432 67.291428H548.205714V186.496z" />
        </svg>
      )}
    />
  );
}


================================================
FILE: ChatGPT/src/layout/index.scss
================================================
.chat-logo {
  text-align: center;
  height: 48px;

  img {
    width: 44px;
    height: 44px;
    margin-top: 4px;
  }
}

.chat-info {
  text-align: center;
  font-weight: bold;

  .ant-tag {
    margin: 2px;
  }
}

.ant-layout-sider-trigger {
  user-select: none;
  -webkit-user-select: none;
}

.ant-layout-sider-children {
  overflow-y: auto;
}

.chat-container {
  padding: 20px;
  overflow: hidden;
}

.ant-menu {
  user-select: none;
  -webkit-user-select: none;
}

.ant-layout-footer {
  color: #666 !important;
  opacity: 0.7;
}


================================================
FILE: ChatGPT/src/layout/index.tsx
================================================
import { useEffect, useState } from 'react';
import { Layout, Menu, Tooltip, ConfigProvider, theme, Tag } from 'antd';
import { SyncOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { getName, getVersion } from '@tauri-apps/api/app';
import { invoke } from '@tauri-apps/api';

import useInit from '@/hooks/useInit';
import Routes, { menuItems } from '@/routes';
import './index.scss';

const { Content, Footer, Sider } = Layout;

export default function ChatLayout() {
  const [collapsed, setCollapsed] = useState(false);
  const [isDashboard, setDashboard] = useState<any>(null);
  const [appInfo, setAppInfo] = useState<Record<string, any>>({});
  const location = useLocation();
  const [menuKey, setMenuKey] = useState(location.pathname);
  const go = useNavigate();

  useEffect(() => {
    if (location.search === '?type=control') {
      go('/settings');
    }
    if (location.search === '?type=preview') {
      go('/?type=preview');
    }
    setMenuKey(location.pathname);
    setDashboard(location.pathname === '/');
  }, [location.pathname]);

  useInit(async () => {
    setAppInfo({
      appName: await getName(),
      appVersion: await getVersion(),
      appTheme: await invoke('get_theme'),
    });
  });

  const checkAppUpdate = async () => {
    await invoke('run_check_update', { silent: false, hasMsg: true });
  };

  const isDark = appInfo.appTheme === 'dark';

  if (isDashboard === null) return null;

  return (
    <ConfigProvider theme={{ algorithm: isDark ? theme.darkAlgorithm : theme.defaultAlgorithm }}>
      {isDashboard ? (
        <Routes />
      ) : (
        <Layout style={{ minHeight: '100vh' }} hasSider>
          <Sider
            theme={isDark ? 'dark' : 'light'}
            collapsible
            collapsed={collapsed}
            onCollapse={(value) => setCollapsed(value)}
            style={{
              overflow: 'auto',
              height: '100vh',
              position: 'fixed',
              left: 0,
              top: 0,
              bottom: 0,
              zIndex: 999,
            }}
          >
            <div className="chat-logo">
              <img src="/logo.png" />
            </div>
            <div className="chat-info">
              <Tag>{appInfo.appName}</Tag>
              <Tag>
                <span style={{ marginRight: 5 }}>{appInfo.appVersion}</span>
                <Tooltip title="click to check update">
                  <a onClick={checkAppUpdate}>
                    <SyncOutlined />
                  </a>
                </Tooltip>
              </Tag>
            </div>

            <Menu
              selectedKeys={[menuKey]}
              mode="inline"
              theme={appInfo.appTheme === 'dark' ? 'dark' : 'light'}
              inlineIndent={12}
              items={menuItems}
              // defaultOpenKeys={['/model']}
              onClick={(i) => go(i.key)}
            />
          </Sider>
          <Layout
            className="chat-layout"
            style={{ marginLeft: collapsed ? 80 : 200, transition: 'margin-left 300ms ease-out' }}
          >
            <Content
              className="chat-container"
              style={{
                overflow: 'inherit',
              }}
            >
              <Routes />
            </Content>
            <Footer style={{ textAlign: 'center' }}>
              <a href="https://github.com/NsLearning/LangHelper" target="_blank">
                ChatGPT Desktop Application & LangHelper
              </a>{' '}
              ©2023 Created by lencx and Nslearning
            </Footer>
          </Layout>
        </Layout>
      )}
    </ConfigProvider>
  );
}


================================================
FILE: ChatGPT/src/main.scss
================================================
:root {
  font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
  font-size: 16px;
  line-height: 24px;
  font-weight: 400;

  color: #2a2a2a;
  background-color: #f6f6f6;

  font-synthesis: none;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  -webkit-text-size-adjust: 100%;
}

html,
body,
#root {
  padding: 0;
  margin: 0;
  height: 100%;
}

.ant-table-selection-col,
.ant-table-selection-column {
  width: 50px !important;
  min-width: 50px !important;
}

.chat-prompts-val {
  display: inline-block;
  width: 100%;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.ellipsis-line {
  display: inline-block;
  width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.rowedit {
  padding: 2px 5px;

  &:hover {
    box-shadow: 0 0 2px rgba(237, 122, 60, 0.8);
    border-radius: 4px;
  }
}

.chat-add-btn {
  margin-bottom: 5px;
}

.chat-tags,
.chat-prompts-tags {
  .ant-tag {
    margin: 2px;
  }
}

.chat-table-tip {
  > span {
    line-height: 16px;
  }
}

.chat-file-path {
  font-size: 12px;
  font-weight: 500;
  color: #888;
  margin-bottom: 3px;
  line-height: 16px;

  > div {
    max-width: 400px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  span {
    display: inline-block;
    // background-color: #d8d8d8;
    color: #4096ff;
    padding: 0 8px;
    height: 20px;
    line-height: 20px;
    border-radius: 4px;
    cursor: pointer;
    text-decoration: underline;
  }
}

.chatico {
  cursor: pointer;
}

.awesome-tips {
  .ant-tag {
    cursor: pointer;
  }
}


================================================
FILE: ChatGPT/src/main.tsx
================================================
import { StrictMode, Suspense } from 'react';
import { BrowserRouter } from 'react-router-dom';
import ReactDOM from 'react-dom/client';

import Layout from '@/layout';
import './main.scss';

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <StrictMode>
    <Suspense fallback={null}>
      <BrowserRouter>
        <Layout />
      </BrowserRouter>
    </Suspense>
  </StrictMode>,
);


================================================
FILE: ChatGPT/src/routes.tsx
================================================
import { useRoutes } from 'react-router-dom';
import {
  SettingOutlined,
  BulbOutlined,
  SyncOutlined,
  FileSyncOutlined,
  UserOutlined,
  DownloadOutlined,
  FormOutlined,
  GlobalOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';

import Settings from '@/view/settings';
import About from '@/view/about';
import Awesome from '@/view/awesome';
import UserCustom from '@/view/model/UserCustom';
import SyncPrompts from '@/view/model/SyncPrompts';
import SyncCustom from '@/view/model/SyncCustom';
import SyncRecord from '@/view/model/SyncRecord';
import Download from '@/view/download';
import Notes from '@/view/notes';
import Markdown from '@/view/markdown';
import Dashboard from '@/view/dashboard';

export type ChatRouteMetaObject = {
  label: string;
  icon?: React.ReactNode;
};

type ChatRouteObject = {
  path: string;
  element?: JSX.Element;
  hideMenu?: boolean;
  meta?: ChatRouteMetaObject;
  children?: ChatRouteObject[];
};

export const routes: Array<ChatRouteObject> = [
  {
    path: '/settings',
    element: <Settings />,
    meta: {
      label: 'Settings',
      icon: <SettingOutlined />,
    },
  },
  {
    path: '/awesome',
    element: <Awesome />,
    meta: {
      label: 'Awesome',
      icon: <GlobalOutlined />,
    },
  },
  {
    path: '/notes',
    element: <Notes />,
    meta: {
      label: 'Notes',
      icon: <FormOutlined />,
    },
  },
  {
    path: '/md/:id',
    element: <Markdown />,
    hideMenu: true,
  },
  {
    path: '/model',
    meta: {
      label: 'Language Model',
      icon: <BulbOutlined />,
    },
    children: [
      {
        path: 'user-custom',
        element: <UserCustom />,
        meta: {
          label: 'User Custom',
          icon: <UserOutlined />,
        },
      },
      // --- Sync
      {
        path: 'sync-prompts',
        element: <SyncPrompts />,
        meta: {
          label: 'Sync Prompts',
          icon: <SyncOutlined />,
        },
      },
      {
        path: 'sync-custom',
        element: <SyncCustom />,
        meta: {
          label: 'Sync Custom',
          icon: <FileSyncOutlined />,
        },
      },
      {
        path: 'sync-custom/:id',
        element: <SyncRecord />,
        hideMenu: true,
      },
    ],
  },
  {
    path: '/download',
    element: <Download />,
    meta: {
      label: 'Download',
      icon: <DownloadOutlined />,
    },
  },
  {
    path: '/about',
    element: <About />,
    meta: {
      label: 'About',
      icon: <InfoCircleOutlined />,
    },
  },
  {
    path: '/',
    element: <Dashboard />,
    hideMenu: true,
  },
];

type MenuItem = Required<MenuProps>['items'][number];
export const menuItems: MenuItem[] = routes
  .filter((j) => !j.hideMenu)
  .map((i) => ({
    ...i.meta,
    key: i.path || '',
    children: i?.children
      ?.filter((j) => !j.hideMenu)
      ?.map((j) => ({ ...j.meta, key: `${i.path}/${j.path}` || '' })),
  }));

export default () => {
  return useRoutes(routes);
};


================================================
FILE: ChatGPT/src/utils.ts
================================================
import { readTextFile, writeTextFile, exists, createDir } from '@tauri-apps/api/fs';
import { homeDir, join, dirname } from '@tauri-apps/api/path';
import dayjs from 'dayjs';

export const APP_CONF_JSON = 'chat.conf.json';
export const CHAT_MODEL_JSON = 'chat.model.json';
export const CHAT_MODEL_CMD_JSON = 'chat.model.cmd.json';
export const CHAT_DOWNLOAD_JSON = 'chat.download.json';
export const CHAT_AWESOME_JSON = 'chat.awesome.json';
export const CHAT_NOTES_JSON = 'chat.notes.json';
export const CHAT_PROMPTS_CSV = 'chat.prompts.csv';
export const GITHUB_PROMPTS_CSV_URL =
  'https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv';
export const GITHUB_LOG_URL = 'https://raw.githubusercontent.com/lencx/ChatGPT/main/UPDATE_LOG.md';

export const DISABLE_AUTO_COMPLETE = {
  autoCapitalize: 'off',
  autoComplete: 'off',
  spellCheck: false,
};

export const chatRoot = async () => {
  return join(await homeDir(), '.chatgpt');
};

export const chatModelPath = async (): Promise<string> => {
  return join(await chatRoot(), CHAT_MODEL_JSON);
};

export const chatPromptsPath = async (): Promise<string> => {
  return join(await chatRoot(), CHAT_PROMPTS_CSV);
};

type readJSONOpts = { defaultVal?: Record<string, any>; isRoot?: boolean; isList?: boolean };
export const readJSON = async (path: string, opts: readJSONOpts = {}) => {
  const { defaultVal = {}, isRoot = false, isList = false } = opts;
  const root = await chatRoot();
  let file = path;

  if (!isRoot) {
    file = await join(root, path);
  }

  if (!(await exists(file))) {
    if ((await dirname(file)) !== root) {
      await createDir(await dirname(file), { recursive: true });
    }
    await writeTextFile(
      file,
      isList
        ? '[]'
        : JSON.stringify(
            {
              name: 'ChatGPT',
              link: 'https://github.com/lencx/ChatGPT',
              ...defaultVal,
            },
            null,
            2,
          ),
    );
  }

  try {
    return JSON.parse(await readTextFile(file));
  } catch (e) {
    return {};
  }
};

type writeJSONOpts = { dir?: string; isRoot?: boolean };
export const writeJSON = async (
  path: string,
  data: Record<string, any>,
  opts: writeJSONOpts = {},
) => {
  const { isRoot = false } = opts;
  const root = await chatRoot();
  let file = path;

  if (!isRoot) {
    file = await join(root, path);
  }

  if (isRoot && !(await exists(await dirname(file)))) {
    await createDir(await dirname(file), { recursive: true });
  }

  await writeTextFile(file, JSON.stringify(data, null, 2));
};

export const fmtDate = (date: any) => dayjs(date).format('YYYY-MM-DD HH:mm:ss');

export const genCmd = (act: string) =>
  act
    .replace(/\s+|\/+/g, '_')
    .replace(/[^\d\w]/g, '')
    .toLocaleLowerCase();


================================================
FILE: ChatGPT/src/view/about/index.scss
================================================
.about {
  .log-tab {
    font-size: 14px;

    h2 {
      font-size: 16px;
    }
  }

  .markdown-body {
    background-color: unset;
  }

  .about-tab {
    .imgs {
      img {
        max-width: 200px;
        margin-bottom: 20px;
      }
    }
  }

  code {
    background-color: rgba(200, 200, 200, 0.4);
    padding: 2px 4px;
    border-radius: 5px;
  }
}


================================================
FILE: ChatGPT/src/view/about/index.tsx
================================================
import { useState } from 'react';
import { invoke } from '@tauri-apps/api';
import { Tabs, Tag } from 'antd';

import { GITHUB_LOG_URL } from '@/utils';
import useInit from '@/hooks/useInit';
import Markdown from '@/components/Markdown';
import './index.scss';

export default function About() {
  const [logContent, setLogContent] = useState('');

  useInit(async () => {
    const data = (await invoke('get_data', { url: GITHUB_LOG_URL })) || '';
    setLogContent(data as string);
  });

  return (
    <div className="about">
      <Tabs
        items={[
          { label: 'About LangHelper', key: 'langhelper', children: <AboutLangHelper /> },
          { label: 'About ChatGPT', key: 'about', children: <AboutChatGPT /> },
          { label: 'Update Log', key: 'log', children: <LogTab content={logContent} /> },
        ]}
      />
    </div>
  );
}

const AboutLangHelper = () =>{
  return (
    <div className="about-tab">
      <p>
        This is new function for learning languages, you can talk with ChatGPT with natural
        AI sound, get pronuciation assessment, memorize words with context, practice listening,
        so on, its based on ChatGPT Desktop@lencx, I've been developing this language helper on 
        the shoulders of gaints, if it helps you, do not hesitate to star it, any problems
        you can follow my channel
        <a href="https://space.bilibili.com/33672855" target="_blank"> https://space.bilibili.com/33672855 </a>
        to get solutions and update,
        and if you have new ideas for it, please contact my email
        <a> nslearning888@gmail.com</a>
           
      </p>
    </div>
  )
}

const AboutChatGPT = () => {
  return (
    <div className="about-tab">
      <Tag>ChatGPT Desktop Application (Mac, Windows and Linux)</Tag>
      <p>
        🕒 History versions:{' '}
        <a href="https://github.com/lencx/ChatGPT/releases" target="_blank">
          lencx/ChatGPT/releases
        </a>
      </p>
      <p>
        It is just a wrapper for the
        <a href="https://chat.openai.com" target="_blank" title="https://chat.openai.com">
          {' '}
          OpenAI ChatGPT{' '}
        </a>
        website, no other data transfer exists (you can check the{' '}
        <a
          href="https://github.com/lencx/ChatGPT"
          target="_blank"
          title="https://github.com/lencx/ChatGPT"
        >
          {' '}
          source code{' '}
        </a>
        ). The development and maintenance of this software has taken up a lot of my time. If it
        helps you, you can buy me a cup of coffee (Chinese users can use WeChat to scan the code),
        thanks!
      </p>
      <p className="imgs" style={{ float: 'left' }}>
        <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"
          />
        </a>{' '}
        <br />
        <img
          width="200"
          src="https://user-images.githubusercontent.com/16164244/207228025-117b5f77-c5d2-48c2-a070-774b7a1596f2.png"
        />
      </p>
      <img
        width="250"
        src="https://user-images.githubusercontent.com/16164244/219439614-d5c3710c-e0b3-4df9-9b3c-c150ba0ba5f1.png"
      />
    </div>
  );
};

const LogTab = ({ content }: { content: string }) => {
  return (
    <div>
      <p>
        Ref:{' '}
        <a href="https://github.com/lencx/ChatGPT/blob/main/UPDATE_LOG.md" target="_blank">
          lencx/ChatGPT/UPDATE_LOG.md
        </a>
      </p>
      <Markdown className="log-tab" children={content} />
    </div>
  );
};


================================================
FILE: ChatGPT/src/view/awesome/Form.tsx
================================================
import { useEffect, ForwardRefRenderFunction, useImperativeHandle, forwardRef } from 'react';
import { Form, Input, Switch } from 'antd';
import type { FormProps } from 'antd';

import Tags from '@comps/Tags';
import { DISABLE_AUTO_COMPLETE } from '@/utils';

interface AwesomeFormProps {
  record?: Record<string | symbol, any> | null;
}

const initFormValue = {
  title: '',
  url: '',
  enable: true,
  tags: [],
  category: '',
};

const AwesomeForm: ForwardRefRenderFunction<FormProps, AwesomeFormProps> = ({ record }, ref) => {
  const [form] = Form.useForm();
  useImperativeHandle(ref, () => ({ form }));

  useEffect(() => {
    if (record) {
      form.setFieldsValue(record);
    }
  }, [record]);

  return (
    <Form form={form} labelCol={{ span: 4 }} initialValues={initFormValue}>
      <Form.Item
        label="Title"
        name="title"
        rules={[{ required: true, message: 'Please enter a title!' }]}
      >
        <Input placeholder="Please enter a title" {...DISABLE_AUTO_COMPLETE} />
      </Form.Item>
      <Form.Item
        label="URL"
        name="url"
        rules={[{ required: true, message: 'Please enter the URL' }, { type: 'url' }]}
      >
        <Input placeholder="Please enter the URL" {...DISABLE_AUTO_COMPLETE} />
      </Form.Item>
      <Form.Item
        label="Category"
        name="category"
        rules={[{ required: true, message: 'Please enter a category' }]}
      >
        <Input placeholder="Please enter a category" {...DISABLE_AUTO_COMPLETE} />
      </Form.Item>
      <Form.Item label="Tags" name="tags">
        <Tags value={record?.tags} />
      </Form.Item>
      <Form.Item label="Enable" name="enable" valuePropName="checked">
        <Switch />
      </Form.Item>
    </Form>
  );
};

export default forwardRef(AwesomeForm);


================================================
FILE: ChatGPT/src/view/awesome/config.tsx
================================================
import { Tag, Space, Popconfirm, Switch } from 'antd';
import { open } from '@tauri-apps/api/shell';

export const awesomeColumns = () => [
  {
    title: 'Title',
    dataIndex: 'title',
    fixed: 'left',
    key: 'title',
    width: 160,
  },
  {
    title: 'URL',
    dataIndex: 'url',
    key: 'url',
    width: 200,
    render: (v: string) => <a onClick={() => open(v)}>{v}</a>,
  },
  // {
  //   title: 'Icon',
  //   dataIndex: 'icon',
  //   key: 'icon',
  //   width: 120,
  // },
  {
    title: 'Enable',
    dataIndex: 'enable',
    key: 'enable',
    width: 80,
    render: (v: boolean = true, row: Record<string, any>, action: Record<string, any>) => (
      <Switch checked={v} onChange={(v) => action.setRecord({ ...row, enable: v }, 'enable')} />
    ),
  },
  {
    title: 'Category',
    dataIndex: 'category',
    key: 'category',
    width: 120,
    render: (v: string) => <Tag color="geekblue">{v}</Tag>,
  },
  {
    title: 'Tags',
    dataIndex: 'tags',
    key: 'tags',
    width: 150,
    render: (v: string[]) => (
      <span className="chat-tags">
        {v?.map((i) => (
          <Tag key={i}>{i}</Tag>
        ))}
      </span>
    ),
  },
  {
    title: 'Action',
    fixed: 'right',
    width: 150,
    render: (_: any, row: any, actions: any) => {
      return (
        <Space>
          <a onClick={() => actions.setRecord(row, 'edit')}>Edit</a>
          <Popconfirm
            title="Are you sure you want to delete this URL?"
            onConfirm={() => actions.setRecord(row, 'delete')}
            okText="Yes"
            cancelText="No"
          >
            <a>Delete</a>
          </Popconfirm>
        </Space>
      );
    },
  },
];


================================================
FILE: ChatGPT/src/view/awesome/index.tsx
================================================
import { useRef, useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Table, Modal, Popconfirm, Button, Tooltip, Tag, message } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { invoke } from '@tauri-apps/api';

import useJson from '@/hooks/useJson';
import useData from '@/hooks/useData';
import useColumns from '@/hooks/useColumns';
import FilePath from '@/components/FilePath';
import { CHAT_AWESOME_JSON } from '@/utils';
import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable';
import { awesomeColumns } from './config';
import AwesomeForm from './Form';

export default function Awesome() {
  const formRef = useRef<any>(null);
  const [isVisible, setVisible] = useState(false);
  const { opData, opInit, opAdd, opReplace, opReplaceItems, opRemove, opRemoveItems, opSafeKey } =
    useData([]);
  const { columns, ...opInfo } = useColumns(awesomeColumns());
  const { rowSelection, selectedRowIDs, rowReset } = useTableRowSelection();
  const { json, updateJson } = useJson<any[]>(CHAT_AWESOME_JSON);
  const selectedItems = rowSelection.selectedRowKeys || [];

  useEffect(() => {
    if (!json || json.length <= 0) return;
    opInit(json);
  }, [json?.length]);

  useEffect(() => {
    if (!opInfo.opType) return;
    if (['edit', 'new'].includes(opInfo.opType)) {
      setVisible(true);
    }
    if (['delete'].includes(opInfo.opType)) {
      const data = opRemove(opInfo?.opRecord?.[opSafeKey]);
      updateJson(data);
      opInfo.resetRecord();
    }
  }, [opInfo.opType, formRef]);

  const hide = () => {
    setVisible(false);
    opInfo.resetRecord();
  };

  useEffect(() => {
    if (opInfo.opType === 'enable') {
      const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord);
      updateJson(data);
    }
  }, [opInfo.opTime]);

  const handleDelete = () => {
    const data = opRemoveItems(selectedRowIDs);
    updateJson(data);
    rowReset();
    message.success('All selected URLs have been deleted');
  };

  const handleOk = () => {
    formRef.current?.form?.validateFields().then(async (vals: Record<string, any>) => {
      let idx = opData.findIndex((i) => i.url === vals.url);
      if (vals.url === opInfo?.opRecord?.url) {
        idx = -1;
      }
      if (idx === -1) {
        if (opInfo.opType === 'new') {
          const data = opAdd(vals);
          await updateJson(data);
          opInit(data);
          message.success('Data added successfully');
        }
        if (opInfo.opType === 'edit') {
          const data = opReplace(opInfo?.opRecord?.[opSafeKey], vals);
          await updateJson(data);
          message.success('Data updated successfully');
        }
        hide();
      } else {
        const data = opData[idx];
        message.error(
          <div style={{ width: 360 }}>
            <div>
              <b>
                {data.title}: {data.url}
              </b>
            </div>
            <div>This URL already exists, please edit it and try again.</div>
          </div>,
        );
      }
    });
  };

  const handleEnable = (isEnable: boolean) => {
    const data = opReplaceItems(selectedRowIDs, { enable: isEnable });
    updateJson(data);
  };

  const handlePreview = () => {
    invoke('wa_window', {
      label: 'awesome_preview',
      url: 'index.html?type=preview',
      title: 'Preview Dashboard',
    });
  };

  const modalTitle = `${{ new: 'Create', edit: 'Edit' }[opInfo.opType]} URL`;

  return (
    <div>
      <div className="chat-table-btns">
        <div>
          <Button className="chat-add-btn" type="primary" onClick={opInfo.opNew}>
            Add URL
          </Button>
          <Button type="dashed" onClick={handlePreview}>
            Preview Dashboard
          </Button>
          <PreviewTip />
        </div>
        <div>
          {selectedItems.length > 0 && (
            <>
              <Button type="primary" onClick={() => handleEnable(true)}>
                Enable
              </Button>
              <Button onClick={() => handleEnable(false)}>Disable</Button>
              <Popconfirm
                overlayStyle={{ width: 250 }}
                title="URLs cannot be recovered after deletion, are you sure you want to delete them?"
                placement="topLeft"
                onConfirm={handleDelete}
                okText="Yes"
                cancelText="No"
              >
                <Button>Delete</Button>
              </Popconfirm>
              <span className="num">Selected {selectedItems.length} items</span>
            </>
          )}
        </div>
      </div>
      <FilePath paths={CHAT_AWESOME_JSON} />
      <Table
        rowKey="url"
        columns={columns}
        scroll={{ x: 800 }}
        dataSource={opData}
        rowSelection={rowSelection}
        pagination={TABLE_PAGINATION}
      />
      <Modal
        open={isVisible}
        title={modalTitle}
        onCancel={hide}
        onOk={handleOk}
        destroyOnClose
        maskClosable={false}
      >
        <AwesomeForm ref={formRef} record={opInfo?.opRecord} />
      </Modal>
    </div>
  );
}

const PreviewTip = () => {
  const go = useNavigate();
  const handleGo = (v: string) => {
    go(`/settings?type=${v}`);
  };

  return (
    <Tooltip
      overlayInnerStyle={{ width: 400 }}
      title={
        <div className="awesome-tips">
          Click the button to preview, and in
          <Link to="/settings"> Settings </Link>
          you can set a single URL or Dashboard as the default window for the app.
          <br />
          <Tag onClick={() => handleGo('main_window')} color="blue">
            Main Window
          </Tag>
          {'or '}
          <Tag onClick={() => handleGo('tray_window')} color="blue">
            SystemTray Window
          </Tag>
        </div>
      }
    >
      <QuestionCircleOutlined style={{ marginLeft: 5, color: '#1677ff' }} />
    </Tooltip>
  );
};


================================================
FILE: ChatGPT/src/view/dashboard/index.scss
================================================
.dashboard {
  position: fixed;
  width: calc(100% - 30px);
  height: calc(100% - 30px);
  overflow-y: auto;
  padding: 15px;

  &-no-data {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    flex-direction: column;
    font-weight: bold;

    .icon {
      color: #989898;
      font-size: 24px;
    }

    .txt {
      padding: 10px;
      font-size: 12px;
      line-height: 16px;

      a {
        color: #1677ff;
        cursor: pointer;
      }
    }
  }

  &.dark {
    background-color: #000;
  }

  &.has-top-dom {
    padding-top: 30px;
  }

  &.preview {
    padding-top: 15px;
  }

  .group-item {
    margin-bottom: 20px;

    .title {
      font-weight: bold;
      font-size: 18px;
      margin-bottom: 10px;
    }

    .item {
      .ant-card-body {
        padding: 10px;
        text-align: center;
        font-weight: 500;
        font-size: 14px;
      }

      span {
        display: block;
        height: 100%;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}


================================================
FILE: ChatGPT/src/view/dashboard/index.tsx
================================================
import { useEffect, useState } from 'react';
import clsx from 'clsx';
import { useSearchParams } from 'react-router-dom';
import { Row, Col, Card } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import { os, invoke } from '@tauri-apps/api';

import useInit from '@/hooks/useInit';
import useJson from '@/hooks/useJson';
import { CHAT_AWESOME_JSON, APP_CONF_JSON, readJSON } from '@/utils';
import './index.scss';

export default function Dashboard() {
  const [params] = useSearchParams();
  const { json } = useJson<Record<string, any>[]>(CHAT_AWESOME_JSON);
  const [list, setList] = useState<Array<[string, Record<string, any>[]]>>();
  const [hasClass, setClass] = useState(false);
  const [theme, setTheme] = useState('');

  useInit(async () => {
    const getOS = await os.platform();
    const conf = await readJSON(APP_CONF_JSON);
    const appTheme = await invoke('get_theme');
    setTheme(appTheme as string);
    setClass(!conf?.titlebar && getOS === 'darwin');
  });

  useEffect(() => {
    if (!json) return;
    const categories = new Map();

    if (Array.isArray(json)) {
      json?.forEach((i) => {
        if (!i.enable) return;
        if (!categories.has(i.category)) {
          categories.set(i.category, []);
        }
        categories.get(i?.category).push(i);
      });
      setList(Array.from(categories) || []);
    } else {
      setList([]);
    }
  }, [JSON.stringify(json)]);

  const handleLink = async (item: Record<string, any>) => {
    await invoke('wa_window', {
      label: btoa(item.url).replace(/[^a-zA-Z0-9]/g, ''),
      title: item.title,
      url: item.url,
    });
  };

  if (!list) return null;
  if (list?.length === 0) {
    return (
      <div className="dashboard-no-data">
        <div className="icon">
          <InboxOutlined style={{ fontSize: 80, marginBottom: 5 }} />
          <br />
          No data
        </div>
        <div className="txt">
          Go to <a onClick={() => invoke('control_window')}>{'Control Center -> Awesome'}</a> to add
          data and make sure they are enabled.
        </div>
      </div>
    );
  }

  return (
    <div
      className={clsx('dashboard', theme, {
        'has-top-dom': hasClass,
        preview: params.get('type') === 'preview',
      })}
    >
      <div>
        {list.map((i) => {
          return (
            <div key={i[0]} className="group-item">
              <Card title={i[0]} size="small">
                <Row className="list" gutter={[8, 8]}>
                  {i[1].map((j, idx) => {
                    return (
                      <Col
                        title={`${j?.title}: ${j?.url}`}
                        key={`${idx}_${j?.url}`}
                        xl={4}
                        md={6}
                        sm={8}
                        xs={12}
                      >
                        <Card className="item" hoverable onClick={() => handleLink(j)}>
                          <span>{j?.title}</span>
                        </Card>
                      </Col>
                    );
                  })}
                </Row>
              </Card>
            </div>
          );
        })}
      </div>
    </div>
  );
}


================================================
FILE: ChatGPT/src/view/download/config.tsx
================================================
import { useState } from 'react';
import { Tag, Space, Popconfirm } from 'antd';
import { path, shell } from '@tauri-apps/api';

import { EditRow } from '@/hooks/useColumns';

import useInit from '@/hooks/useInit';
import { fmtDate, chatRoot } from '@/utils';

const colorMap: any = {
  pdf: 'blue',
  png: 'orange',
};

export const downloadColumns = () => [
  {
    title: 'Name',
    dataIndex: 'name',
    fixed: 'left',
    key: 'name',
    width: 240,
    render: (_: string, row: any, actions: any) => (
      <EditRow rowKey="name" row={row} actions={actions} />
    ),
  },
  {
    title: 'Extension',
    dataIndex: 'ext',
    key: 'ext',
    width: 120,
    render: (v: string) => <Tag color={colorMap[v]}>{v}</Tag>,
  },
  {
    title: 'Path',
    dataIndex: 'path',
    key: 'path',
    width: 200,
    render: (_: string, row: any) => <RenderPath row={row} />,
  },
  {
    title: 'Created',
    dataIndex: 'created',
    key: 'created',
    width: 150,
    render: fmtDate,
  },
  {
    title: 'Action',
    fixed: 'right',
    width: 150,
    render: (_: any, row: any, actions: any) => {
      return (
        <Space>
          <a onClick={() => actions.setRecord(row, 'preview')}>Preview</a>
          <Popconfirm
            title="Are you sure to delete this file?"
            onConfirm={() => actions.setRecord(row, 'delete')}
            okText="Yes"
            cancelText="No"
          >
            <a>Delete</a>
          </Popconfirm>
        </Space>
      );
    },
  },
];

const RenderPath = ({ row }: any) => {
  const [filePath, setFilePath] = useState('');
  useInit(async () => {
    setFilePath(await getPath(row));
  });
  return <a onClick={() => shell.open(filePath)}>{filePath}</a>;
};

export const getPath = async (row: any) => {
  const isImg = ['png'].includes(row?.ext);
  return (
    (await path.join(await chatRoot(), 'download', isImg ? 'img' : row.ext, row.id)) + `.${row.ext}`
  );
};


================================================
FILE: ChatGPT/src/view/download/index.tsx
================================================
import { useEffect, useState } from 'react';
import { Table, Modal, Popconfirm, Button, message } from 'antd';
import { invoke, path, fs } from '@tauri-apps/api';

import useJson from '@/hooks/useJson';
import useData from '@/hooks/useData';
import useColumns from '@/hooks/useColumns';
import FilePath from '@/components/FilePath';
import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable';
import { chatRoot, CHAT_DOWNLOAD_JSON } from '@/utils';
import { downloadColumns } from './config';

function renderFile(buff: Uint8Array, type: string) {
  const renderType = {
    pdf: 'application/pdf',
    png: 'image/png',
  }[type];
  return URL.createObjectURL(new Blob([buff], { type: renderType }));
}

export default function Download() {
  const [source, setSource] = useState('');
  const [isVisible, setVisible] = useState(false);
  const { opData, opInit, opReplace, opSafeKey } = useData([]);
  const { columns, ...opInfo } = useColumns(downloadColumns());
  const { rowSelection, selectedRows, rowReset } = useTableRowSelection({ rowType: 'row' });
  const { json, refreshJson, updateJson } = useJson<any[]>(CHAT_DOWNLOAD_JSON);
  const selectedItems = rowSelection.selectedRowKeys || [];

  useEffect(() => {
    if (!json || json.length <= 0) return;
    opInit(json);
  }, [json?.length]);

  useEffect(() => {
    if (!opInfo.opType) return;
    (async () => {
      const record = opInfo?.opRecord;
      const isImg = ['png'].includes(record?.ext);
      const file = await path.join(
        await chatRoot(),
        'download',
        isImg ? 'img' : record?.ext,
        `${record?.id}.${record?.ext}`,
      );
      if (opInfo.opType === 'preview') {
        const data = await fs.readBinaryFile(file);
        const sourceData = renderFile(data, record?.ext);
        setSource(sourceData);
        setVisible(true);
        return;
      }
      if (opInfo.opType === 'delete') {
        await fs.removeFile(file);
        await handleRefresh();
      }
      if (opInfo.opType === 'rowedit') {
        const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord);
        await updateJson(data);
        message.success('Name has been changed!');
      }
      opInfo.resetRecord();
    })();
  }, [opInfo.opType]);

  const handleDelete = async () => {
    if (opData?.length === selectedRows.length) {
      const downloadDir = await path.join(await chatRoot(), 'download');
      await fs.removeDir(downloadDir, { recursive: true });
      await handleRefresh();
      message.success('All files have been cleared!');
      return;
    }

    const rows = selectedRows.map(async (i) => {
      const isImg = ['png'].includes(i?.ext);
      const file = await path.join(
        await chatRoot(),
        'download',
        isImg ? 'img' : i?.ext,
        `${i?.id}.${i?.ext}`,
      );
      await fs.removeFile(file);
      return file;
    });
    Promise.all(rows).then(async () => {
      await handleRefresh();
      message.success('All files selected are cleared!');
    });
  };

  const handleRefresh = async () => {
    await invoke('download_list', { pathname: CHAT_DOWNLOAD_JSON, dir: 'download' });
    rowReset();
    const data = await refreshJson();
    opInit(data);
  };

  const handleCancel = () => {
    setVisible(false);
    opInfo.resetRecord();
  };

  return (
    <div>
      <div className="chat-table-btns">
        <div>
          {selectedItems.length > 0 && (
            <>
              <Popconfirm
                overlayStyle={{ width: 250 }}
                title="Files cannot be recovered after deletion, are you sure you want to delete them?"
                placement="topLeft"
                onConfirm={handleDelete}
                okText="Yes"
                cancelText="No"
              >
                <Button>Delete</Button>
              </Popconfirm>
              <span className="num">Selected {selectedItems.length} items</span>
            </>
          )}
        </div>
      </div>
      <FilePath paths={CHAT_DOWNLOAD_JSON} />
      <Table
        rowKey="id"
        columns={columns}
        scroll={{ x: 800 }}
        dataSource={opData}
        rowSelection={rowSelection}
        pagination={TABLE_PAGINATION}
      />
      <Modal
        open={isVisible}
        title={<div>{opInfo?.opRecord?.name || ''}</div>}
        onCancel={handleCancel}
        footer={false}
        destroyOnClose
      >
        <img style={{ maxWidth: '100%' }} src={source} />
      </Modal>
    </div>
  );
}


================================================
FILE: ChatGPT/src/view/markdown/index.scss
================================================
.md-task {
  margin-bottom: 5px;
  display: flex;
  justify-content: space-between;

  .ant-breadcrumb-link {
    padding: 3px 5px;
    transition: all 300ms ease;
    border-radius: 4px;
    &:hover {
      color: rgba(0, 0, 0, 0.88);
      background-color: rgba(0, 0, 0, 0.06);
      cursor: pointer;
    }
  }
}


================================================
FILE: ChatGPT/src/view/markdown/index.tsx
================================================
import { useState } from 'react';
import { useLocation } from 'react-router-dom';
import { Breadcrumb } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import MarkdownEditor from '@/components/Markdown/Editor';
import { fs, shell } from '@tauri-apps/api';

import useInit from '@/hooks/useInit';
import SplitIcon from '@/icons/SplitIcon';
import { getPath } from '@/view/notes/config';
import './index.scss';

const modeMap: any = {
  0: 'split',
  1: 'md',
  2: 'doc',
};

export default function Markdown() {
  const [filePath, setFilePath] = useState('');
  const [source, setSource] = useState('');
  const [previewMode, setPreviewMode] = useState(0);
  const location = useLocation();
  const state = location?.state;

  useInit(async () => {
    const file = await getPath(state);
    setFilePath(file);
    setSource(await fs.readTextFile(file));
  });

  const handleChange = async (v: string) => {
    await fs.writeTextFile(filePath, v);
  };

  const handlePreview = () => {
    let mode = previewMode + 1;
    if (mode > 2) mode = 0;
    setPreviewMode(mode);
  };

  return (
    <>
      <div className="md-task">
        <Breadcrumb separator="">
          <Breadcrumb.Item onClick={() => history.go(-1)}>
            <ArrowLeftOutlined />
          </Breadcrumb.Item>
          <Breadcrumb.Item onClick={() => shell.open(filePath)}>{filePath}</Breadcrumb.Item>
        </Breadcrumb>
        <div>
          <SplitIcon onClick={handlePreview} style={{ fontSize: 18, color: 'rgba(0,0,0,0.5)' }} />
        </div>
      </div>
      <MarkdownEditor value={source} onChange={handleChange} mode={modeMap[previewMode]} />
    </>
  );
}


================================================
FILE: ChatGPT/src/view/model/SyncCustom/Form.tsx
================================================
import {
  useEffect,
  useState,
  ForwardRefRenderFunction,
  useImperativeHandle,
  forwardRef,
} from 'react';
import { Form, Input, Select, Tooltip } from 'antd';
import { v4 } from 'uuid';
import type { FormProps } from 'antd';

import { DISABLE_AUTO_COMPLETE, chatRoot } from '@/utils';
import useInit from '@/hooks/useInit';

interface SyncFormProps {
  record?: Record<string | symbol, any> | null;
  type: string;
}

const initFormValue = {
  act: '',
  enable: true,
  tags: [],
  prompt: '',
};

const SyncForm: ForwardRefRenderFunction<FormProps, SyncFormProps> = ({ record, type }, ref) => {
  const isDisabled = type === 'edit';
  const [form] = Form.useForm();
  useImperativeHandle(ref, () => ({ form }));
  const [root, setRoot] = useState('');

  useInit(async () => {
    setRoot(await chatRoot());
  });

  useEffect(() => {
    if (record) {
      form.setFieldsValue(record);
    }
  }, [record]);

  const pathOptions = (
    <Form.Item noStyle name="protocol" initialValue="https">
      <Select disabled={isDisabled}>
        <Select.Option value="local">{root}</Select.Option>
        <Select.Option value="http">http://</Select.Option>
        <Select.Option value="https">https://</Select.Option>
      </Select>
    </Form.Item>
  );
  const extOptions = (
    <Form.Item noStyle name="ext" initialValue="json">
      <Select disabled={isDisabled}>
        <Select.Option value="csv">.csv</Select.Option>
        <Select.Option value="json">.json</Select.Option>
      </Select>
    </Form.Item>
  );

  const jsonTip = (
    <Tooltip
      title={
        <pre>
          {JSON.stringify(
            [
              { cmd: '', act: '', prompt: '' },
              { cmd: '', act: '', prompt: '' },
            ],
            null,
            2,
          )}
        </pre>
      }
    >
      <a>JSON</a>
    </Tooltip>
  );

  const csvTip = (
    <Tooltip
      title={
        <pre>{`"cmd","act","prompt"
"cmd","act","prompt"
"cmd","act","prompt"
"cmd","act","prompt"`}</pre>
      }
    >
      <a>CSV</a>
    </Tooltip>
  );

  return (
    <>
      <Form form={form} labelCol={{ span: 4 }} initialValues={initFormValue}>
        <Form.Item
          label="Name"
          name="name"
          rules={[{ required: true, message: 'Please enter a name!' }]}
        >
          <Input placeholder="Please enter a name" {...DISABLE_AUTO_COMPLETE} />
        </Form.Item>
        <Form.Item
          label="PATH"
          name="path"
          rules={[{ required: true, message: 'Please enter the path!' }]}
        >
          <Input
            placeholder="YOUR_PATH"
            addonBefore={pathOptions}
            addonAfter={extOptions}
            {...DISABLE_AUTO_COMPLETE}
          />
        </Form.Item>
        <Form.Item style={{ display: 'none' }} name="id" initialValue={v4().replace(/-/g, '')}>
          <input />
        </Form.Item>
      </Form>
      <div className="tip">
        <p>
          The file supports only {csvTip} and {jsonTip} formats.
        </p>
      </div>
    </>
  );
};

export default forwardRef(SyncForm);


================================================
FILE: ChatGPT/src/view/model/SyncCustom/config.tsx
================================================
import { useState } from 'react';
import { Tag, Space, Popconfirm } from 'antd';
import { HistoryOutlined } from '@ant-design/icons';
import { shell, path } from '@tauri-apps/api';
import { Link } from 'react-router-dom';

import useInit from '@/hooks/useInit';
import { chatRoot, fmtDate } from '@/utils';

export const syncColumns = () => [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
    width: 100,
  },
  {
    title: 'Protocol',
    dataIndex: 'protocol',
    key: 'protocol',
    width: 80,
    render: (v: string) => <Tag>{v}</Tag>,
  },
  {
    title: 'PATH',
    dataIndex: 'path',
    key: 'path',
    width: 180,
    render: (_: string, row: any) => <RenderPath row={row} />,
  },
  {
    title: 'Last updated',
    dataIndex: 'last_updated',
    key: 'last_updated',
    width: 140,
    render: (v: number) => (
      <div>
        <HistoryOutlined style={{ marginRight: 5, color: v ? '#52c41a' : '#ff4d4f' }} />
        {v ? fmtDate(v) : ''}
      </div>
    ),
  },
  {
    title: 'Action',
    fixed: 'right',
    width: 150,
    render: (_: any, row: any, actions: any) => {
      return (
        <Space>
          <Popconfirm
            overlayStyle={{ width: 250 }}
            title="Sync will overwrite the previous data, confirm to sync?"
            onConfirm={() => actions.setRecord(row, 'sync')}
            okText="Yes"
            cancelText="No"
          >
            <a>Sync</a>
          </Popconfirm>
          {row.last_updated && (
            <Link to={`${row.id}`} state={row}>
              View
            </Link>
          )}
          <a onClick={() => actions.setRecord(row, 'edit')}>Edit</a>
          <Popconfirm
            title="Are you sure to delete this path?"
            onConfirm={() => actions.setRecord(row, 'delete')}
            okText="Yes"
            cancelText="No"
          >
            <a>Delete</a>
          </Popconfirm>
        </Space>
      );
    },
  },
];

const RenderPath = ({ row }: any) => {
  const [filePath, setFilePath] = useState('');
  useInit(async () => {
    setFilePath(await getPath(row));
  });
  return <a onClick={() => shell.open(filePath)}>{filePath}</a>;
};

export const getPath = async (row: any) => {
  if (!/^http/.test(row.protocol)) {
    return (await path.join(await chatRoot(), row.path)) + `.${row.ext}`;
  } else {
    return `${row.protocol}://${row.path}.${row.ext}`;
  }
};


================================================
FILE: ChatGPT/src/view/model/SyncCustom/index.tsx
================================================
import { useState, useRef, useEffect } from 'react';
import { Table, Modal, Button, message } from 'antd';
import { invoke, path, fs } from '@tauri-apps/api';

import useData from '@/hooks/useData';
import useColumns from '@/hooks/useColumns';
import { TABLE_PAGINATION } from '@/hooks/useTable';
import useChatModel, { useCacheModel } from '@/hooks/useChatModel';
import { CHAT_MODEL_JSON, chatRoot, readJSON, genCmd } from '@/utils';
import { syncColumns, getPath } from './config';
import SyncForm from './Form';

const fmtData = (data: Record<string, any>[] = []) =>
  (Array.isArray(data) ? data : []).map((i) => ({
    ...i,
    cmd: i.cmd ? i.cmd : genCmd(i.act),
    tags: ['user-sync'],
    enable: true,
  }));

export default function SyncCustom() {
  const [isVisible, setVisible] = useState(false);
  const { modelData, modelSet } = useChatModel('sync_custom', CHAT_MODEL_JSON);
  const { modelCacheCmd, modelCacheSet } = useCacheModel();
  const { opData, opInit, opAdd, opRemove, opReplace, opSafeKey } = useData([]);
  const { columns, ...opInfo } = useColumns(syncColumns());
  const formRef = useRef<any>(null);

  const hide = () => {
    setVisible(false);
    opInfo.resetRecord();
  };

  useEffect(() => {
    if (modelData.length <= 0) return;
    opInit(modelData);
  }, [modelData]);

  useEffect(() => {
    if (!opInfo.opType) return;
    if (opInfo.opType === 'sync') {
      const filename = `${opInfo?.opRecord?.id}.json`;
      handleSync(filename).then((isOk: boolean) => {
        opInfo.resetRecord();
        if (!isOk) return;
        const data = opReplace(opInfo?.opRecord?.[opSafeKey], {
          ...opInfo?.opRecord,
          last_updated: Date.now(),
        });
        modelSet(data);
        opInfo.resetRecord();
      });
    }
    if (['edit', 'new'].includes(opInfo.opType)) {
      setVisible(true);
    }
    if (['delete'].includes(opInfo.opType)) {
      (async () => {
        try {
          const file = await path.join(
            await chatRoot(),
            'cache_model',
            `${opInfo?.opRecord?.id}.json`,
          );
          await fs.removeFile(file);
        } catch (e) {}
        const data = opRemove(opInfo?.opRecord?.[opSafeKey]);
        modelSet(data);
        opInfo.resetRecord();
        modelCacheCmd();
      })();
    }
  }, [opInfo.opType, formRef]);

  const handleSync = async (filename: string) => {
    const record = opInfo?.opRecord;
    const isJson = /json$/.test(record?.ext);
    const file = await path.join(await chatRoot(), 'cache_model', filename);
    const filePath = await getPath(record);

    // https or http
    if (/^http/.test(record?.protocol)) {
      const data = await invoke('sync_user_prompts', { url: filePath, dataType: record?.ext });
      if (data) {
        await modelCacheSet(data as [], file);
        await modelCacheCmd();
        message.success('ChatGPT Prompts data has been synchronized!');
        return true;
      } else {
        message.error('ChatGPT Prompts data sync failed, please try again!');
        return false;
      }
    }
    // local
    if (isJson) {
      // parse json
      const data = await readJSON(filePath, { isRoot: true });
      await modelCacheSet(fmtData(data), file);
    } else {
      // parse csv
      const data = await fs.readTextFile(filePath);
      const list: Record<string, string>[] = await invoke('parse_prompt', { data });
      await modelCacheSet(fmtData(list), file);
    }
    await modelCacheCmd();
    return true;
  };

  const handleOk = () => {
    formRef.current?.form?.validateFields().then((vals: Record<string, any>) => {
      if (opInfo.opType === 'new') {
        const data = opAdd(vals);
        modelSet(data);
        message.success('Data added successfully');
      }
      if (opInfo.opType === 'edit') {
        const data = opReplace(opInfo?.opRecord?.[opSafeKey], vals);
        modelSet(data);
        message.success('Data updated successfully');
      }
      hide();
    });
  };

  return (
    <div>
      <Button
        style={{ marginBottom: 10 }}
        className="chat-add-btn"
        type="primary"
        onClick={opInfo.opNew}
      >
        Add PATH
      </Button>
      <Table
        key="id"
        rowKey="name"
        columns={columns}
        scroll={{ x: 800 }}
        dataSource={opData}
        pagination={TABLE_PAGINATION}
      />
      <Modal
        open={isVisible}
        onCancel={hide}
        title="Sync PATH"
        onOk={handleOk}
        destroyOnClose
        maskClosable={false}
      >
        <SyncForm ref={formRef} record={opInfo?.opRecord} type={opInfo.opType} />
      </Modal>
    </div>
  );
}


================================================
FILE: ChatGPT/src/view/model/SyncPrompts/config.tsx
================================================
import { Table, Switch, Tag } from 'antd';

import { genCmd } from '@/utils';

export const syncColumns = () => [
  {
    title: '/{cmd}',
    dataIndex: 'cmd',
    fixed: 'left',
    // width: 120,
    key: 'cmd',
    render: (_: string, row: Record<string, string>) => (
      <Tag color="#2a2a2a">/{genCmd(row.act)}</Tag>
    ),
  },
  {
    title: 'Act',
    dataIndex: 'act',
    key: 'act',
    // width: 200,
  },
  {
    title: 'Tags',
    dataIndex: 'tags',
    key: 'tags',
    // width: 150,
    render: () => <Tag>chatgpt-prompts</Tag>,
  },
  {
    title: 'Enable',
    dataIndex: 'enable',
    key: 'enable',
    // width: 80,
    render: (v: boolean = false, row: Record<string, any>, action: Record<string, any>) => (
      <Switch checked={v} onChange={(v) => action.setRecord({ ...row, enable: v }, 'enable')} />
    ),
  },
  Table.EXPAND_COLUMN,
  {
    title: 'Prompt',
    dataIndex: 'prompt',
    key: 'prompt',
    // width: 300,
    render: (v: string) => <span className="chat-prompts-val">{v}</span>,
  },
];


================================================
FILE: ChatGPT/src/view/model/SyncPrompts/index.scss
================================================
.chat-table-tip,
.chat-table-btns {
  display: flex;
  justify-content: space-between;
}

.chat-table-btns {
  margin-bottom: 5px;

  .num {
    margin-left: 10px;
  }
}


================================================
FILE: ChatGPT/src/view/model/SyncPrompts/index.tsx
================================================
import { useEffect, useState } from 'react';
import { Table, Button, Popconfirm } from 'antd';
import { invoke, path } from '@tauri-apps/api';

import useInit from '@/hooks/useInit';
import useData from '@/hooks/useData';
import useColumns from '@/hooks/useColumns';
import FilePath from '@/components/FilePath';
import useChatModel, { useCacheModel } from '@/hooks/useChatModel';
import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable';
import { fmtDate, chatRoot } from '@/utils';
import { syncColumns } from './config';
import './index.scss';

const promptsURL = 'https://github.com/f/awesome-chatgpt-prompts/blob/main/prompts.csv';

export default function SyncPrompts() {
  const { rowSelection, selectedRowIDs } = useTableRowSelection();
  const [jsonPath, setJsonPath] = useState('');
  const { modelJson, modelSet } = useChatModel('sync_prompts');
  const { modelCacheJson, modelCacheSet } = useCacheModel(jsonPath);
  const { opData, opInit, opReplace, opReplaceItems, opSafeKey } = useData([]);
  const { columns, ...opInfo } = useColumns(syncColumns());
  const lastUpdated = modelJson?.sync_prompts?.last_updated;
  const selectedItems = rowSelection.selectedRowKeys || [];

  useInit(async () => {
    setJsonPath(await path.join(await chatRoot(), 'cache_model', 'chatgpt_prompts.json'));
  });

  useEffect(() => {
    if (modelCacheJson.length <= 0) return;
    opInit(modelCacheJson);
  }, [modelCacheJson.length]);

  const handleSync = async () => {
    const data = await invoke('sync_prompts', { time: Date.now() });
    if (data) {
      opInit(data as any[]);
      modelSet({
        id: 'chatgpt_prompts',
        last_updated: Date.now(),
      });
    }
  };

  useEffect(() => {
    if (opInfo.opType === 'enable') {
      const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord);
      modelCacheSet(data);
    }
  }, [opInfo.opTime]);

  const handleEnable = (isEnable: boolean) => {
    const data = opReplaceItems(selectedRowIDs, { enable: isEnable });
    modelCacheSet(data);
  };

  return (
    <div>
      <div className="chat-table-btns">
        <Popconfirm
          overlayStyle={{ width: 250 }}
          title="Sync will overwrite the previous data, confirm to sync?"
          placement="topLeft"
          onConfirm={handleSync}
          okText="Yes"
          cancelText="No"
        >
          <Button type="primary">Sync</Button>
        </Popconfirm>
        <div>
          {selectedItems.length > 0 && (
            <>
              <Button type="primary" onClick={() => handleEnable(true)}>
                Enable
              </Button>
              <Button onClick={() => handleEnable(false)}>Disable</Button>
              <span className="num">Selected {selectedItems.length} items</span>
            </>
          )}
        </div>
      </div>
      <div className="chat-table-tip">
        <div className="chat-sync-path">
          <FilePath url={promptsURL} content="f/awesome-chatgpt-prompts/prompts.csv" />
          <FilePath label="CACHE" paths="cache_model/chatgpt_prompts.json" />
        </div>
        {lastUpdated && (
          <span style={{ marginLeft: 10, color: '#888', fontSize: 12 }}>
            Last updated on {fmtDate(lastUpdated)}
          </span>
        )}
      </div>
      <Table
        key={lastUpdated}
        rowKey="act"
        columns={columns}
        scroll={{ x: 'auto' }}
        dataSource={opData}
        rowSelection={rowSelection}
        pagination={TABLE_PAGINATION}
        expandable={{
          expandedRowRender: (record) => <div style={{ padding: 10 }}>{record.prompt}</div>,
        }}
      />
    </div>
  );
}


================================================
FILE: ChatGPT/src/view/model/SyncRecord/config.tsx
================================================
import { Switch, Tag, Table } from 'antd';

import { genCmd } from '@/utils';

export const syncColumns = () => [
  {
    title: '/{cmd}',
    dataIndex: 'cmd',
    fixed: 'left',
    // width: 120,
    key: 'cmd',
    render: (_: string, row: Record<string, string>) => (
      <Tag color="#2a2a2a">/{row.cmd ? row.cmd : genCmd(row.act)}</Tag>
    ),
  },
  {
    title: 'Act',
    dataIndex: 'act',
    key: 'act',
    // width: 200,
  },
  {
    title: 'Tags',
    dataIndex: 'tags',
    key: 'tags',
    // width: 150,
    render: (v: string[]) => (
      <span className="chat-prompts-tags">
        {v?.map((i) => (
          <Tag key={i}>{i}</Tag>
        ))}
      </span>
    ),
  },
  {
    title: 'Enable',
    dataIndex: 'enable',
    key: 'enable',
    // width: 80,
    render: (v: boolean = false, row: Record<string, any>, action: Record<string, any>) => (
      <Switch checked={v} onChange={(v) => action.setRecord({ ...row, enable: v }, 'enable')} />
    ),
  },
  Table.EXPAND_COLUMN,
  {
    title: 'Prompt',
    dataIndex: 'prompt',
    key: 'prompt',
    // width: 300,
    render: (v: string) => <span className="chat-prompts-val">{v}</span>,
  },
];


================================================
FILE: ChatGPT/src/view/model/SyncRecord/index.tsx
================================================
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { Table, Button } from 'antd';
import { path } from '@tauri-apps/api';

import useData from '@/hooks/useData';
import useColumns from '@/hooks/useColumns';
import FilePath from '@/components/FilePath';
import { useCacheModel } from '@/hooks/useChatModel';
import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable';
import { getPath } from '@/view/model/SyncCustom/config';
import { fmtDate, chatRoot } from '@/utils';
import { syncColumns } from './config';
import useInit from '@/hooks/useInit';

export default function SyncRecord() {
  const location = useLocation();
  const [filePath, setFilePath] = useState('');
  const [jsonPath, setJsonPath] = useState('');
  const state = location?.state;

  const { rowSelection, selectedRowIDs } = useTableRowSelection();
  const { modelCacheJson, modelCacheSet } = useCacheModel(jsonPath);
  const { opData, opInit, opReplace, opReplaceItems, opSafeKey } = useData([]);
  const { columns, ...opInfo } = useColumns(syncColumns());

  const selectedItems = rowSelection.selectedRowKeys || [];

  useInit(async () => {
    setFilePath(await getPath(state));
    setJsonPath(await path.join(await chatRoot(), 'cache_model', `${state?.id}.json`));
  });

  useEffect(() => {
    if (modelCacheJson.length <= 0) return;
    opInit(modelCacheJson);
  }, [modelCacheJson.length]);

  useEffect(() => {
    if (opInfo.opType === 'enable') {
      const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord);
      modelCacheSet(data);
    }
  }, [opInfo.opTime]);

  const handleEnable = (isEnable: boolean) => {
    const data = opReplaceItems(selectedRowIDs, { enable: isEnable });
    modelCacheSet(data);
  };

  return (
    <div>
      <div className="chat-table-btns">
        <div>
          <Button shape="round" icon={<ArrowLeftOutlined />} onClick={() => history.back()} />
        </div>
        <div>
          {selectedItems.length > 0 && (
            <>
              <Button type="primary" onClick={() => handleEnable(true)}>
                Enable
              </Button>
              <Button onClick={() => handleEnable(false)}>Disable</Button>
              <span className="num">Selected {selectedItems.length} items</span>
            </>
          )}
        </div>
      </div>
      <div className="chat-table-tip">
        <div className="chat-sync-path">
          <FilePath url={filePath} />
          <FilePath label="CACHE" paths={`cache_model/${state?.id}.json`} />
        </div>
        {state?.last_updated && (
          <span style={{ marginLeft: 10, color: '#888', fontSize: 12 }}>
            Last updated on {fmtDate(state?.last_updated)}
          </span>
        )}
      </div>
      <Table
        key="prompt"
        rowKey="act"
        columns={columns}
        scroll={{ x: 'auto' }}
        dataSource={opData}
        rowSelection={rowSelection}
        pagination={TABLE_PAGINATION}
        expandable={{
          expandedRowRender: (record) => <div style={{ padding: 10 }}>{record.prompt}</div>,
        }}
      />
    </div>
  );
}


================================================
FILE: ChatGPT/src/view/model/UserCustom/Form.tsx
================================================
import { useEffect, ForwardRefRenderFunction, useImperativeHandle, forwardRef } from 'react';
import { Form, Input, Switch } from 'antd';
import type { FormProps } from 'antd';

import Tags from '@comps/Tags';
import { DISABLE_AUTO_COMPLETE } from '@/utils';

interface UserCustomFormProps {
  record?: Record<string | symbol, any> | null;
}

const initFormValue = {
  act: '',
  enable: true,
  tags: [],
  prompt: '',
};

const UserCustomForm: ForwardRefRenderFunction<FormProps, UserCustomFormProps> = (
  { record },
  ref,
) => {
  const [form] = Form.useForm();
  useImperativeHandle(ref, () => ({ form }));

  useEffect(() => {
    if (record) {
      form.setFieldsValue(record);
    }
  }, [record]);

  return (
    <Form form={form} labelCol={{ span: 4 }} initialValues={initFormValue}>
      <Form.Item
        label="/{cmd}"
        name="cmd"
        rules={[{ required: true, message: 'Please enter the {cmd}!' }]}
      >
        <Input placeholder="Please enter the {cmd}" {...DISABLE_AUTO_COMPLETE} />
      </Form.Item>
      <Form.Item
        label="Act"
        name="act"
        rules={[{ required: true, message: 'Please enter the Act!' }]}
      >
        <Input placeholder="Please enter the Act" {...DISABLE_AUTO_COMPLETE} />
      </Form.Item>
      <Form.Item label="Tags" name="tags">
        <Tags value={record?.tags} />
      </Form.Item>
      <Form.Item label="Enable" name="enable" valuePropName="checked">
        <Switch />
      </Form.Item>
      <Form.Item
        label="Prompt"
        name="prompt"
        rules={[{ required: true, message: 'Please enter a prompt!' }]}
      >
        <Input.TextArea rows={4} placeholder="Please enter a prompt" {...DISABLE_AUTO_COMPLETE} />
      </Form.Item>
    </Form>
  );
};

export default forwardRef(UserCustomForm);


================================================
FILE: ChatGPT/src/view/model/UserCustom/config.tsx
================================================
import { Tag, Switch, Space, Popconfirm, Table } from 'antd';

export const modelColumns = () => [
  {
    title: '/{cmd}',
    dataIndex: 'cmd',
    fixed: 'left',
    width: 120,
    key: 'cmd',
    render: (v: string) => <Tag color="#2a2a2a">/{v}</Tag>,
  },
  {
    title: 'Act',
    dataIndex: 'act',
    key: 'act',
    width: 200,
  },
  {
    title: 'Tags',
    dataIndex: 'tags',
    key: 'tags',
    width: 150,
    render: (v: string[]) => (
      <span className="chat-prompts-tags">
        {v?.map((i) => (
          <Tag key={i}>{i}</Tag>
        ))}
      </span>
    ),
  },
  {
    title: 'Enable',
    dataIndex: 'enable',
    key: 'enable',
    width: 80,
    render: (v: boolean = false, row: Record<string, any>, action: Record<string, any>) => (
      <Switch checked={v} onChange={(v) => action.setRecord({ ...row, enable: v }, 'enable')} />
    ),
  },
  Table.EXPAND_COLUMN,
  {
    title: 'Prompt',
    dataIndex: 'prompt',
    key: 'prompt',
    width: 300,
    render: (v: string) => <span className="chat-prompts-val">{v}</span>,
  },
  {
    title: 'Action',
    key: 'action',
    fixed: 'right',
    width: 120,
    render: (_: any, row: any, actions: any) => (
      <Space size="middle">
        <a onClick={() => actions.setRecord(row, 'edit')}>Edit</a>
        <Popconfirm
          title="Are you sure to delete this model?"
          onConfirm={() => actions.setRecord(row, 'delete')}
          okText="Yes"
          cancelText="No"
        >
          <a>Delete</a>
        </Popconfirm>
      </Space>
    ),
  },
];


================================================
FILE: ChatGPT/src/view/model/UserCustom/index.tsx
================================================
import { useState, useRef, useEffect } from 'react';
import { Table, Button, Modal, message } from 'antd';
import { path } from '@tauri-apps/api';

import useInit from '@/hooks/useInit';
import useData from '@/hooks/useData';
import useColumns from '@/hooks/useColumns';
import FilePath from '@/components/FilePath';
import useChatModel, { useCacheModel } from '@/hooks/useChatModel';
import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable';
import { chatRoot, fmtDate } from '@/utils';
import { modelColumns } from './config';
import UserCustomForm from './Form';

export default function UserCustom() {
  const { rowSelection, selectedRowIDs } = useTableRowSelection();
  const [isVisible, setVisible] = useState(false);
  const [jsonPath, setJsonPath] = useState('');
  const { modelJson, modelSet } = useChatModel('user_custom');
  const { modelCacheJson, modelCacheSet } = useCacheModel(jsonPath);
  const { opData, opInit, opReplaceItems, opAdd, opRemove, opReplace, opSafeKey } = useData([]);
  const { columns, ...opInfo } = useColumns(modelColumns());
  const lastUpdated = modelJson?.user_custom?.last_updated;
  const selectedItems = rowSelection.selectedRowKeys || [];
  const formRef = useRef<any>(null);

  useInit(async () => {
    setJsonPath(await path.join(await chatRoot(), 'cache_model', 'user_custom.json'));
  });

  useEffect(() => {
    if (modelCacheJson.length <= 0) return;
    opInit(modelCacheJson);
  }, [modelCacheJson.length]);

  useEffect(() => {
    if (!opInfo.opType) return;
    if (['edit', 'new'].includes(opInfo.opType)) {
      setVisible(true);
    }
    if (['delete'].includes(opInfo.opType)) {
      const data = opRemove(opInfo?.opRecord?.[opSafeKey]);
      modelCacheSet(data);
      opInfo.resetRecord();
    }
  }, [opInfo.opType, formRef]);

  useEffect(() => {
    if (opInfo.opType === 'enable') {
      const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord);
      modelCacheSet(data);
    }
  }, [opInfo.opTime]);

  const handleEnable = (isEnable: boolean) => {
    const data = opReplaceItems(selectedRowIDs, { enable: isEnable });
    modelCacheSet(data);
  };

  const hide = () => {
    setVisible(false);
    opInfo.resetRecord();
  };

  const handleOk = () => {
    formRef.current?.form?.validateFields().then(async (vals: Record<string, any>) => {
      if (
        modelCacheJson.map((i: any) => i.cmd).includes(vals.cmd) &&
        opInfo?.opRecord?.cmd !== vals.cmd
      ) {
        message.warning(
          `"cmd: /${vals.cmd}" already exists, please change the "${vals.cmd}" name and resubmit.`,
        );
        return;
      }
      let data = [];
      switch (opInfo.opType) {
        case 'new':
          data = opAdd(vals);
          break;
        case 'edit':
          data = opReplace(opInfo?.opRecord?.[opSafeKey], vals);
          break;
        default:
          break;
      }
      await modelCacheSet(data);
      opInit(data);
      modelSet({
        id: 'user_custom',
        last_updated: Date.now(),
      });
      hide();
    });
  };

  const modalTitle = `${{ new: 'Create', edit: 'Edit' }[opInfo.opType]} Model`;

  return (
    <div>
      <div className="chat-table-btns">
        <Button className="chat-add-btn" type="primary" onClick={opInfo.opNew}>
          Add Model
        </Button>
        <div>
          {selectedItems.length > 0 && (
            <>
              <Button type="primary" onClick={() => handleEnable(true)}>
                Enable
              </Button>
              <Button onClick={() => handleEnable(false)}>Disable</Button>
              <span className="num">Selected {selectedItems.length} items</span>
            </>
          )}
        </div>
      </div>
      <div className="chat-table-tip">
        <FilePath label="CACHE" paths="cache_model/user_custom.json" />
        {lastUpdated && (
          <span style={{ marginLeft: 10, color: '#888', fontSize: 12 }}>
            Last updated on {fmtDate(lastUpdated)}
          </span>
        )}
      </div>
      <Table
        key={lastUpdated}
        rowKey="cmd"
        columns={columns}
        scroll={{ x: 'auto' }}
        dataSource={opData}
        rowSelection={rowSelection}
        pagination={TABLE_PAGINATION}
        expandable={{
          expandedRowRender: (record) => <div style={{ padding: 10 }}>{record.prompt}</div>,
        }}
      />
      <Modal
        open={isVisible}
        onCancel={hide}
        title={modalTitle}
        onOk={handleOk}
        destroyOnClose
        maskClosable={false}
      >
        <UserCustomForm record={opInfo?.opRecord} ref={formRef} />
      </Modal>
    </div>
  );
}


================================================
FILE: ChatGPT/src/view/notes/config.tsx
================================================
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { Space, Popconfirm } from 'antd';
import { path, shell } from '@tauri-apps/api';

import { EditRow } from '@/hooks/useColumns';

import useInit from '@/hooks/useInit';
import { fmtDate, chatRoot } from '@/utils';

export const notesColumns = () => [
  {
    title: 'Name',
    dataIndex: 'name',
    fixed: 'left',
    key: 'name',
    width: 240,
    render: (_: string, row: any, actions: any) => (
      <EditRow rowKey="name" row={row} actions={actions} />
    ),
  },
  {
    title: 'Path',
    dataIndex: 'path',
    key: 'path',
    width: 200,
    render: (_: string, row: any) => <RenderPath row={row} />,
  },
  {
    title: 'Created',
    dataIndex: 'created',
    key: 'created',
    width: 150,
    render: fmtDate,
  },
  {
    title: 'Action',
    fixed: 'right',
    width: 160,
    render: (_: any, row: any, actions: any) => {
      return (
        <Space>
          <a onClick={() => actions.setRecord(row, 'preview')}>Preview</a>
          <Link to={`/md/${row.id}`} state={row}>
            Edit
          </Link>
          <Popconfirm
            title="Are you sure to delete this file?"
            onConfirm={() => actions.setRecord(row, 'delete')}
            okText="Yes"
            cancelText="No"
          >
            <a>Delete</a>
          </Popconfirm>
        </Space>
      );
    },
  },
];

const RenderPath = ({ row }: any) => {
  const [filePath, setFilePath] = useState('');
  useInit(async () => {
    setFilePath(await getPath(row));
  });
  return <a onClick={() => shell.open(filePath)}>{filePath}</a>;
};

export const getPath = async (row: any) => {
  return (await path.join(await chatRoot(), 'notes', row.id)) + `.${row.ext}`;
};


================================================
FILE: ChatGPT/src/view/notes/index.tsx
================================================
import { useEffect, useState } from 'react';
import { Table, Modal, Popconfirm, Button, message } from 'antd';
import { invoke, path, fs } from '@tauri-apps/api';

import useJson from '@/hooks/useJson';
import useData from '@/hooks/useData';
import useColumns from '@/hooks/useColumns';
import Markdown from '@/components/Markdown';
import FilePath from '@/components/FilePath';
import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable';
import { chatRoot, CHAT_NOTES_JSON } from '@/utils';
import { notesColumns } from './config';

export default function Notes() {
  const [source, setSource] = useState('');
  const [isVisible, setVisible] = useState(false);
  const { opData, opInit, opReplace, opSafeKey } = useData([]);
  const { columns, ...opInfo } = useColumns(notesColumns());
  const { rowSelection, selectedRows, rowReset } = useTableRowSelection({ rowType: 'row' });
  const { json, refreshJson, updateJson } = useJson<any[]>(CHAT_NOTES_JSON);
  const selectedItems = rowSelection.selectedRowKeys || [];

  useEffect(() => {
    if (!json || json.length <= 0) return;
    opInit(json);
  }, [json?.length]);

  useEffect(() => {
    if (!opInfo.opType) return;
    (async () => {
      const record = opInfo?.opRecord;
      const file = await path.join(await chatRoot(), 'notes', `${record?.id}.${record?.ext}`);
      if (opInfo.opType === 'preview') {
        const data = await fs.readTextFile(file);
        setSource(data);
        setVisible(true);
        return;
      }
      if (opInfo.opType === 'delete') {
        await fs.removeFile(file);
        await handleRefresh();
      }
      if (opInfo.opType === 'rowedit') {
        const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord);
        await updateJson(data);
        message.success('Name has been changed!');
      }
      opInfo.resetRecord();
    })();
  }, [opInfo.opType]);

  const handleDelete = async () => {
    if (opData?.length === selectedRows.length) {
      const notesDir = await path.join(await chatRoot(), 'notes');
      await fs.removeDir(notesDir, { recursive: true });
      await handleRefresh();
      message.success('All files have been cleared!');
      return;
    }

    const rows = selectedRows.map(async (i) => {
      const file = await path.join(await chatRoot(), 'notes', `${i?.id}.${i?.ext}`);
      await fs.removeFile(file);
      return file;
    });
    Promise.all(rows).then(async () => {
      await handleRefresh();
      message.success('All files selected are cleared!');
    });
  };

  const handleRefresh = async () => {
    await invoke('download_list', { pathname: CHAT_NOTES_JSON, dir: 'notes' });
    rowReset();
    const data = await refreshJson();
    opInit(data);
  };

  const handleCancel = () => {
    setVisible(false);
    opInfo.resetRecord();
  };

  return (
    <div>
      <div className="chat-table-btns">
        <div>
          {selectedItems.length > 0 && (
            <>
              <Popconfirm
                overlayStyle={{ width: 250 }}
                title="Files cannot be recovered after deletion, are you sure you want to delete them?"
                placement="topLeft"
                onConfirm={handleDelete}
                okText="Yes"
                cancelText="No"
              >
                <Button>Delete</Button>
              </Popconfirm>
              <span className="num">Selected {selectedItems.length} items</span>
            </>
          )}
        </div>
      </div>
      <FilePath paths={CHAT_NOTES_JSON} />
      <Table
        rowKey="id"
        columns={columns}
        scroll={{ x: 800 }}
        dataSource={opData}
        rowSelection={rowSelection}
        pagination={TABLE_PAGINATION}
      />
      <Modal
        open={isVisible}
        title={<div>{opInfo?.opRecord?.name || ''}</div>}
        onCancel={handleCancel}
        footer={false}
        destroyOnClose
        width={600}
      >
        <Markdown children={source} />
      </Modal>
    </div>
  );
}


================================================
FILE: ChatGPT/src/view/settings/General.tsx
================================================
import { useState } from 'react';
import { Form, Radio, Switch, Input, Tooltip, Select, Tag } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { platform } from '@tauri-apps/api/os';

import useInit from '@/hooks/useInit';
import { DISABLE_AUTO_COMPLETE } from '@/utils';

export default function General() {
  const [platformInfo, setPlatform] = useState('');
  const [vlist, setVoices] = useState<any[]>([]);

  useInit(async () => {
    setPlatform(await platform());
    speechSynthesis.addEventListener('voiceschanged', () => {
      const voices = speechSynthesis.getVoices();
      console.log(voices);
      setVoices(voices);
    });
    setVoices(speechSynthesis.getVoices());
  });

  return (
    <>
      <Form.Item label="Stay On Top" name="stay_on_top" valuePropName="checked">
        <Switch />
      </Form.Item>
      <Form.Item label="Save Window State" name="save_window_state" valuePropName="checked">
        <Switch />
      </Form.Item>
      {platformInfo === 'darwin' && (
        <Form.Item label="Titlebar" name="titlebar" valuePropName="checked">
          <Switch />
        </Form.Item>
      )}
      {platformInfo === 'darwin' && (
        <Form.Item label="Hide Dock Icon" name="hide_dock_icon" valuePropName="checked">
          <Switch />
        </Form.Item>
      )}
      <Form.Item label="Theme" name="theme">
        <Radio.Group>
          <Radio value="light">Light</Radio>
          <Radio value="dark">Dark</Radio>
          {['darwin', 'windows'].includes(platformInfo) && <Radio value="System">System</Radio>}
        </Radio.Group>
      </Form.Item>
      <Form.Item label={<AutoUpdateLabel />} name="auto_update">
        <Radio.Group>
          <Radio value="prompt">Prompt</Radio>
          <Radio value="silent">Silent</Radio>
          {/*<Radio value="disable">Disable</Radio>*/}
        </Radio.Group>
      </Form.Item>
      <Form.Item label={<GlobalShortcutLabel />} name="global_shortcut">
        <Input placeholder="CmdOrCtrl+Shift+O" {...DISABLE_AUTO_COMPLETE} />
      </Form.Item>
      <Form.Item label="Set Speech Language" name="speech_lang">
        <Select>
          {vlist.map((voice: any) => {
            return (
              <Select.Option key={voice.voiceURI} value={voice.voiceURI}>
                {voice.name} {': '}
                <Tag>{voice.lang}</Tag>
              </Select.Option>
            );
          })}
        </Select>
      </Form.Item>
    </>
  );
}

const AutoUpdateLabel = () => {
  return (
    <span>
      Auto Update{' '}
      <Tooltip
        title={
          <div>
            <div>Auto Update Policy</div>
            <div>
              <strong>Prompt</strong>: prompt to install
            </div>
            <div>
              <strong>Silent</strong>: install silently
            </div>
            {/* <div><strong>Disable</strong>: disable auto update</div> */}
          </div>
        }
      >
        <QuestionCircleOutlined style={{ color: '#1677ff' }} />
      </Tooltip>
    </span>
  );
};

const GlobalShortcutLabel = () => {
  return (
    <div>
      Global Shortcut{' '}
      <Tooltip
        title={
          <div>
            <div>Shortcut definition, modifiers and key separated by "+" e.g. CmdOrControl+Q</div>
            <div style={{ margin: '10px 0' }}>If empty, the shortcut is disabled.</div>
            <a href="https://tauri.app/v1/api/js/globalshortcut" target="_blank">
              https://tauri.app/v1/api/js/globalshortcut
            </a>
          </div>
        }
      >
        <QuestionCircleOutlined style={{ color: '#1677ff' }} />
      </Tooltip>
    </div>
  );
};


================================================
FILE: ChatGPT/src/view/settings/LangHelper.tsx
================================================
import { useState} from 'react';
import useInit from '@/hooks/useInit';
import {Form,Switch,Select,Radio,Input} from 'antd'
import { speakers, celebrity} from './Speakers';
import { FormInstance } from 'antd/lib/form';

export default function LangHelper({ form }: { form: FormInstance }) {

    const Speech_Type_List = ['web','ai','azure','iflytek'];
    // web, ai,azure, iflytek
    const Rec_Type_List = ['web','iflytek','ai'];
    //iflytek, speechsuper
    const Assess_Type_List = ['','iflytek','speechsuper'];

    const Special_Speech_Mode =['accent_per_sentence',"region_per_passage"]
    const [selectSpeech, setSelectSpeech] = useState('')
    const [selectRec,setSelectRec]  = useState('');
    const [selectAssess,setSelectAssess]  = useState('');
    
    useInit(() => {
        setSelectSpeech(form.getFieldValue('speech_type'));
        setSelectRec(form.getFieldValue('rec_type'));
        setSelectAssess(form.getFieldValue('assess_type'));
    });
    return (
      <>
        <Form.Item label="Talk mode" name="talk_mode" valuePropName="checked">
            <Switch />
        </Form.Item>
        <Form.Item label = "Speech Type" name="speech_type">
            <Select onChange={(v) =>{setSelectSpeech(v)}}>
                { Speech_Type_List.map((s:string) =>{
                    return (
                        <Select.Option key={s} value={s}>
                            {s}
                        </Select.Option>
                    );
                })}
            </Select>
        </Form.Item>
        <Form.Item label = "Recognition Type" name="rec_type">
            <Select onChange={(v)=>{setSelectRec(v)}}>
                { Rec_Type_List.map((s:string) =>{
                    return (
                        <Select.Option key={s} value={s}>
                            {s}
                        </Select.Option>
                    );
                })}
            </Select>
        </Form.Item>
        <Form.Item label = "Assessment Type" name="assess_type">
            <Select onChange={(v) =>{setSelectAssess(v)}}>
                { Assess_Type_List.map((s:string) =>{
                    return (
                        <Select.Option key={s} value={s}>
                            {s}
                        </Select.Option>
                    );
                })}
            </Select>
        </Form.Item>
        { selectSpeech === "ai" && (
            <Form.Item label="Hundreds ai Accents" name="speech_ai_lang">
                <Select>
                    {Special_Speech_Mode.map((s:string)=>{
                        return (
                            <Select.Option key={s} value ={s}>
                                {s}
                            </Select.Option>
                        );
                    })}
                    {speakers.map((l:string[])=>{
                        const speaker = l.join("-");
                        return (
                            <Select.Option key={speaker} value ={speaker}>
                                {speaker}
                            </Select.Option>
                        );
                    })}
                    {celebrity.map((s:string)=>{
                        return (
                            <Select.Option key={s} value ={s}>
                                {s}
                            </Select.Option>
                        );
                    })}
                </Select>
            </Form.Item>
        )}
         { selectSpeech === "ai" && (
            <Form.Item label="AI speech subprocess number" name="subprocess_number">
                <Radio.Group>
                    <Radio value="1">1</Radio>
                    <Radio value="2">2</Radio>
                    <Radio value="3">3</Radio>
                </Radio.Group>
          </Form.Item>
        )}
        { selectRec === "iflytek" && (
            <Form.Item label="iflytek Rec AppId" name="iflytek_rec_appid">
                <Input placeholder="input your iflytek Rec AppId"/>
            </Form.Item>
        )}
        { selectRec === "iflytek" && (
            <Form.Item label="iflytek Rec ApiKey" name="iflytek_rec_apikey">
                <Input placeholder="input your iflytek Rec ApiKey"/>
            </Form.Item>
        )}
        { selectRec === "iflytek" && (
            <Form.Item label="iflytek Rec Lang" name="rec_iflytek_lang">
                <Radio.Group>
                    <Radio value="cn">ch&en</Radio>
                    <Radio value="en">en</Radio>
                </Radio.Group>
            </Form.Item>
        )}
        { selectAssess === "iflytek" && (
            <Form.Item label="iflytek Assess AppId" name="iflytek_assess_appid">
                <Input placeholder="input your iflytek Assess AppId"/>
            </Form.Item>
        )}
        { selectAssess === "iflytek" && (
            <Form.Item label="iflytek Assess ApiSecret" name="iflytek_assess_appsecret">
                <Input placeholder="input your iflytek Assess ApiSecret"/>
            </Form.Item>
        )}
        { selectAssess === "iflytek" && (
            <Form.Item label="iflytek Assess ApiKey" name="iflytek_assess_apikey">
                <Input placeholder="input your iflytek Assess ApiKey"/>
            </Form.Item>
        )}
        { selectAssess === "speechsuper" && (
            <Form.Item label="speechsuper Assess AppKey" name="ss_assess_appkey">
                <Input placeholder="input your speechsuper Assess AppKey"/>
            </Form.Item>
        )}
        { selectAssess === "speechsuper" && (
            <Form.Item label="speechsuper Assess SecretKey" name="ss_assess_secretkey">
                <Input placeholder="input your speechsuper Assess SecretKey"/>
            </Form.Item>
        )}
      </>
    );
}
  

================================================
FILE: ChatGPT/src/view/settings/MainWindow.tsx
================================================
import { Form, Switch, Input, InputNumber, Tooltip } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';

import SwitchOrigin from '@/components/SwitchOrigin';
import { DISABLE_AUTO_COMPLETE } from '@/utils';

const PopupSearchLabel = () => {
  return (
    <span>
      Pop-up Search{' '}
      <Tooltip
        title={
          <div>
            <div style={{ marginBottom: 10 }}>
              Generate images according to the content: Select the ChatGPT content with the mouse,
              no more than 400 characters. the <b>DALL·E 2</b> 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).
            </div>
            <div>
              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.
            </div>
          </div>
        }
      >
        <QuestionCircleOutlined style={{ color: '#1677ff' }} />
      </Tooltip>
    </span>
  );
};

const MainCloseLabel = () => {
  return (
    <span>
      Close Exit{' '}
      <Tooltip title="Click the close button whether to exit directly, the default minimized.">
        <QuestionCircleOutlined style={{ color: '#1677ff' }} />
      </Tooltip>
    </span>
  );
};

export default function MainWindow() {
  return (
    <>
      <Form.Item label={<PopupSearchLabel />} name="popup_search" valuePropName="checked">
        <Switch />
      </Form.Item>
      <Form.Item label={<MainCloseLabel />} name="main_close" valuePropName="checked">
        <Switch />
      </Form.Item>
      <Form.Item label="Default Width" name="main_width">
        <InputNumber />
      </Form.Item>
      <Form.Item label="Default Height" name="main_height">
        <InputNumber />
      </Form.Item>
      <SwitchOrigin name="main" />
      <Form.Item label="User Agent (Main)" name="ua_window">
        <Input.TextArea
          autoSize={{ minRows: 4, maxRows: 4 }}
          {...DISABLE_AUTO_COMPLETE}
          placeholder="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
        />
      </Form.Item>
    </>
  );
}


================================================
FILE: ChatGPT/src/view/settings/Speakers.ts
================================================

export const speakers: string[][] =[
    ['p225', 'F', 'English'],
    ['p226', 'M', 'English'],
    ['p227', 'M', 'English'],
    ['p228', 'F', 'English'],
    ['p229', 'F', 'English'],
    ['p230', 'F', 'English'],
    ['p231', 'F', 'English'],
    ['p232', 'M', 'English'],
    ['p233', 'F', 'English'],
    ['p234', 'F', 'Scottish'],
    ['p236', 'F', 'English'],
    ['p237', 'M', 'Scottish'],
    ['p238', 'F', 'NorthernIrish'],
    ['p239', 'F', 'English'],
    ['p240', 'F', 'English'],
    ['p241', 'M', 'Scottish'],
    ['p243', 'M', 'English'],
    ['p244', 'F', 'English'],
    ['p245', 'M', 'Irish'],
    ['p246', 'M', 'Scottish'],
    ['p247', 'M', 'Scottish'],
    ['p248', 'F', 'Indian'],
    ['p249', 'F', 'Scottish'],
    ['p250', 'F', 'English'],
    ['p251', 'M', 'Indian'],
    ['p252', 'M', 'Scottish'],
    ['p253', 'F', 'Welsh'],
    ['p254', 'M', 'English'],
    ['p255', 'M', 'Scottish'],
    ['p256', 'M', 'English'],
    ['p257', 'F', 'English'],
    ['p258', 'M', 'English'],
    ['p259', 'M', 'English'],
    ['p260', 'M', 'Scottish'],
    ['p261', 'F', 'NorthernIrish'],
    ['p262', 'F', 'Scottish'],
    ['p263', 'M', 'Scottish'],
    ['p264', 'F', 'Scottish'],
    ['p265', 'F', 'Scottish'],
    ['p266', 'F', 'Irish'],
    ['p267', 'F', 'English'],
    ['p268', 'F', 'English'],
    ['p269', 'F', 'English'],
    ['p270', 'M', 'English'],
    ['p271', 'M', 'Scottish'],
    ['p272', 'M', 'Scottish'],
    ['p273', 'M', 'English'],
    ['p274', 'M', 'English'],
    ['p275', 'M', 'Scottish'],
    ['p276', 'F', 'English'],
    ['p277', 'F', 'English'],
    ['p278', 'M', 'English'],
    ['p279', 'M', 'English'],
    ['p280', 'F', 'Unknown'],
    ['p281', 'M', 'Scottish'],
    ['p282', 'F', 'English'],
    ['p283', 'F', 'Irish'],
    ['p284', 'M', 'Scottish'],
    ['p285', 'M', 'Scottish'],
    ['p286', 'M', 'English'],
    ['p287', 'M', 'English'],
    ['p288', 'F', 'Irish'],
    ['p292', 'M', 'NorthernIrish'],
    ['p293', 'F', 'NorthernIrish'],
    ['p294', 'F', 'American'],
    ['p295', 'F', 'Irish'],
    ['p297', 'F', 'American'],
    ['p298', 'M', 'Irish'],
    ['p299', 'F', 'American'],
    ['p300', 'F', 'American'],
    ['p301', 'F', 'American'],
    ['p302', 'M', 'Canadian'],
    ['p303', 'F', 'Canadian'],
    ['p304', 'M', 'NorthernIrish'],
    ['p305', 'F', 'American'],
    ['p306', 'F', 'American'],
    ['p307', 'F', 'Canadian'],
    ['p308', 'F', 'American'],
    ['p310', 'F', 'American'],
    ['p311', 'M', 'American'],
    ['p312', 'F', 'Canadian'],
    ['p313', 'F', 'Irish'],
    ['p314', 'F', 'SouthAfrican'],
    ['p315', 'M', 'American'],
    ['p316', 'M', 'Canadian'],
    ['p317', 'F', 'Canadian'],
    ['p318', 'F', 'American'],
    ['p323', 'F', 'SouthAfrican'],
    ['p326', 'M', 'Australian'],
    ['p329', 'F', 'American'],
    ['p330', 'F', 'American'],
    ['p333', 'F', 'American'],
    ['p334', 'M', 'American'],
    ['p335', 'F', 'NewZealand'],
    ['p336', 'F', 'SouthAfrican'],
    ['p339', 'F', 'American'],
    ['p340', 'F', 'Irish'],
    ['p341', 'F', 'American'],
    ['p343', 'F', 'Canadian'],
    ['p345', 'M', 'American'],
    ['p347', 'M', 'SouthAfrican'],
    ['p351', 'F', 'NorthernIrish'],
    ['p360', 'M', 'American'],
    ['p361', 'F', 'American'],
    ['p362', 'F', 'American'],
    ['p363', 'M', 'Canadian'],
    ['p364', 'M', 'Irish'],
    ['p374', 'M', 'Australian'],
    ['p376', 'M', 'Indian'],
    ['s5', 'F', 'British'],
];

export const celebrity:string[]= [
  "Downey",
  "Obama",
];

================================================
FILE: ChatGPT/src/view/settings/TrayWindow.tsx
================================================
import { Form, Switch, Input, InputNumber, Tooltip } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';

import { DISABLE_AUTO_COMPLETE } from '@/utils';
import SwitchOrigin from '@/components/SwitchOrigin';

const UALabel = () => {
  return (
    <span>
      User Agent (SystemTray){' '}
      <Tooltip
        title={<div>For a better experience, we recommend using the Mobile User-Agent.</div>}
      >
        <QuestionCircleOutlined style={{ color: '#1677ff' }} />
      </Tooltip>
    </span>
  );
};

export default function TrayWindow() {
  return (
    <>
      <Form.Item label="Enable SystemTray" name="tray" valuePropName="checked">
        <Switch />
      </Form.Item>
      <Form.Item label="Default Width" name="tray_width">
        <InputNumber />
      </Form.Item>
      <Form.Item label="Default Height" name="tray_height">
        <InputNumber />
      </Form.Item>
      <SwitchOrigin name="tray" />
      <Form.Item label={<UALabel />} name="ua_tray">
        <Input.TextArea
          autoSize={{ minRows: 4, maxRows: 4 }}
          {...DISABLE_AUTO_COMPLETE}
          placeholder="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"
        />
      </Form.Item>
    </>
  );
}


================================================
FILE: ChatGPT/src/view/settings/index.tsx
================================================
import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Form, Tabs, Space, Button, Popconfirm, message } from 'antd';
import { invoke, dialog, process, path, shell } from '@tauri-apps/api';
import { clone, omit, isEqual } from 'lodash';

import useInit from '@/hooks/useInit';
import FilePath from '@/components/FilePath';
import { chatRoot, APP_CONF_JSON } from '@/utils';
import General from './General';
import MainWindow from './MainWindow';
import TrayWindow from './TrayWindow';
import LangHelper from './LangHelper'

export default function Settings() {
  const [params] = useSearchParams();
  const [activeKey, setActiveKey] = useState('general');
  const [form] = Form.useForm();
  const [chatConf, setChatConf] = useState<any>(null);
  const [filePath, setPath] = useState('');
  const key = params.get('type');

  useEffect(() => {
    setActiveKey(key ? key : 'general');
  }, [key]);

  useInit(async () => {
    setChatConf(await invoke('get_app_conf'));
    setPath(await path.join(await chatRoot(), APP_CONF_JSON));
  });

  useEffect(() => {
    form.setFieldsValue(clone(chatConf));
  }, [chatConf]);

  const onCancel = () => {
    form.setFieldsValue(chatConf);
  };

  const onReset = async () => {
    const chatData = await invoke('reset_app_conf');
    setChatConf(chatData);
    const isOk = await dialog.ask(`Configuration reset successfully, do you want to restart?`, {
      title: 'ChatGPT Preferences',
    });
    if (isOk) {
      process.relaunch();
      return;
    }
    message.success('Configuration reset successfully');
  };

  const onFinish = async (values: any) => {
    if (!isEqual(omit(chatConf, ['default_origin']), values)) {
      await invoke('form_confirm', { data: values, label: 'main' });
      const isOk = await dialog.ask(`Configuration saved successfully, do you want to restart?`, {
        title: 'ChatGPT Preferences',
      });
      if (isOk) {
        process.relaunch();
        return;
      }
      message.success('Configuration saved successfully');
    }
  };

  const handleTab = (v: string) => {
    setActiveKey(v);
  };

  return (
    <div>
      <FilePath paths={APP_CONF_JSON} />
      <Form
        form={form}
        style={{ maxWidth: 500 }}
        onFinish={onFinish}
        labelCol={{ span: 10 }}
        wrapperCol={{ span: 13, offset: 1 }}
      >
        <Tabs
          activeKey={activeKey}
          onChange={handleTab}
          items={[
            { label: 'LangHelper', key: 'lang_helper', children: <LangHelper form= {form}/> },
            { label: 'General', key: 'general', children: <General /> },
            { label: 'Main Window', key: 'main_window', children: <MainWindow /> },
            { label: 'SystemTray Window', key: 'tray_window', children: <TrayWindow /> },
          ]}
        />

        <Form.Item>
          <Space size={20}>
            <Button onClick={onCancel}>Cancel</Button>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
            <Popconfirm
              title={
                <div style={{ width: 360 }}>
                  Are you sure you want to reset the configuration file
                  <a onClick={() => shell.open(filePath)} style={{ margin: '0 5px' }}>
                    {filePath}
                  </a>
                  to the default?
                </div>
              }
              onConfirm={onReset}
              okText="Yes"
              cancelText="No"
            >
              <Button type="dashed">Reset to defaults</Button>
            </Popconfirm>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );
}


================================================
FILE: ChatGPT/src/vite-env.d.ts
================================================
/// <reference types="vite/client" />


================================================
FILE: ChatGPT/src-tauri/Cargo.toml
================================================
[package]
name = "chatgpt"
version = "0.0.0"
authors = ["lencx <cxin1314@gmail.com>"]
description = "ChatGPT Desktop Application"
repository = "https://github.com/lencx/ChatGPT"
license = "MIT"
edition = "2021"
rust-version = "1.57"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[build-dependencies]
tauri-build = {version = "1.2.1", 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 = {version = "0.11.13", features = ["json"] }
wry = "0.24.1"
dark-light = "1.0.0"
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.23.0", features = ["macros"] }
tauri = { version = "1.2.4", features = ["devtools", "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-open-api", "system-tray", "updater"] }
tauri-plugin-positioner = { git = "https://github.com/lencx/tauri-plugins-workspace", features = ["system-tray"] }
tauri-plugin-log = { git = "https://github.com/lencx/tauri-plugins-workspace", branch = "dev", features = ["colored"] }
tauri-plugin-autostart = { git = "https://github.com/lencx/tauri-plugins-workspace", branch = "dev" }
tauri-plugin-window-state = { git = "https://github.com/lencx/tauri-plugins-workspace", branch = "dev" }
hyper = "0.14.11"
webview = "0.1.1"
# 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" ]


================================================
FILE: ChatGPT/src-tauri/build.rs
================================================
fn main() {
  tauri_build::build()
}


================================================
FILE: ChatGPT/src-tauri/src/app/cmd.rs
================================================
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();
  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 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
  })
}


================================================
FILE: ChatGPT/src-tauri/src/app/cors.rs
================================================
use serde::{Deserialize, Serialize};
use reqwest::{Client, Method, RequestBuilder,Proxy};
// use wry::http::UriScheme;

#[derive(Default, Serialize, Deserialize,Debug)]
pub struct Message {
    message: String,
    data:String,
}

#[tauri::command]
pub async fn fetch_data(
    method: String,
    url: String,
    body: Option<String>
) -> Result<Message, String>{
    println!("{},{},{:?}",method,url,body);

    let req_builder: RequestBuilder;
    let method = match method.as_str() {
        "GET" => Method::GET,
        "POST" => Method::POST,
        "PUT" => Method::PUT,
        "DELETE" => Method::DELETE,
        _ => {
            // Handle invalid method
            return Err("Invalid method".to_string());
        }
    };
    if url.contains("localhost"){
        let mut client_builder = Client::builder();
        // let mut client_builder = Client::builder()
        //         .pool_max_idle_per_host(15);
        //         .pool_idle_timeout(Duration::from_secs(10))
                // .build()?;
        client_builder = client_builder.proxy(Proxy::custom(move |url| {       
                None::<String> // bypass proxy for localhost
        }));
        let client = client_builder.build().map_err(|e| format!("Failed to create client: {}", e))?;
        req_builder = client.request(method, &url);
    } else {
        let client =Client::new();
        req_builder = client.request(method, &url);
    }
    
    let req_builder = req_builder.header("Content-Type", "application/json"); // Add header
    let resp = match body {
        Some(data) => req_builder.body(data).send().await.map_err(|e| format!("Request failed: {}", e))?,
        None => req_builder.send().await.map_err(|e| format!("Request failed: {}", e))?,
    };
    
    let message: Message = resp.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
    println!("response:{:?}",message);
    Ok(message) // Return the response directly
}


================================================
FILE: ChatGPT/src-tauri/src/app/fs_extra.rs
================================================
// 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()
// }


================================================
FILE: ChatGPT/src-tauri/src/app/gpt.rs
================================================
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_model_cmd() -> serde_json::Value {
  let path = utils::app_root().join("chat.model.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 PromptRecord {
  pub cmd: Option<String>,
  pub act: String,
  pub prompt: String,
}

#[command]
pub fn parse_prompt(data: String) -> Vec<PromptRecord> {
  let mut rdr = csv::Reader::from_reader(data.as_bytes());
  let mut list = vec![];
  for result in rdr.deserialize() {
    let record: PromptRecord = result.unwrap_or_else(|err| {
      error!("parse_prompt: {}", err);
      PromptRecord {
        cmd: None,
        act: "".to_string(),
        prompt: "".to_string(),
      }
    });
    if !record.act.is_empty() {
      list.push(record);
    }
  }
  list
}

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct ModelRecord {
  pub cmd: String,
  pub act: String,
  pub prompt: String,
  pub tags: Vec<String>,
  pub enable: bool,
}

#[command]
pub fn cmd_list() -> Vec<ModelRecord> {
  let mut list = vec![];
  for entry in WalkDir::new(utils::app_root().join("cache_model"))
    .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<ModelRecord> = 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<ModelRecord>> {
  let res = utils::get_data(GITHUB_PROMPTS_CSV_URL, Some(&app))
    .await
    .unwrap();

  if let Some(v) = res {
    let data = parse_prompt(v)
      .iter()
      .map(move |i| ModelRecord {
        cmd: if i.cmd.is_some() {
          i.cmd.clone().unwrap()
        } else {
          utils::gen_cmd(i.act.clone())
        },
        act: i.act.clone(),
        prompt: i.prompt.clone(),
        tags: vec!["chatgpt-prompts".to_string()],
        enable: true,
      })
      .collect::<Vec<ModelRecord>>();

    let data2 = data.clone();

    let model = utils::app_root().join("chat.model.json");
    let model_cmd = utils::app_root().join("chat.model.cmd.json");
    let chatgpt_prompts = utils::app_root()
      .join("cache_model")
      .join("chatgpt_prompts.json");

    if !utils::exists(&model) {
      fs::write(
        &model,
        serde_json::json!({
          "name": "ChatGPT Model",
          "link": "https://github.com/lencx/ChatGPT"
        })
        .to_string(),
      )
      .unwrap();
    }

    // chatgpt_prompts.json
    fs::write(
      chatgpt_prompts,
      serde_json::to_string_pretty(&data).unwrap(),
    )
    .unwrap();
    let cmd_data = cmd_list();

    // chat.model.cmd.json
    fs::write(
      model_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 model_data = utils::merge(
      &serde_json::from_str(&fs::read_to_string(&model).unwrap()).unwrap(),
      &kv,
    );

    // chat.model.json
    fs::write(model, serde_json::to_string_pretty(&model_data).unwrap()).unwrap();

    // refresh window
    api::dialog::message(
      app.get_window("core").as_ref(),
      "Sync Prompts",
      "ChatGPT Prompts data has been synchronized!",
    );
    window::cmd::window_reload(app.clone(), "core");
    window::cmd::window_reload(app, "tray");

    return Some(data2);
  }

  None
}

#[command]
pub async fn sync_user_prompts(url: String, data_type: String) -> Option<Vec<ModelRecord>> {
  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;
    if data_type == "csv" {
      info!("chatgpt_http_csv_parse");
      data = parse_prompt(v);
    } else if data_type == "json" {
      info!("chatgpt_http_json_parse");
      data = serde_json::from_str(&v).unwrap_or_else(|err| {
        error!("chatgpt_http_json_parse: {}", err);
        vec![]
      });
    } else {
      error!("chatgpt_http_unknown_type");
      data = vec![];
    }

    let data = data
      .iter()
      .map(move |i| ModelRecord {
        cmd: if i.cmd.is_some() {
          i.cmd.clone().unwrap()
        } 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<ModelRecord>>();

    return Some(data);
  }

  None
}


================================================
FILE: ChatGPT/src-tauri/src/app/menu.rs
================================================
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".to_string(), "About ChatGPT").into(),
      CustomMenuItem::new("check_update".to_string(), "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".to_string(), "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".to_string(), "Light");
  let theme_dark = CustomMenuItem::new("theme_dark".to_string(), "Dark");
  let theme_system = CustomMenuItem::new("theme_system".to_string(), "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".to_string(), "Prompt");
  let update_silent = CustomMenuItem::new("update_silent".to_string(), "Silent");
  // let _update_disable = CustomMenuItem::new("update_disable".to_string(), "Disable");

  let popup_search = CustomMenuItem::new("popup_search".to_string(), "Pop-up Search");
  let popup_search_menu = if app_conf.popup_search {
    popup_search.selected()
  } else {
    popup_search
  };

  #[cfg(target_os = "macos")]
  let titlebar = CustomMenuItem::new("titlebar".to_string(), "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".to_string(), "System Tray");
  let system_tray_menu = if app_conf.tray {
    system_tray.selected()
  } else {
    system_tray
  };

  let auto_update = app_conf.get_auto_update();
  let preferences_menu = Submenu::new(
    "Preferences",
    Menu::with_items([
      CustomMenuItem::new("control_center".to_string(), "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")]
      CustomMenuItem::new("hide_dock_icon".to_string(), "Hide Dock Icon").into(),
      system_tray_menu.into(),
      CustomMenuItem::new("inject_script".to_string(), "Inject Script")
        .accelerator("CmdOrCtrl+J")
        .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(),
      popup_search_menu.into(),
      CustomMenuItem::new("sync_prompts".to_string(), "Sync Prompts").into(),
      MenuItem::S
Download .txt
gitextract_0flj9ssv/

├── ChatGPT/
│   ├── .gitattributes
│   ├── .gitignore
│   ├── .husky/
│   │   └── pre-commit
│   ├── .npmrc
│   ├── .prettierignore
│   ├── .prettierrc
│   ├── .vscode/
│   │   └── extensions.json
│   ├── Cargo.toml
│   ├── LICENSE
│   ├── README-ZH_CN.md
│   ├── README.md
│   ├── UPDATE_LOG.md
│   ├── casks/
│   │   └── chatgpt.rb
│   ├── index.html
│   ├── package.json
│   ├── rustfmt.toml
│   ├── src/
│   │   ├── components/
│   │   │   ├── FilePath/
│   │   │   │   └── index.tsx
│   │   │   ├── Markdown/
│   │   │   │   ├── Editor.tsx
│   │   │   │   ├── index.scss
│   │   │   │   └── index.tsx
│   │   │   ├── SwitchOrigin/
│   │   │   │   └── index.tsx
│   │   │   └── Tags/
│   │   │       └── index.tsx
│   │   ├── hooks/
│   │   │   ├── useChatModel.ts
│   │   │   ├── useColumns.tsx
│   │   │   ├── useData.ts
│   │   │   ├── useInit.ts
│   │   │   ├── useJson.ts
│   │   │   └── useTable.tsx
│   │   ├── icons/
│   │   │   └── SplitIcon.tsx
│   │   ├── layout/
│   │   │   ├── index.scss
│   │   │   └── index.tsx
│   │   ├── main.scss
│   │   ├── main.tsx
│   │   ├── routes.tsx
│   │   ├── utils.ts
│   │   ├── view/
│   │   │   ├── about/
│   │   │   │   ├── index.scss
│   │   │   │   └── index.tsx
│   │   │   ├── awesome/
│   │   │   │   ├── Form.tsx
│   │   │   │   ├── config.tsx
│   │   │   │   └── index.tsx
│   │   │   ├── dashboard/
│   │   │   │   ├── index.scss
│   │   │   │   └── index.tsx
│   │   │   ├── download/
│   │   │   │   ├── config.tsx
│   │   │   │   └── index.tsx
│   │   │   ├── markdown/
│   │   │   │   ├── index.scss
│   │   │   │   └── index.tsx
│   │   │   ├── model/
│   │   │   │   ├── SyncCustom/
│   │   │   │   │   ├── Form.tsx
│   │   │   │   │   ├── config.tsx
│   │   │   │   │   └── index.tsx
│   │   │   │   ├── SyncPrompts/
│   │   │   │   │   ├── config.tsx
│   │   │   │   │   ├── index.scss
│   │   │   │   │   └── index.tsx
│   │   │   │   ├── SyncRecord/
│   │   │   │   │   ├── config.tsx
│   │   │   │   │   └── index.tsx
│   │   │   │   └── UserCustom/
│   │   │   │       ├── Form.tsx
│   │   │   │       ├── config.tsx
│   │   │   │       └── index.tsx
│   │   │   ├── notes/
│   │   │   │   ├── config.tsx
│   │   │   │   └── index.tsx
│   │   │   └── settings/
│   │   │       ├── General.tsx
│   │   │       ├── LangHelper.tsx
│   │   │       ├── MainWindow.tsx
│   │   │       ├── Speakers.ts
│   │   │       ├── TrayWindow.tsx
│   │   │       └── index.tsx
│   │   └── vite-env.d.ts
│   ├── src-tauri/
│   │   ├── Cargo.toml
│   │   ├── build.rs
│   │   ├── icons/
│   │   │   └── icon.icns
│   │   ├── src/
│   │   │   ├── app/
│   │   │   │   ├── cmd.rs
│   │   │   │   ├── cors.rs
│   │   │   │   ├── fs_extra.rs
│   │   │   │   ├── gpt.rs
│   │   │   │   ├── menu.rs
│   │   │   │   ├── mod.rs
│   │   │   │   ├── setup.rs
│   │   │   │   └── window.rs
│   │   │   ├── conf.rs
│   │   │   ├── main.rs
│   │   │   ├── scripts/
│   │   │   │   ├── chat.js
│   │   │   │   ├── cmd.js
│   │   │   │   ├── core.js
│   │   │   │   ├── dalle2.js
│   │   │   │   ├── export.js
│   │   │   │   ├── markdown.export.js
│   │   │   │   └── popup.core.js
│   │   │   ├── utils.rs
│   │   │   └── vendors/
│   │   │       ├── floating-ui-core.js
│   │   │       ├── floating-ui-dom.js
│   │   │       ├── html2canvas.js
│   │   │       ├── jspdf.js
│   │   │       ├── turndown-plugin-gfm.js
│   │   │       └── turndown.js
│   │   └── tauri.conf.json
│   ├── tsconfig.json
│   ├── tsconfig.node.json
│   └── vite.config.ts
├── LICENSE
├── LangHelper/
│   ├── Assess/
│   │   ├── IflytekAssessment.py
│   │   ├── SpeechSuper.py
│   │   └── __init__.py
│   ├── Recognition/
│   │   ├── IflytekRec.py
│   │   └── __init__.py
│   ├── Resource/
│   │   ├── cn/
│   │   │   ├── read_sentence_cn.pcm
│   │   │   ├── read_sentence_cn.txt
│   │   │   ├── read_syllable_cn.pcm
│   │   │   └── read_syllable_cn.txt
│   │   ├── en/
│   │   │   ├── oral_translation_en.pcm
│   │   │   ├── oral_translation_en.txt
│   │   │   ├── picture_talk_en.pcm
│   │   │   ├── picture_talk_en.txt
│   │   │   ├── read_choice_en.pcm
│   │   │   ├── read_choice_en.txt
│   │   │   ├── read_sentence_en.pcm
│   │   │   ├── read_sentence_en.txt
│   │   │   ├── read_word_en.pcm
│   │   │   ├── read_word_en.txt
│   │   │   ├── retell_en.pcm
│   │   │   ├── retell_en.txt
│   │   │   ├── topic_en.pcm
│   │   │   └── topic_en.txt
│   │   ├── rec/
│   │   │   └── realtime.pcm
│   │   ├── speaker-info.txt
│   │   └── tts_models--en--vctk--vits/
│   │       ├── config.json
│   │       └── speaker_ids.json
│   ├── main.py
│   └── recoder.py
└── README.md
Download .txt
SYMBOL INDEX (466 symbols across 61 files)

FILE: ChatGPT/src-tauri/build.rs
  function main (line 1) | fn main() {

FILE: ChatGPT/src-tauri/src/app/cmd.rs
  function drag_window (line 7) | pub fn drag_window(app: AppHandle) {
  function fullscreen (line 12) | pub fn fullscreen(app: AppHandle) {
  function download (line 22) | pub fn download(app: AppHandle, name: String, blob: Vec<u8>) {
  function save_file (line 35) | pub fn save_file(app: AppHandle, name: String, content: String) {
  function open_link (line 48) | pub fn open_link(app: AppHandle, url: String) {
  function run_check_update (line 53) | pub fn run_check_update(app: AppHandle, silent: bool, has_msg: Option<bo...
  function open_file (line 58) | pub fn open_file(path: PathBuf) {
  function get_data (line 63) | pub async fn get_data(app: AppHandle, url: String, is_msg: Option<bool>)...

FILE: ChatGPT/src-tauri/src/app/cors.rs
  type Message (line 6) | pub struct Message {
  function fetch_data (line 12) | pub async fn fetch_data(

FILE: ChatGPT/src-tauri/src/app/fs_extra.rs
  type Result (line 19) | type Result<T> = std::result::Result<T, Error>;
  type Error (line 22) | pub enum Error {
  method serialize (line 28) | fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::E...
  type Permissions (line 38) | struct Permissions {
  type UnixMetadata (line 47) | struct UnixMetadata {
  type Metadata (line 61) | pub struct Metadata {
  function system_time_to_ms (line 77) | pub fn system_time_to_ms(time: std::io::Result<SystemTime>) -> u64 {
  function metadata (line 87) | pub async fn metadata(path: PathBuf) -> Result<Metadata> {

FILE: ChatGPT/src-tauri/src/app/gpt.rs
  function get_chat_model_cmd (line 13) | pub fn get_chat_model_cmd() -> serde_json::Value {
  type PromptRecord (line 20) | pub struct PromptRecord {
  function parse_prompt (line 27) | pub fn parse_prompt(data: String) -> Vec<PromptRecord> {
  type ModelRecord (line 47) | pub struct ModelRecord {
  function cmd_list (line 56) | pub fn cmd_list() -> Vec<ModelRecord> {
  type FileMetadata (line 75) | pub struct FileMetadata {
  function get_download_list (line 83) | pub fn get_download_list(pathname: &str) -> (Vec<serde_json::Value>, Pat...
  function download_list (line 100) | pub fn download_list(pathname: &str, dir: &str, filename: Option<String>...
  function sync_prompts (line 162) | pub async fn sync_prompts(app: AppHandle, time: u64) -> Option<Vec<Model...
  function sync_user_prompts (line 251) | pub async fn sync_user_prompts(url: String, data_type: String) -> Option...

FILE: ChatGPT/src-tauri/src/app/menu.rs
  function init (line 16) | pub fn init() -> Menu {
  function menu_handler (line 236) | pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
  function tray_menu (line 418) | pub fn tray_menu() -> SystemTray {
  function tray_handler (line 461) | pub fn tray_handler(handle: &AppHandle, event: SystemTrayEvent) {
  function open (line 521) | pub fn open(app: &AppHandle, path: String) {

FILE: ChatGPT/src-tauri/src/app/setup.rs
  function init (line 6) | pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error...

FILE: ChatGPT/src-tauri/src/app/window.rs
  function tray_window (line 6) | pub fn tray_window(handle: &tauri::AppHandle) {
  function dalle2_window (line 42) | pub fn dalle2_window(
  function dalle2_search_window (line 100) | pub fn dalle2_search_window(app: tauri::AppHandle, query: String) {
  function control_window (line 110) | pub fn control_window(handle: tauri::AppHandle) {
  function wa_window (line 134) | pub fn wa_window(
  function window_reload (line 164) | pub fn window_reload(app: tauri::AppHandle, label: &str) {

FILE: ChatGPT/src-tauri/src/conf.rs
  constant APP_WEBSITE (line 11) | pub const APP_WEBSITE: &str = "https://lencx.github.io/app/";
  constant ISSUES_URL (line 12) | pub const ISSUES_URL: &str = "https://github.com/lencx/ChatGPT/issues";
  constant NOFWL_APP (line 13) | pub const NOFWL_APP: &str = "https://github.com/lencx/nofwl";
  constant UPDATE_LOG_URL (line 14) | pub const UPDATE_LOG_URL: &str = "https://github.com/lencx/ChatGPT/blob/...
  constant BUY_COFFEE (line 15) | pub const BUY_COFFEE: &str = "https://www.buymeacoffee.com/lencx";
  constant GITHUB_PROMPTS_CSV_URL (line 16) | pub const GITHUB_PROMPTS_CSV_URL: &str =
  constant APP_CONF_PATH (line 19) | pub const APP_CONF_PATH: &str = "chat.conf.json";
  constant CHATGPT_URL (line 20) | pub const CHATGPT_URL: &str = "https://chat.openai.com";
  constant UA_MOBILE (line 21) | pub const UA_MOBILE: &str = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 lik...
  method new (line 86) | pub fn new() -> Self {
  method file_path (line 136) | pub fn file_path() -> PathBuf {
  method read (line 140) | pub fn read() -> Self {
  method write (line 157) | pub fn write(self) -> Self {
  method amend (line 174) | pub fn amend(self, json: Value) -> Self {
  method titlebar (line 199) | pub fn titlebar(self) -> TitleBarStyle {
  method theme_mode (line 207) | pub fn theme_mode() -> Theme {
  method get_theme (line 222) | pub fn get_theme() -> String {
  method get_auto_update (line 226) | pub fn get_auto_update(self) -> String {
  method theme_check (line 230) | pub fn theme_check(self, mode: &str) -> bool {
  method restart (line 234) | pub fn restart(self, app: tauri::AppHandle) {
  method default (line 240) | fn default() -> Self {
  function get_app_conf (line 250) | pub fn get_app_conf() -> AppConf {
  function reset_app_conf (line 255) | pub fn reset_app_conf() -> AppConf {
  function get_theme (line 260) | pub fn get_theme() -> String {
  function form_confirm (line 265) | pub fn form_confirm(_app: AppHandle, data: serde_json::Value) {
  function form_cancel (line 270) | pub fn form_cancel(app: AppHandle, label: &str, title: &str, msg: &str) {
  function form_msg (line 285) | pub fn form_msg(app: AppHandle, label: &str, title: &str, msg: &str) {

FILE: ChatGPT/src-tauri/src/main.rs
  function main (line 19) | async fn main() {

FILE: ChatGPT/src-tauri/src/scripts/chat.js
  function init (line 25) | async function init() {
  function Get_app_conf (line 56) | async function Get_app_conf(){
  function chatBtns (line 84) | async function chatBtns() {
  function AddRecognitionBtn (line 188) | function AddRecognitionBtn(){
  function Speech_Assessment (line 252) | async function Speech_Assessment(btn){
  function Skip_Speech (line 280) | function Skip_Speech(){
  function SpeechRecognition (line 294) | async function SpeechRecognition(btn, action){
  function Helper_SendMessage (line 360) | function Helper_SendMessage(text){
  function Helper_CheckNewMessages (line 382) | function Helper_CheckNewMessages(){
  function Helper_TagNewWord (line 436) | function Helper_TagNewWord(elements){
  function Helper_NewMessageFlag (line 477) | function Helper_NewMessageFlag() {
  function Helper_SayOutLoud (line 490) | async function Helper_SayOutLoud(text){
  function Helper_Words (line 512) | function Helper_Words(cmd){
  function Helper_SplitIntoSentences (line 541) | function Helper_SplitIntoSentences(text) {
  function copyToClipboard (line 579) | function copyToClipboard(text, btn) {
  function focusOnInput (line 600) | function focusOnInput() {
  function setIcon (line 605) | function setIcon(type) {

FILE: ChatGPT/src-tauri/src/scripts/cmd.js
  function init (line 3) | function init() {
  function cmdTip (line 144) | async function cmdTip() {
  function initDom (line 304) | function initDom() {

FILE: ChatGPT/src-tauri/src/scripts/core.js
  function transformCallback (line 4) | function transformCallback(callback = () => {}, once = false) {
  function invoke (line 19) | async function invoke(cmd, args) {
  function message (line 39) | async function message(message) {
  function init (line 57) | async function init() {
  function coreZoom (line 118) | function coreZoom() {

FILE: ChatGPT/src-tauri/src/scripts/dalle2.js
  function init (line 3) | function init() {

FILE: ChatGPT/src-tauri/src/scripts/export.js
  function init (line 3) | async function init() {

FILE: ChatGPT/src-tauri/src/scripts/popup.core.js
  function init (line 3) | async function init() {

FILE: ChatGPT/src-tauri/src/utils.rs
  function app_root (line 14) | pub fn app_root() -> PathBuf {
  function get_tauri_conf (line 18) | pub fn get_tauri_conf() -> Option<Config> {
  function exists (line 24) | pub fn exists(path: &Path) -> bool {
  function create_file (line 28) | pub fn create_file(path: &Path) -> Result<File> {
  function create_chatgpt_prompts (line 35) | pub fn create_chatgpt_prompts() {
  function script_path (line 43) | pub fn script_path() -> PathBuf {
  function user_script (line 60) | pub fn user_script() -> String {
  function open_file (line 68) | pub fn open_file(path: PathBuf) {
  function convert_path (line 90) | pub fn convert_path(path_str: &str) -> String {
  function clear_conf (line 98) | pub fn clear_conf(app: &tauri::AppHandle) {
  function merge (line 119) | pub fn merge(v: &Value, fields: &HashMap<String, Value>) -> Value {
  function gen_cmd (line 132) | pub fn gen_cmd(name: String) -> String {
  function get_data (line 137) | pub async fn get_data(
  function run_check_update (line 156) | pub fn run_check_update(app: AppHandle<Wry>, silent: bool, has_msg: Opti...
  function prompt_for_install (line 186) | pub async fn prompt_for_install(app: AppHandle<Wry>, update: UpdateRespo...
  function silent_install (line 233) | pub async fn silent_install(app: AppHandle<Wry>, update: UpdateResponse<...
  function is_hidden (line 257) | pub fn is_hidden(entry: &walkdir::DirEntry) -> bool {
  function vec_to_hashmap (line 265) | pub fn vec_to_hashmap(

FILE: ChatGPT/src-tauri/src/vendors/floating-ui-core.js
  function e (line 1) | function e(t){return t.split("-")[1]}
  function n (line 1) | function n(t){return"y"===t?"height":"width"}
  function i (line 1) | function i(t){return t.split("-")[0]}
  function o (line 1) | function o(t){return["top","bottom"].includes(i(t))?"x":"y"}
  function r (line 1) | function r(t,r,a){let{reference:l,floating:s}=t;const f=l.x+l.width/2-s....
  function a (line 1) | function a(t){return"number"!=typeof t?function(t){return{top:0,right:0,...
  function l (line 1) | function l(t){return{...t,top:t.y,left:t.x,right:t.x+t.width,bottom:t.y+...
  function s (line 1) | async function s(t,e){var n;void 0===e&&(e={});const{x:i,y:o,platform:r,...
  function u (line 1) | function u(t,e,n){return c(t,f(e,n))}
  function p (line 1) | function p(t){return t.replace(/left|right|bottom|top/g,(t=>g[t]))}
  function h (line 1) | function h(t,i,r){void 0===r&&(r=!1);const a=e(t),l=o(t),s=n(l);let f="x...
  function x (line 1) | function x(t){return t.replace(/start|end/g,(t=>y[t]))}
  function w (line 1) | function w(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t...
  function v (line 1) | function v(t){return m.some((e=>t[e]>=0))}
  function b (line 1) | function b(t){return"x"===t?"y":"x"}
  method fn (line 1) | async fn(i){const{element:r,padding:l=0}=t||{},{x:s,y:f,placement:c,rect...
  method fn (line 1) | async fn(n){var o,r,a;const{rects:l,middlewareData:f,placement:c,platfor...
  method fn (line 1) | async fn(n){var o;const{placement:r,middlewareData:a,rects:l,initialPlac...
  method fn (line 1) | async fn(e){const{strategy:n="referenceHidden",...i}=t,{rects:o}=e;switc...
  method fn (line 1) | async fn(e){const{placement:n,elements:r,rects:s,platform:u,strategy:m}=...
  method fn (line 1) | fn(e){const{x:n,y:r,placement:a,rects:l,middlewareData:s}=e,{offset:f=0,...
  method fn (line 1) | async fn(n){const{x:r,y:a}=n,l=await async function(t,n){const{placement...
  method fn (line 1) | async fn(e){const{x:n,y:r,placement:a}=e,{mainAxis:l=!0,crossAxis:f=!1,l...
  method fn (line 1) | async fn(n){const{placement:o,rects:r,platform:a,elements:l}=n,{apply:f=...

FILE: ChatGPT/src-tauri/src/vendors/floating-ui-dom.js
  function n (line 1) | function n(t){var e;return(null==(e=t.ownerDocument)?void 0:e.defaultVie...
  function o (line 1) | function o(t){return n(t).getComputedStyle(t)}
  function i (line 1) | function i(t){return s(t)?(t.nodeName||"").toLowerCase():""}
  function l (line 1) | function l(){if(r)return r;const t=navigator.userAgentData;return t&&Arr...
  function c (line 1) | function c(t){return t instanceof n(t).HTMLElement}
  function f (line 1) | function f(t){return t instanceof n(t).Element}
  function s (line 1) | function s(t){return t instanceof n(t).Node}
  function u (line 1) | function u(t){if("undefined"==typeof ShadowRoot)return!1;return t instan...
  function a (line 1) | function a(t){const{overflow:e,overflowX:n,overflowY:i,display:r}=o(t);r...
  function d (line 1) | function d(t){return["table","td","th"].includes(i(t))}
  function h (line 1) | function h(t){const e=/firefox/i.test(l()),n=o(t),i=n.backdropFilter||n....
  function p (line 1) | function p(){return!/^((?!chrome|android).)*safari/i.test(l())}
  function g (line 1) | function g(t){return["html","body","#document"].includes(i(t))}
  function w (line 1) | function w(t){const e=o(t);let n=parseFloat(e.width),i=parseFloat(e.heig...
  function x (line 1) | function x(t){return f(t)?t:t.contextElement}
  function L (line 1) | function L(t){const e=x(t);if(!c(e))return v;const n=e.getBoundingClient...
  function T (line 1) | function T(t,e,o,i){var r,l;void 0===e&&(e=!1),void 0===o&&(o=!1);const ...
  function O (line 1) | function O(t){return((s(t)?t.ownerDocument:t.document)||window.document)...
  function P (line 1) | function P(t){return f(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop...
  function R (line 1) | function R(t){return T(O(t)).left+P(t).scrollLeft}
  function E (line 1) | function E(t,e,n){const o=c(e),r=O(e),l=T(t,!0,"fixed"===n,e);let f={scr...
  function C (line 1) | function C(t){if("html"===i(t))return t;const e=t.assignedSlot||t.parent...
  function j (line 1) | function j(t){return c(t)&&"fixed"!==o(t).position?t.offsetParent:null}
  function F (line 1) | function F(t){const e=n(t);let r=j(t);for(;r&&d(r)&&"static"===o(r).posi...
  function D (line 1) | function D(t){const e=C(t);return g(e)?t.ownerDocument.body:c(e)&&a(e)?e...
  function S (line 1) | function S(t,e){var o;void 0===e&&(e=[]);const i=D(t),r=i===(null==(o=t....
  function W (line 1) | function W(t,i,r){return"viewport"===i?e.rectToClientRect(function(t,e){...
  method getElementRects (line 1) | async getElementRects(t){let{reference:e,floating:n,strategy:o}=t;const ...

FILE: ChatGPT/src-tauri/src/vendors/html2canvas.js
  function A (line 20) | function A(A,e){if("function"!=typeof e&&null!==e)throw new TypeError("C...
  function a (line 20) | function a(A,s,o,i){return new(o=o||Promise)(function(t,e){function r(A)...
  function H (line 20) | function H(t,r){var B,n,s,o={label:0,sent:function(){if(1&s[0])throw s[1...
  function t (line 20) | function t(A,e,t){if(t||2===arguments.length)for(var r,B=0,n=e.length;B<...
  function B (line 20) | function B(A,e,t,r){this.left=A,this.top=e,this.width=t,this.height=r}
  function w (line 20) | function w(A,e,t){return A.slice?A.slice(e,t):new Uint16Array(Array.prot...
  function l (line 20) | function l(A,e,t,r,B,n){this.initialValue=A,this.errorValue=e,this.highS...
  function p (line 20) | function p(A,e,t,r){var B=r[t];if(Array.isArray(A)?-1!==A.indexOf(B):A==...
  function E (line 20) | function E(A,e){for(var t=A;0<=t;){var r=e[t];if(r!==D)return r;t--}retu...
  function I (line 20) | function I(t,A){var e=(B=function(A,r){void 0===r&&(r="strict");var B=[]...
  function gA (line 20) | function gA(A,e,t,r){this.codePoints=A,this.required="!"===e,this.start=...
  function wA (line 20) | function wA(A,e){var t=Q(A),r=(e=I(t,e))[0],B=e[1],n=e[2],s=t.length,o=0...
  function UA (line 20) | function UA(A){return 48<=A&&A<=57}
  function lA (line 20) | function lA(A){return UA(A)||65<=A&&A<=70||97<=A&&A<=102}
  function CA (line 20) | function CA(A){return 10===A||9===A||32===A}
  function uA (line 20) | function uA(A){return 97<=(t=e=A)&&t<=122||65<=(e=e)&&e<=90||128<=A||95=...
  function FA (line 20) | function FA(A){return uA(A)||UA(A)||45===A}
  function hA (line 20) | function hA(A,e){return 92===A&&10!==e}
  function dA (line 20) | function dA(A,e,t){return 45===A?uA(e)||hA(e,t):!!uA(A)||92===A&&10!==e}
  function fA (line 20) | function fA(A,e,t){return 43===A||45===A?!!UA(e)||46===e&&UA(t):UA(46===...
  function XA (line 20) | function XA(){this._value=[]}
  function YA (line 20) | function YA(A){this._tokens=A}
  function WA (line 20) | function WA(A){return 15===A.type}
  function ZA (line 20) | function ZA(A){return 17===A.type}
  function _A (line 20) | function _A(A){return 20===A.type}
  function qA (line 20) | function qA(A){return 0===A.type}
  function jA (line 20) | function jA(A,e){return _A(A)&&A.value===e}
  function zA (line 20) | function zA(A){return 31!==A.type}
  function $A (line 20) | function $A(A){return 31!==A.type&&4!==A.type}
  function Ae (line 20) | function Ae(A){var e=[],t=[];return A.forEach(function(A){if(4===A.type)...
  function ee (line 20) | function ee(A){return 17===A.type||15===A.type}
  function te (line 20) | function te(A){return 16===A.type||ee(A)}
  function re (line 20) | function re(A){return 1<A.length?[A[0],A[1]]:[A[0]]}
  function Be (line 20) | function Be(A,e,t){var r=A[0],A=A[1];return[Ue(r,e),Ue(void 0!==A?A:r,t)]}
  function ne (line 20) | function ne(A){return 15===A.type&&("deg"===A.unit||"grad"===A.unit||"ra...
  function se (line 20) | function se(A){switch(A.filter(_A).map(function(A){return A.value}).join...
  function oe (line 20) | function oe(A){return 0==(255&A)}
  function ie (line 20) | function ie(A){var e=255&A,t=255&A>>8,r=255&A>>16,A=255&A>>24;return e<2...
  function Qe (line 20) | function Qe(A,e){if(17===A.type)return A.number;if(16!==A.type)return 0;...
  function de (line 20) | function de(A,e,t){return t<0&&(t+=1),1<=t&&--t,t<1/6?(e-A)*t*6+A:t<.5?e...
  function fe (line 20) | function fe(A,e){return ue(A,JA.create(e).parseComponentValue())}
  function He (line 20) | function He(A,e){return A=ue(A,e[0]),(e=e[1])&&te(e)?{color:A,stop:e}:{c...
  function pe (line 20) | function pe(A,t){var e=A[0],r=A[A.length-1];null===e.stop&&(e.stop=ae),n...
  function Ee (line 20) | function Ee(A,e,t){var r="number"==typeof A?A:(s=e/2,r=(n=t)/2,s=Ue((B=A...
  function Ie (line 20) | function Ie(A,e){return Math.sqrt(A*A+e*e)}
  function ye (line 20) | function ye(A,e,B,n,s){return[[0,0],[0,e],[A,0],[A,e]].reduce(function(A...
  function Ye (line 20) | function Ye(A,e){return _A(A)&&"normal"===A.value?1.2*e:17===A.type?e*A....
  function Pt (line 20) | function Pt(A,e){return 0!=(A&e)}
  function Xt (line 20) | function Xt(A,e,t){return(A=A&&A[Math.min(e,A.length-1)])?t?A.open:A.clo...
  function gr (line 20) | function gr(A,e){this.animationDuration=lr(A,nr,e.animationDuration),thi...
  function fr (line 20) | function fr(A,e,t){return A.slice?A.slice(e,t):new Uint16Array(Array.pro...
  function pr (line 20) | function pr(A,e,t,r,B,n){this.initialValue=A,this.errorValue=e,this.high...
  function Kr (line 20) | function Kr(A){return kr.get(A)}
  function mr (line 20) | function mr(A){var t=function(A){for(var e=[],t=0,r=A.length;t<r;){var B...
  function Lr (line 20) | function Lr(A){return 0===A[0]&&255===A[1]&&0===A[2]&&255===A[3]}
  method SUPPORT_RANGE_BOUNDS (line 20) | get SUPPORT_RANGE_BOUNDS(){var A=function(A){if(A.createRange){var e=A.c...
  method SUPPORT_WORD_BREAKING (line 20) | get SUPPORT_WORD_BREAKING(){var A=Xr.SUPPORT_RANGE_BOUNDS&&function(A){v...
  method SUPPORT_SVG_DRAWING (line 20) | get SUPPORT_SVG_DRAWING(){var A=function(A){var e=new Image,t=A.createEl...
  method SUPPORT_FOREIGNOBJECT_DRAWING (line 20) | get SUPPORT_FOREIGNOBJECT_DRAWING(){var A="function"==typeof Array.from&...
  method SUPPORT_CORS_IMAGES (line 20) | get SUPPORT_CORS_IMAGES(){var A=void 0!==(new Image).crossOrigin;return ...
  method SUPPORT_RESPONSE_TYPE (line 20) | get SUPPORT_RESPONSE_TYPE(){var A="string"==typeof(new XMLHttpRequest).r...
  method SUPPORT_CORS_XHR (line 20) | get SUPPORT_CORS_XHR(){var A="withCredentials"in new XMLHttpRequest;retu...
  method SUPPORT_NATIVE_TEXT_SEGMENTATION (line 20) | get SUPPORT_NATIVE_TEXT_SEGMENTATION(){var A=!("undefined"==typeof Intl|...
  function rB (line 20) | function rB(A,e){A=Sr.call(this,A,e)||this;return A.src=e.currentSrc||e....
  function sB (line 20) | function sB(A,e){A=BB.call(this,A,e)||this;return A.canvas=e,A.intrinsic...
  function QB (line 20) | function QB(A,e){var t=oB.call(this,A,e)||this,r=new XMLSerializer,A=f(A...
  function gB (line 20) | function gB(A,e){A=cB.call(this,A,e)||this;return A.value=e.value,A}
  function lB (line 20) | function lB(A,e){A=wB.call(this,A,e)||this;return A.start=e.start,A.reve...
  function EB (line 20) | function EB(A,e){var t=CB.call(this,A,e)||this;switch(t.type=e.type.toLo...
  function KB (line 20) | function KB(A,e){A=IB.call(this,A,e)||this,e=e.options[e.selectedIndex||...
  function bB (line 20) | function bB(A,e){A=mB.call(this,A,e)||this;return A.value=e.value,A}
  function xB (line 20) | function xB(A,e){var t,r,B=DB.call(this,A,e)||this;B.src=e.src,B.width=p...
  function MB (line 20) | function MB(A){return"VIDEO"===A.tagName}
  function SB (line 20) | function SB(A){return"STYLE"===A.tagName}
  function TB (line 20) | function TB(A){return 0<A.tagName.indexOf("-")}
  function nn (line 20) | function nn(){this.counters={}}
  function sn (line 20) | function sn(r,A,e,B,t,n){return r<A||e<r?Fn(r,t,0<n.length):B.integers.r...
  function on (line 20) | function on(A,e,t,r){for(var B="";t||A--,B=r(A)+B,e<=(A/=e)*e;);return B}
  function Qn (line 20) | function Qn(A,e,t,r,B){var n=t-e+1;return(A<0?"-":"")+(on(Math.abs(A),n,...
  function cn (line 20) | function cn(A,e,t){void 0===t&&(t=". ");var r=e.length;return on(Math.ab...
  function an (line 20) | function an(A,e,t,r,B,n){if(A<-9999||9999<A)return Fn(A,4,0<B.length);va...
  function fn (line 20) | function fn(A,e,t){if(this.context=A,this.options=t,this.scrolledElement...
  function Hn (line 20) | function Hn(e){return new Promise(function(A){!e.complete&&e.src?(e.onlo...
  function Gn (line 20) | function Gn(){}
  function Vn (line 20) | function Vn(A,e){this.context=A,this._options=e,this._cache={}}
  function _n (line 20) | function _n(A,e){this.type=0,this.x=A,this.y=e}
  function qn (line 20) | function qn(A,e,t){return new Zn(A.x+(e.x-A.x)*t,A.y+(e.y-A.y)*t)}
  function zn (line 20) | function zn(A,e,t,r){this.type=1,this.start=A,this.startControl=e,this.e...
  function $n (line 20) | function $n(A){return 1===A.type}
  function ts (line 20) | function ts(A){return[A.topLeftBorderBox,A.topRightBorderBox,A.bottomRig...
  function rs (line 20) | function rs(A){return[A.topLeftPaddingBox,A.topRightPaddingBox,A.bottomR...
  function Bs (line 20) | function Bs(A){return 1===A.type}
  function ns (line 20) | function ns(A,t){return A.length===t.length&&A.some(function(A,e){return...
  function gs (line 20) | function gs(A,e){var t,r;this.container=A,this.parent=e,this.effects=[],...
  function ws (line 20) | function ws(A,e){switch(e){case 0:return Hs(A.topLeftBorderBox,A.topLeft...
  function Us (line 20) | function Us(A){var e=A.bounds,A=A.styles;return e.add(A.borderLeftWidth,...
  function ls (line 20) | function ls(A){var e=A.styles,t=A.bounds,r=Ue(e.paddingLeft,t.width),B=U...
  function Cs (line 20) | function Cs(A,e,t){var r=(B=Es(A.styles.backgroundOrigin,e),n=A,0===B?n....
  function us (line 20) | function us(A){return _A(A)&&A.value===Ve.AUTO}
  function Fs (line 20) | function Fs(A){return"number"==typeof A}
  function ms (line 20) | function ms(A){this._data={},this._document=A}
  function Ds (line 20) | function Ds(A,e){A=Ls.call(this,A,e)||this;return A._activeEffects=[],A....
  function Vs (line 20) | function Vs(A,e){A=vs.call(this,A,e)||this;return A.canvas=e.canvas||doc...
  function Ns (line 20) | function Ns(A){var e=A.id,A=A.enabled;this.id=e,this.enabled=A,this.star...
  function Xs (line 20) | function Xs(A,e){this.windowBounds=e,this.instanceName="#"+Xs.instanceCo...

FILE: ChatGPT/src-tauri/src/vendors/jspdf.js
  function e (line 51) | function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbo...
  function n (line 51) | function n(){r.console&&"function"==typeof r.console.log&&r.console.log....
  function a (line 51) | function a(t,e,r){var n=new XMLHttpRequest;n.open("GET",t),n.responseTyp...
  function o (line 51) | function o(t){var e=new XMLHttpRequest;e.open("HEAD",t,!1);try{e.send()}...
  function s (line 51) | function s(t){try{t.dispatchEvent(new MouseEvent("click"))}catch(r){var ...
  function h (line 57) | function h(t){var e;t=t||"",this.ok=!1,"#"==t.charAt(0)&&(t=t.substr(1,6...
  function f (line 67) | function f(t,e){var r=t[0],n=t[1],i=t[2],a=t[3];r=p(r,n,i,a,e[0],7,-6808...
  function d (line 67) | function d(t,e,r,n,i,a){return e=S(S(e,t),S(n,a)),S(e<<i|e>>>32-i,r)}
  function p (line 67) | function p(t,e,r,n,i,a,o){return d(e&r|~e&n,t,e,i,a,o)}
  function g (line 67) | function g(t,e,r,n,i,a,o){return d(e&n|r&~n,t,e,i,a,o)}
  function m (line 67) | function m(t,e,r,n,i,a,o){return d(e^r^n,t,e,i,a,o)}
  function v (line 67) | function v(t,e,r,n,i,a,o){return d(r^(e|~n),t,e,i,a,o)}
  function b (line 67) | function b(t){var e,r=t.length,n=[1732584193,-271733879,-1732584194,2717...
  function y (line 67) | function y(t){var e,r=[];for(e=0;e<64;e+=4)r[e>>2]=t.charCodeAt(e)+(t.ch...
  function N (line 67) | function N(t){for(var e="",r=0;r<4;r++)e+=w[t>>8*r+4&15]+w[t>>8*r&15];re...
  function L (line 67) | function L(t){return String.fromCharCode((255&t)>>0,(65280&t)>>8,(167116...
  function A (line 67) | function A(t){return function(t){return t.map(L).join("")}(b(t))}
  function S (line 67) | function S(t,e){if(x){var r=(65535&t)+(65535&e);return(t>>16)+(e>>16)+(r...
  function _ (line 75) | function _(t,e){var r,n,i,a;if(t!==r){for(var o=(i=t,a=1+(256/t.length>>...
  function k (line 86) | function k(t,e,r,n){this.v=1,this.r=2;var i=192;t.forEach((function(t){i...
  function F (line 86) | function F(t){if(/[^\u0000-\u00ff]/.test(t))throw new Error("Invalid PDF...
  function I (line 86) | function I(t){if("object"!==e(t))throw new Error("Invalid Context passed...
  function C (line 86) | function C(t){if(!(this instanceof C))return new C(t);var e="opacity,str...
  function j (line 86) | function j(t,e){this.gState=t,this.matrix=e,this.id="",this.objectNumber...
  function O (line 86) | function O(t,e,r,n,i){if(!(this instanceof O))return new O(t,e,r,n,i);th...
  function B (line 86) | function B(t,e,r,n,i){if(!(this instanceof B))return new B(t,e,r,n,i);th...
  function M (line 86) | function M(t){var n,a="string"==typeof arguments[0]?arguments[0]:"p",o=a...
  function St (line 86) | function St(t){return t.reduce((function(t,e,r){return t[e]=r,t}),{})}
  function Ct (line 117) | function Ct(t){var e=t.family.replace(/"|'/g,"").toLowerCase(),r=functio...
  function jt (line 117) | function jt(t,e,r,n){var i;for(i=r;i>=0&&i<e.length;i+=n)if(t[e[i]])retu...
  function Mt (line 117) | function Mt(t){return[t.stretch,t.style,t.weight,t.family].join(" ")}
  function Et (line 117) | function Et(t,e,r){for(var n=(r=r||{}).defaultFontFamily||"times",i=Obje...
  function qt (line 117) | function qt(t){return t.trimLeft()}
  function Dt (line 117) | function Dt(t,e){for(var r=0;r<t.length;){if(t.charAt(r)===e)return[t.su...
  function Rt (line 117) | function Rt(t){var e=t.match(/^(-[a-z_]|[a-z_])[a-z0-9_-]*/i);return nul...
  function h (line 117) | function h(t,e){if(null===l){var r=function(t){var e=[];return Object.ke...
  function _e (line 117) | function _e(t,e){void 0===e&&(e={});var r=function(){var t=1,e=0;return{...
  function Pe (line 117) | function Pe(t,e){return function(t,e,r){var n=t.length,i=!e||r,a=!r||r.i...
  function i (line 134) | function i(){return(r.html2canvas?Promise.resolve(r.html2canvas):"object...
  function a (line 134) | function a(){return(r.DOMPurify?Promise.resolve(r.DOMPurify):"object"===...
  function e (line 134) | function e(t,e){return Math.floor(t*e/72*96)}
  function i (line 175) | function i(t){var e,r,n,i,a,o,s,c,u,l,h,f,d,p;for(this.data=t,this.pos=8...
  function a (line 175) | function a(a,o,s,c){var u,l,h,f,d,p,g,m,v,b,y,w,N,L,A,x,S,_,P,k,F,I=Math...
  function Be (line 229) | function Be(t){var e=0;if(71!==t[e++]||73!==t[e++]||70!==t[e++]||56!==t[...
  function Me (line 229) | function Me(t,e,r,n){for(var a=t[e++],o=1<<a,s=o+1,c=s+1,u=a+1,l=(1<<u)-...
  function Ee (line 261) | function Ee(t){var e,r,n,i,a,o=Math.floor,s=new Array(64),c=new Array(64...
  function qe (line 268) | function qe(t,e){if(this.pos=0,this.buffer=t,this.datav=new DataView(t.b...
  function De (line 268) | function De(t){function e(t){if(!t)throw Error("assert :P")}function r(t...
  function a (line 331) | function a(){return(r.canvg?Promise.resolve(r.canvg):"object"===(void 0=...
  function d (line 357) | function d(t,e){var r,n=!1;for(r=0;r<t.length;r+=1)t[r]===e&&(n=!0);retu...
  function t (line 397) | function t(t){var e;if(this.rawData=t,e=this.contents=new Te(t),this.con...
  function t (line 397) | function t(t){this.data=null!=t?t:[],this.pos=0,this.length=this.data.le...
  function e (line 397) | function e(t){var e,r,n;for(this.scalarType=t.readInt(),this.tableCount=...
  function n (line 397) | function n(){this.constructor=t}
  function e (line 397) | function e(){return e.__super__.constructor.apply(this,arguments)}
  function t (line 397) | function t(t){var e;this.file=t,e=this.file.directory.tables[this.tag],t...
  function t (line 397) | function t(t,e){var r,n,i,a,o,s,c,u,l,h,f,d,p,g,m,v,b;switch(this.platfo...
  function e (line 397) | function e(){return e.__super__.constructor.apply(this,arguments)}
  function e (line 397) | function e(){return e.__super__.constructor.apply(this,arguments)}
  function e (line 397) | function e(){return e.__super__.constructor.apply(this,arguments)}
  function e (line 397) | function e(){return e.__super__.constructor.apply(this,arguments)}
  function e (line 397) | function e(){return e.__super__.constructor.apply(this,arguments)}
  function e (line 397) | function e(){return e.__super__.constructor.apply(this,arguments)}
  function e (line 397) | function e(){return e.__super__.constructor.apply(this,arguments)}
  function e (line 397) | function e(){return e.__super__.constructor.apply(this,arguments)}
  function t (line 397) | function t(t,e,r,n,i,a){this.raw=t,this.numberOfContours=e,this.xMin=r,t...
  function t (line 397) | function t(t,e,r,n,i){var a,o;for(this.raw=t,this.xMin=e,this.yMin=r,thi...
  function e (line 397) | function e(){return e.__super__.constructor.apply(this,arguments)}
  function t (line 397) | function t(t){this.font=t,this.subset={},this.unicodes={},this.next=33}
  function e (line 397) | function e(){}

FILE: ChatGPT/src-tauri/src/vendors/turndown-plugin-gfm.js
  function highlightedCodeBlock (line 6) | function highlightedCodeBlock (turndownService) {
  function strikethrough (line 30) | function strikethrough (turndownService) {
  function isHeadingRow (line 98) | function isHeadingRow (tr) {
  function isFirstTbody (line 110) | function isFirstTbody (element) {
  function cell (line 123) | function cell (content, node) {
  function tables (line 130) | function tables (turndownService) {
  function taskListItems (line 137) | function taskListItems (turndownService) {
  function gfm (line 148) | function gfm (turndownService) {

FILE: ChatGPT/src-tauri/src/vendors/turndown.js
  function u (line 1) | function u(e,n){return Array(n+1).join(e)}
  function o (line 1) | function o(e){return l(e,n)}
  function i (line 1) | function i(e){return l(e,r)}
  function l (line 1) | function l(e,n){return 0<=n.indexOf(e.nodeName)}
  function c (line 1) | function c(n,e){return n.getElementsByTagName&&e.some(function(e){return...
  function s (line 1) | function s(e){return e?e.replace(/(\n+\s*)+/g,"\n"):""}
  function f (line 1) | function f(e){for(var n in this.options=e,this._keep=[],this._remove=[],...
  function d (line 1) | function d(e,n,t){for(var r=0;r<e.length;r++){var i=e[r];if(function(e,n...
  function p (line 1) | function p(e){var n=e.nextSibling||e.parentNode;return e.parentNode.remo...
  function h (line 1) | function h(e,n,t){return e&&e.parentNode===n||t(n)?n.nextSibling||n.pare...
  function e (line 1) | function e(){}
  function v (line 1) | function v(e,n){return function(e){var n=e.element,t=e.isBlock,r=e.isVoi...
  function y (line 1) | function y(e){return"PRE"===e.nodeName||"CODE"===e.nodeName}
  function N (line 1) | function N(e,n){var t;return e.isBlock=o(e),e.isCode="CODE"===e.nodeName...
  function E (line 1) | function E(e,n,t){var r,i,n="left"===e?(r=n.previousSibling,/ $/):(r=n.n...
  function C (line 1) | function C(e){if(!(this instanceof C))return new C(e);this.options=funct...
  function k (line 1) | function k(e){var r=this;return T.call(e.childNodes,function(e,n){var t=...
  function b (line 1) | function b(e,n){var t=function(e){for(var n=e.length;0<n&&"\n"===e[n-1];...

FILE: ChatGPT/src/components/FilePath/index.tsx
  type FilePathProps (line 7) | interface FilePathProps {

FILE: ChatGPT/src/components/Markdown/Editor.tsx
  type MarkdownEditorProps (line 8) | interface MarkdownEditorProps {

FILE: ChatGPT/src/components/Markdown/index.tsx
  type MarkdownProps (line 12) | interface MarkdownProps {
  method code (line 27) | code({ node, inline, className, children, ...props }) {

FILE: ChatGPT/src/components/SwitchOrigin/index.tsx
  type SwitchOriginProps (line 8) | interface SwitchOriginProps {

FILE: ChatGPT/src/components/Tags/index.tsx
  type TagsProps (line 8) | interface TagsProps {

FILE: ChatGPT/src/hooks/useChatModel.ts
  function useChatModel (line 8) | function useChatModel(key: string, file = CHAT_MODEL_JSON) {
  function useCacheModel (line 28) | function useCacheModel(file = '') {

FILE: ChatGPT/src/hooks/useColumns.tsx
  function useColumns (line 6) | function useColumns(columns: any[] = []) {
  type EditRowProps (line 49) | interface EditRowProps {

FILE: ChatGPT/src/hooks/useData.ts
  function useData (line 6) | function useData(oData: any[]) {

FILE: ChatGPT/src/hooks/useInit.ts
  function useInit (line 4) | function useInit(callback: () => void) {

FILE: ChatGPT/src/hooks/useJson.ts
  function useJson (line 6) | function useJson<T>(file: string) {

FILE: ChatGPT/src/hooks/useTable.tsx
  type rowSelectionOptions (line 7) | type rowSelectionOptions = {
  function useTableRowSelection (line 11) | function useTableRowSelection(options?: Partial<rowSelectionOptions>) {
  constant TABLE_PAGINATION (line 50) | const TABLE_PAGINATION = {

FILE: ChatGPT/src/icons/SplitIcon.tsx
  type IconProps (line 4) | interface IconProps {
  function SplitIcon (line 8) | function SplitIcon(props: Partial<CustomIconComponentProps & IconProps>) {

FILE: ChatGPT/src/layout/index.tsx
  function ChatLayout (line 14) | function ChatLayout() {

FILE: ChatGPT/src/routes.tsx
  type ChatRouteMetaObject (line 27) | type ChatRouteMetaObject = {
  type ChatRouteObject (line 32) | type ChatRouteObject = {
  type MenuItem (line 132) | type MenuItem = Required<MenuProps>['items'][number];

FILE: ChatGPT/src/utils.ts
  constant APP_CONF_JSON (line 5) | const APP_CONF_JSON = 'chat.conf.json';
  constant CHAT_MODEL_JSON (line 6) | const CHAT_MODEL_JSON = 'chat.model.json';
  constant CHAT_MODEL_CMD_JSON (line 7) | const CHAT_MODEL_CMD_JSON = 'chat.model.cmd.json';
  constant CHAT_DOWNLOAD_JSON (line 8) | const CHAT_DOWNLOAD_JSON = 'chat.download.json';
  constant CHAT_AWESOME_JSON (line 9) | const CHAT_AWESOME_JSON = 'chat.awesome.json';
  constant CHAT_NOTES_JSON (line 10) | const CHAT_NOTES_JSON = 'chat.notes.json';
  constant CHAT_PROMPTS_CSV (line 11) | const CHAT_PROMPTS_CSV = 'chat.prompts.csv';
  constant GITHUB_PROMPTS_CSV_URL (line 12) | const GITHUB_PROMPTS_CSV_URL =
  constant GITHUB_LOG_URL (line 14) | const GITHUB_LOG_URL = 'https://raw.githubusercontent.com/lencx/ChatGPT/...
  constant DISABLE_AUTO_COMPLETE (line 16) | const DISABLE_AUTO_COMPLETE = {
  type readJSONOpts (line 34) | type readJSONOpts = { defaultVal?: Record<string, any>; isRoot?: boolean...
  type writeJSONOpts (line 71) | type writeJSONOpts = { dir?: string; isRoot?: boolean };

FILE: ChatGPT/src/view/about/index.tsx
  function About (line 10) | function About() {

FILE: ChatGPT/src/view/awesome/Form.tsx
  type AwesomeFormProps (line 8) | interface AwesomeFormProps {

FILE: ChatGPT/src/view/awesome/index.tsx
  function Awesome (line 16) | function Awesome() {

FILE: ChatGPT/src/view/dashboard/index.tsx
  function Dashboard (line 13) | function Dashboard() {

FILE: ChatGPT/src/view/download/index.tsx
  function renderFile (line 13) | function renderFile(buff: Uint8Array, type: string) {
  function Download (line 21) | function Download() {

FILE: ChatGPT/src/view/markdown/index.tsx
  function Markdown (line 19) | function Markdown() {

FILE: ChatGPT/src/view/model/SyncCustom/Form.tsx
  type SyncFormProps (line 15) | interface SyncFormProps {

FILE: ChatGPT/src/view/model/SyncCustom/index.tsx
  function SyncCustom (line 21) | function SyncCustom() {

FILE: ChatGPT/src/view/model/SyncPrompts/index.tsx
  function SyncPrompts (line 17) | function SyncPrompts() {

FILE: ChatGPT/src/view/model/SyncRecord/index.tsx
  function SyncRecord (line 17) | function SyncRecord() {

FILE: ChatGPT/src/view/model/UserCustom/Form.tsx
  type UserCustomFormProps (line 8) | interface UserCustomFormProps {

FILE: ChatGPT/src/view/model/UserCustom/index.tsx
  function UserCustom (line 15) | function UserCustom() {

FILE: ChatGPT/src/view/notes/index.tsx
  function Notes (line 14) | function Notes() {

FILE: ChatGPT/src/view/settings/General.tsx
  function General (line 9) | function General() {

FILE: ChatGPT/src/view/settings/LangHelper.tsx
  function LangHelper (line 7) | function LangHelper({ form }: { form: FormInstance }) {

FILE: ChatGPT/src/view/settings/MainWindow.tsx
  function MainWindow (line 44) | function MainWindow() {

FILE: ChatGPT/src/view/settings/TrayWindow.tsx
  function TrayWindow (line 20) | function TrayWindow() {

FILE: ChatGPT/src/view/settings/index.tsx
  function Settings (line 15) | function Settings() {

FILE: LangHelper/Assess/IflytekAssessment.py
  class Ws_Param (line 24) | class Ws_Param(object):
    method __init__ (line 26) | def __init__(
    method create_url (line 53) | def create_url(self):
  class Assessment (line 87) | class Assessment:
    method __init__ (line 88) | def __init__(self,APPID,APISecret,APIKey,AudioFile):
    method start_connection (line 109) | def start_connection(self,text):
    method close_connection (line 122) | def close_connection(self):
    method get_finish_state (line 127) | def get_finish_state(self):
    method on_message (line 130) | def on_message(self,ws, message):
    method on_error (line 165) | def on_error(self,ws, error):
    method on_close (line 170) | def on_close(self,ws):
    method on_open (line 176) | def on_open(self,ws):

FILE: LangHelper/Assess/SpeechSuper.py
  class SpeechSuper (line 11) | class SpeechSuper:
    method __init__ (line 12) | def __init__(
    method initConnnct (line 37) | async def initConnnct(self,websocket):
    method startScore (line 64) | async def startScore(self, websocket, request):
    method main_logic (line 115) | async def main_logic(self,refText):

FILE: LangHelper/Recognition/IflytekRec.py
  class Recognition (line 9) | class  Recognition():
    method __init__ (line 10) | def __init__(self, app_id, api_key):
    method update_request_parameter (line 25) | def update_request_parameter(self):
    method set_language (line 37) | def set_language(self, lang):
    method get_finish_state (line 40) | def get_finish_state(self):
    method start_connection (line 43) | def start_connection(self):
    method check_connection (line 57) | def check_connection(self):
    method send (line 60) | def send(self, file_path, chunk):
    method send_endtag (line 83) | def send_endtag(self):
    method recv (line 87) | def recv(self):
    method close (line 123) | def close(self):

FILE: LangHelper/main.py
  function Reed_MultiSpeaker (line 50) | def Reed_MultiSpeaker(path):
  function TextIsSuitable (line 63) | def TextIsSuitable(text):
  function play_audio (line 75) | def play_audio(path) :
  function generate_voice (line 80) | def generate_voice(text:str, path:str,speaker:str):
  function serve_forever (line 111) | def serve_forever(server):
  function is_audio_ready (line 114) | def is_audio_ready(file_path):
  class RequestHandler (line 121) | class RequestHandler(BaseHTTPRequestHandler):
    method do_OPTIONS (line 122) | def do_OPTIONS(self):
    method do_POST (line 130) | def do_POST(self):
  function RealTimeStt (line 263) | def RealTimeStt(file_path):

FILE: LangHelper/recoder.py
  class VoiceRecorder (line 5) | class VoiceRecorder:
    method __init__ (line 6) | def __init__(self, root_path):
    method start (line 16) | def start(self):
    method stop (line 27) | def stop(self):
    method read_audio (line 38) | def read_audio(self):
    method save_to_pcm (line 45) | def save_to_pcm(self, filename, frames):
    method save_to_wav (line 49) | def save_to_wav(self,filename,frames):
Condensed preview — 128 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,026K chars).
[
  {
    "path": "ChatGPT/.gitattributes",
    "chars": 101,
    "preview": "*.js linguist-vendored\n*.tsx linguist-vendored\n*.scss linguist-vendored\nsrc/**/*.ts linguist-vendored"
  },
  {
    "path": "ChatGPT/.gitignore",
    "chars": 305,
    "preview": "package-lock.json\nnode_modules/\n\n.yarn/*\n.pnp.*\n\n# rust\ntarget/\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-e"
  },
  {
    "path": "ChatGPT/.husky/pre-commit",
    "chars": 93,
    "preview": "#!/usr/bin/env sh\n. \"$(dirname -- \"$0\")/_/husky.sh\"\n\nnpm run pretty-quick\ncargo fmt\ngit add ."
  },
  {
    "path": "ChatGPT/.npmrc",
    "chars": 55,
    "preview": "registry=https://registry.npmjs.org/\nengine-strict=true"
  },
  {
    "path": "ChatGPT/.prettierignore",
    "chars": 415,
    "preview": "package-lock.json\nnode_modules/\nyarn.lock\n*.lock\n\ncasks/\n\n# rust\nsrc-tauri/\ntarget/\nCargo.lock\n*.toml\n\n# Logs\nlogs\n*.log"
  },
  {
    "path": "ChatGPT/.prettierrc",
    "chars": 106,
    "preview": "{\n  \"trailingComma\": \"all\",\n  \"singleQuote\": true,\n  \"semi\": true,\n  \"tabWidth\": 2,\n  \"printWidth\": 100\n}\n"
  },
  {
    "path": "ChatGPT/.vscode/extensions.json",
    "chars": 80,
    "preview": "{\n  \"recommendations\": [\"tauri-apps.tauri-vscode\", \"rust-lang.rust-analyzer\"]\n}\n"
  },
  {
    "path": "ChatGPT/Cargo.toml",
    "chars": 182,
    "preview": "[workspace]\nmembers = [\"src-tauri\"]\n\n# fix: mac v1.2.0 can not copy/paste\n# https://github.com/tauri-apps/tauri/issues/5"
  },
  {
    "path": "ChatGPT/LICENSE",
    "chars": 34522,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "ChatGPT/README-ZH_CN.md",
    "chars": 9924,
    "preview": "<p align=\"center\">\n  <img width=\"180\" src=\"./public/logo.png\" alt=\"ChatGPT\">\n  <h1 align=\"center\">ChatGPT</h1>\n  <p alig"
  },
  {
    "path": "ChatGPT/README.md",
    "chars": 60,
    "preview": "adapted from [ChatGPT桌面版](https://github.com/lencx/ChatGPT)\n"
  },
  {
    "path": "ChatGPT/UPDATE_LOG.md",
    "chars": 8062,
    "preview": "# UPDATE LOG\n\n**🛑 URGENT NOTICE: A hacker has been found to take advantage of the heat of `lencx/ChatGPT` to plant a Tro"
  },
  {
    "path": "ChatGPT/casks/chatgpt.rb",
    "chars": 920,
    "preview": "cask \"chatgpt\" do\n  version \"0.12.0\"\n  arch = Hardware::CPU.arch.to_s\n  sha256s = {\n    \"x86_64\" => \"d7f32d11f86ad8ac073"
  },
  {
    "path": "ChatGPT/index.html",
    "chars": 295,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-w"
  },
  {
    "path": "ChatGPT/package.json",
    "chars": 2486,
    "preview": "{\n  \"name\": \"chatgpt\",\n  \"version\": \"0.0.0\",\n  \"scripts\": {\n    \"dev:fe\": \"vite\",\n    \"build:fe\": \"tsc && vite build\",\n "
  },
  {
    "path": "ChatGPT/rustfmt.toml",
    "chars": 333,
    "preview": "max_width = 100\nhard_tabs = false\ntab_spaces = 2\nnewline_style = \"Auto\"\nuse_small_heuristics = \"Default\"\nreorder_imports"
  },
  {
    "path": "ChatGPT/src/components/FilePath/index.tsx",
    "chars": 959,
    "preview": "import { FC, useEffect, useState } from 'react';\nimport clsx from 'clsx';\nimport { path, shell } from '@tauri-apps/api';"
  },
  {
    "path": "ChatGPT/src/components/Markdown/Editor.tsx",
    "chars": 1269,
    "preview": "import { FC, useEffect, useState } from 'react';\nimport Editor from '@monaco-editor/react';\nimport { Panel, PanelGroup, "
  },
  {
    "path": "ChatGPT/src/components/Markdown/index.scss",
    "chars": 599,
    "preview": ".markdown-body {\n  height: 100%;\n  overflow: auto;\n  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto S"
  },
  {
    "path": "ChatGPT/src/components/Markdown/index.tsx",
    "chars": 1519,
    "preview": "import { FC } from 'react';\nimport clsx from 'clsx';\nimport ReactMarkdown from 'react-markdown';\nimport remarkGfm from '"
  },
  {
    "path": "ChatGPT/src/components/SwitchOrigin/index.tsx",
    "chars": 3133,
    "preview": "import { FC } from 'react';\nimport { Link } from 'react-router-dom';\nimport { Form, Select, Tag, Tooltip, Switch } from "
  },
  {
    "path": "ChatGPT/src/components/Tags/index.tsx",
    "chars": 2389,
    "preview": "import { FC, useEffect, useRef, useState } from 'react';\nimport { PlusOutlined } from '@ant-design/icons';\nimport { Inpu"
  },
  {
    "path": "ChatGPT/src/hooks/useChatModel.ts",
    "chars": 1852,
    "preview": "import { useState, useEffect } from 'react';\nimport { clone } from 'lodash';\nimport { invoke } from '@tauri-apps/api';\n\n"
  },
  {
    "path": "ChatGPT/src/hooks/useColumns.tsx",
    "chars": 2016,
    "preview": "import { FC, useState, useCallback } from 'react';\nimport { Input } from 'antd';\n\nimport { DISABLE_AUTO_COMPLETE } from "
  },
  {
    "path": "ChatGPT/src/hooks/useData.ts",
    "chars": 1554,
    "preview": "import { useState, useEffect } from 'react';\nimport { v4 } from 'uuid';\n\nexport const safeKey = Symbol('chat-id');\n\nexpo"
  },
  {
    "path": "ChatGPT/src/hooks/useInit.ts",
    "chars": 303,
    "preview": "import { useRef, useEffect } from 'react';\n\n// fix: Two interface requests will be made in development mode\nexport defau"
  },
  {
    "path": "ChatGPT/src/hooks/useJson.ts",
    "chars": 511,
    "preview": "import { useState } from 'react';\n\nimport { readJSON, writeJSON } from '@/utils';\nimport useInit from '@/hooks/useInit';"
  },
  {
    "path": "ChatGPT/src/hooks/useTable.tsx",
    "chars": 1760,
    "preview": "import React, { useState } from 'react';\nimport { Table } from 'antd';\nimport type { TableRowSelection } from 'antd/es/t"
  },
  {
    "path": "ChatGPT/src/icons/SplitIcon.tsx",
    "chars": 1115,
    "preview": "import Icon from '@ant-design/icons';\nimport type { CustomIconComponentProps } from '@ant-design/icons/lib/components/Ic"
  },
  {
    "path": "ChatGPT/src/layout/index.scss",
    "chars": 538,
    "preview": ".chat-logo {\n  text-align: center;\n  height: 48px;\n\n  img {\n    width: 44px;\n    height: 44px;\n    margin-top: 4px;\n  }\n"
  },
  {
    "path": "ChatGPT/src/layout/index.tsx",
    "chars": 3703,
    "preview": "import { useEffect, useState } from 'react';\nimport { Layout, Menu, Tooltip, ConfigProvider, theme, Tag } from 'antd';\ni"
  },
  {
    "path": "ChatGPT/src/main.scss",
    "chars": 1723,
    "preview": ":root {\n  font-family: Inter, Avenir, Helvetica, Arial, sans-serif;\n  font-size: 16px;\n  line-height: 24px;\n  font-weigh"
  },
  {
    "path": "ChatGPT/src/main.tsx",
    "chars": 414,
    "preview": "import { StrictMode, Suspense } from 'react';\nimport { BrowserRouter } from 'react-router-dom';\nimport ReactDOM from 're"
  },
  {
    "path": "ChatGPT/src/routes.tsx",
    "chars": 3011,
    "preview": "import { useRoutes } from 'react-router-dom';\nimport {\n  SettingOutlined,\n  BulbOutlined,\n  SyncOutlined,\n  FileSyncOutl"
  },
  {
    "path": "ChatGPT/src/utils.ts",
    "chars": 2789,
    "preview": "import { readTextFile, writeTextFile, exists, createDir } from '@tauri-apps/api/fs';\nimport { homeDir, join, dirname } f"
  },
  {
    "path": "ChatGPT/src/view/about/index.scss",
    "chars": 362,
    "preview": ".about {\n  .log-tab {\n    font-size: 14px;\n\n    h2 {\n      font-size: 16px;\n    }\n  }\n\n  .markdown-body {\n    background"
  },
  {
    "path": "ChatGPT/src/view/about/index.tsx",
    "chars": 3642,
    "preview": "import { useState } from 'react';\nimport { invoke } from '@tauri-apps/api';\nimport { Tabs, Tag } from 'antd';\n\nimport { "
  },
  {
    "path": "ChatGPT/src/view/awesome/Form.tsx",
    "chars": 1804,
    "preview": "import { useEffect, ForwardRefRenderFunction, useImperativeHandle, forwardRef } from 'react';\nimport { Form, Input, Swit"
  },
  {
    "path": "ChatGPT/src/view/awesome/config.tsx",
    "chars": 1688,
    "preview": "import { Tag, Space, Popconfirm, Switch } from 'antd';\nimport { open } from '@tauri-apps/api/shell';\n\nexport const aweso"
  },
  {
    "path": "ChatGPT/src/view/awesome/index.tsx",
    "chars": 5978,
    "preview": "import { useRef, useEffect, useState } from 'react';\nimport { Link, useNavigate } from 'react-router-dom';\nimport { Tabl"
  },
  {
    "path": "ChatGPT/src/view/dashboard/index.scss",
    "chars": 1134,
    "preview": ".dashboard {\n  position: fixed;\n  width: calc(100% - 30px);\n  height: calc(100% - 30px);\n  overflow-y: auto;\n  padding: "
  },
  {
    "path": "ChatGPT/src/view/dashboard/index.tsx",
    "chars": 3213,
    "preview": "import { useEffect, useState } from 'react';\nimport clsx from 'clsx';\nimport { useSearchParams } from 'react-router-dom'"
  },
  {
    "path": "ChatGPT/src/view/download/config.tsx",
    "chars": 1939,
    "preview": "import { useState } from 'react';\nimport { Tag, Space, Popconfirm } from 'antd';\nimport { path, shell } from '@tauri-app"
  },
  {
    "path": "ChatGPT/src/view/download/index.tsx",
    "chars": 4515,
    "preview": "import { useEffect, useState } from 'react';\nimport { Table, Modal, Popconfirm, Button, message } from 'antd';\nimport { "
  },
  {
    "path": "ChatGPT/src/view/markdown/index.scss",
    "chars": 316,
    "preview": ".md-task {\n  margin-bottom: 5px;\n  display: flex;\n  justify-content: space-between;\n\n  .ant-breadcrumb-link {\n    paddin"
  },
  {
    "path": "ChatGPT/src/view/markdown/index.tsx",
    "chars": 1667,
    "preview": "import { useState } from 'react';\nimport { useLocation } from 'react-router-dom';\nimport { Breadcrumb } from 'antd';\nimp"
  },
  {
    "path": "ChatGPT/src/view/model/SyncCustom/Form.tsx",
    "chars": 3092,
    "preview": "import {\n  useEffect,\n  useState,\n  ForwardRefRenderFunction,\n  useImperativeHandle,\n  forwardRef,\n} from 'react';\nimpor"
  },
  {
    "path": "ChatGPT/src/view/model/SyncCustom/config.tsx",
    "chars": 2406,
    "preview": "import { useState } from 'react';\nimport { Tag, Space, Popconfirm } from 'antd';\nimport { HistoryOutlined } from '@ant-d"
  },
  {
    "path": "ChatGPT/src/view/model/SyncCustom/index.tsx",
    "chars": 4666,
    "preview": "import { useState, useRef, useEffect } from 'react';\nimport { Table, Modal, Button, message } from 'antd';\nimport { invo"
  },
  {
    "path": "ChatGPT/src/view/model/SyncPrompts/config.tsx",
    "chars": 1036,
    "preview": "import { Table, Switch, Tag } from 'antd';\n\nimport { genCmd } from '@/utils';\n\nexport const syncColumns = () => [\n  {\n  "
  },
  {
    "path": "ChatGPT/src/view/model/SyncPrompts/index.scss",
    "chars": 170,
    "preview": ".chat-table-tip,\n.chat-table-btns {\n  display: flex;\n  justify-content: space-between;\n}\n\n.chat-table-btns {\n  margin-bo"
  },
  {
    "path": "ChatGPT/src/view/model/SyncPrompts/index.tsx",
    "chars": 3662,
    "preview": "import { useEffect, useState } from 'react';\nimport { Table, Button, Popconfirm } from 'antd';\nimport { invoke, path } f"
  },
  {
    "path": "ChatGPT/src/view/model/SyncRecord/config.tsx",
    "chars": 1175,
    "preview": "import { Switch, Tag, Table } from 'antd';\n\nimport { genCmd } from '@/utils';\n\nexport const syncColumns = () => [\n  {\n  "
  },
  {
    "path": "ChatGPT/src/view/model/SyncRecord/index.tsx",
    "chars": 3209,
    "preview": "import { useEffect, useState } from 'react';\nimport { useLocation } from 'react-router-dom';\nimport { ArrowLeftOutlined "
  },
  {
    "path": "ChatGPT/src/view/model/UserCustom/Form.tsx",
    "chars": 1806,
    "preview": "import { useEffect, ForwardRefRenderFunction, useImperativeHandle, forwardRef } from 'react';\nimport { Form, Input, Swit"
  },
  {
    "path": "ChatGPT/src/view/model/UserCustom/config.tsx",
    "chars": 1559,
    "preview": "import { Tag, Switch, Space, Popconfirm, Table } from 'antd';\n\nexport const modelColumns = () => [\n  {\n    title: '/{cmd"
  },
  {
    "path": "ChatGPT/src/view/model/UserCustom/index.tsx",
    "chars": 4667,
    "preview": "import { useState, useRef, useEffect } from 'react';\nimport { Table, Button, Modal, message } from 'antd';\nimport { path"
  },
  {
    "path": "ChatGPT/src/view/notes/config.tsx",
    "chars": 1765,
    "preview": "import { useState } from 'react';\nimport { Link } from 'react-router-dom';\nimport { Space, Popconfirm } from 'antd';\nimp"
  },
  {
    "path": "ChatGPT/src/view/notes/index.tsx",
    "chars": 4014,
    "preview": "import { useEffect, useState } from 'react';\nimport { Table, Modal, Popconfirm, Button, message } from 'antd';\nimport { "
  },
  {
    "path": "ChatGPT/src/view/settings/General.tsx",
    "chars": 3659,
    "preview": "import { useState } from 'react';\nimport { Form, Radio, Switch, Input, Tooltip, Select, Tag } from 'antd';\nimport { Ques"
  },
  {
    "path": "ChatGPT/src/view/settings/LangHelper.tsx",
    "chars": 5808,
    "preview": "import { useState} from 'react';\nimport useInit from '@/hooks/useInit';\nimport {Form,Switch,Select,Radio,Input} from 'an"
  },
  {
    "path": "ChatGPT/src/view/settings/MainWindow.tsx",
    "chars": 2351,
    "preview": "import { Form, Switch, Input, InputNumber, Tooltip } from 'antd';\nimport { QuestionCircleOutlined } from '@ant-design/ic"
  },
  {
    "path": "ChatGPT/src/view/settings/Speakers.ts",
    "chars": 3491,
    "preview": "\nexport const speakers: string[][] =[\n    ['p225', 'F', 'English'],\n    ['p226', 'M', 'English'],\n    ['p227', 'M', 'Eng"
  },
  {
    "path": "ChatGPT/src/view/settings/TrayWindow.tsx",
    "chars": 1312,
    "preview": "import { Form, Switch, Input, InputNumber, Tooltip } from 'antd';\nimport { QuestionCircleOutlined } from '@ant-design/ic"
  },
  {
    "path": "ChatGPT/src/view/settings/index.tsx",
    "chars": 3692,
    "preview": "import { useEffect, useState } from 'react';\nimport { useSearchParams } from 'react-router-dom';\nimport { Form, Tabs, Sp"
  },
  {
    "path": "ChatGPT/src/vite-env.d.ts",
    "chars": 38,
    "preview": "/// <reference types=\"vite/client\" />\n"
  },
  {
    "path": "ChatGPT/src-tauri/Cargo.toml",
    "chars": 1924,
    "preview": "[package]\nname = \"chatgpt\"\nversion = \"0.0.0\"\nauthors = [\"lencx <cxin1314@gmail.com>\"]\ndescription = \"ChatGPT Desktop App"
  },
  {
    "path": "ChatGPT/src-tauri/build.rs",
    "chars": 37,
    "preview": "fn main() {\n  tauri_build::build()\n}\n"
  },
  {
    "path": "ChatGPT/src-tauri/src/app/cmd.rs",
    "chars": 1886,
    "preview": "use crate::utils;\nuse log::error;\nuse std::{fs, path::PathBuf};\nuse tauri::{api, command, AppHandle, Manager};\n\n#[comman"
  },
  {
    "path": "ChatGPT/src-tauri/src/app/cors.rs",
    "chars": 1958,
    "preview": "use serde::{Deserialize, Serialize};\nuse reqwest::{Client, Method, RequestBuilder,Proxy};\n// use wry::http::UriScheme;\n\n"
  },
  {
    "path": "ChatGPT/src-tauri/src/app/fs_extra.rs",
    "chars": 2887,
    "preview": "// https://github.com/tauri-apps/tauri-plugin-fs-extra/blob/dev/src/lib.rs\n\n// Copyright 2019-2021 Tauri Programme withi"
  },
  {
    "path": "ChatGPT/src-tauri/src/app/gpt.rs",
    "chars": 7885,
    "preview": "use crate::{\n  app::{fs_extra, window},\n  conf::GITHUB_PROMPTS_CSV_URL,\n  utils,\n};\nuse log::{error, info};\nuse regex::R"
  },
  {
    "path": "ChatGPT/src-tauri/src/app/menu.rs",
    "chars": 16501,
    "preview": "use crate::{\n  app::window,\n  conf::{self, AppConf},\n  utils,\n};\nuse tauri::{\n  AppHandle, CustomMenuItem, Manager, Menu"
  },
  {
    "path": "ChatGPT/src-tauri/src/app/mod.rs",
    "chars": 103,
    "preview": "pub mod cmd;\npub mod fs_extra;\npub mod gpt;\npub mod menu;\npub mod setup;\npub mod window;\npub mod cors;\n"
  },
  {
    "path": "ChatGPT/src-tauri/src/app/setup.rs",
    "chars": 3714,
    "preview": "use crate::{app::window, conf::AppConf, utils};\nuse log::{error, info};\nuse tauri::{utils::config::WindowUrl, window::Wi"
  },
  {
    "path": "ChatGPT/src-tauri/src/app/window.rs",
    "chars": 4950,
    "preview": "use crate::{conf::AppConf, utils};\nuse log::info;\nuse std::time::SystemTime;\nuse tauri::{utils::config::WindowUrl, windo"
  },
  {
    "path": "ChatGPT/src-tauri/src/conf.rs",
    "chars": 7894,
    "preview": "use log::{error, info};\nuse serde_json::Value;\nuse std::{collections::BTreeMap, path::PathBuf};\nuse tauri::{Manager, The"
  },
  {
    "path": "ChatGPT/src-tauri/src/main.rs",
    "chars": 3694,
    "preview": "#![cfg_attr(\n  all(not(debug_assertions), target_os = \"windows\"),\n  windows_subsystem = \"windows\"\n)]\n\nmod app;\nmod conf;"
  },
  {
    "path": "ChatGPT/src-tauri/src/scripts/chat.js",
    "chars": 32550,
    "preview": "var RecBtnClickCnt = 0;\nconst SpeechRecognitionApi_Sart = 'http://localhost:6868/Rec/Start';\nconst SpeechRecognitionApi_"
  },
  {
    "path": "ChatGPT/src-tauri/src/scripts/cmd.js",
    "chars": 10313,
    "preview": "// *** Core Script - CMD ***\n\nfunction init() {\n  const styleDom = document.createElement('style');\n  styleDom.innerHTML"
  },
  {
    "path": "ChatGPT/src-tauri/src/scripts/core.js",
    "chars": 5757,
    "preview": "// *** Core Script - IPC ***\n\nconst uid = () => window.crypto.getRandomValues(new Uint32Array(1))[0];\nfunction transform"
  },
  {
    "path": "ChatGPT/src-tauri/src/scripts/dalle2.js",
    "chars": 1067,
    "preview": "// *** Core Script - DALL·E 2 ***\n\nfunction init() {\n  document.addEventListener(\"click\", (e) => {\n    const origin = e."
  },
  {
    "path": "ChatGPT/src-tauri/src/scripts/export.js",
    "chars": 15828,
    "preview": "// *** Core Script - Export ***\n\nasync function init() {\n  if (window.location.pathname === '/auth/login') return;\n  con"
  },
  {
    "path": "ChatGPT/src-tauri/src/scripts/markdown.export.js",
    "chars": 1065,
    "preview": "var ExportMD = (function () {\n  if (!TurndownService || !turndownPluginGfm) return;\n  const hljsREG = /^.*(hljs).*(langu"
  },
  {
    "path": "ChatGPT/src-tauri/src/scripts/popup.core.js",
    "chars": 2317,
    "preview": "// *** Core Script - DALL·E 2 Core ***\n\nasync function init() {\n  const chatConf = await invoke('get_app_conf') || {};\n "
  },
  {
    "path": "ChatGPT/src-tauri/src/utils.rs",
    "chars": 7767,
    "preview": "use anyhow::Result;\nuse log::{error, info};\nuse regex::Regex;\nuse serde_json::Value;\nuse std::{\n  collections::HashMap,\n"
  },
  {
    "path": "ChatGPT/src-tauri/src/vendors/floating-ui-core.js",
    "chars": 11339,
    "preview": "!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?e(exports):\"function\"==typeof define&&define.amd?def"
  },
  {
    "path": "ChatGPT/src-tauri/src/vendors/floating-ui-dom.js",
    "chars": 8556,
    "preview": "!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?e(exports,require(\"@floating-ui/core\")):\"function\"=="
  },
  {
    "path": "ChatGPT/src-tauri/src/vendors/html2canvas.js",
    "chars": 197783,
    "preview": "/*!\n * html2canvas 1.4.1 <https://html2canvas.hertzen.com>\n * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com"
  },
  {
    "path": "ChatGPT/src-tauri/src/vendors/jspdf.js",
    "chars": 364671,
    "preview": "/** @license\n *\n * jsPDF - PDF Document creation from JavaScript\n * Version 2.5.1 Built on 2022-01-28T15:37:57.789Z\n *  "
  },
  {
    "path": "ChatGPT/src-tauri/src/vendors/turndown-plugin-gfm.js",
    "chars": 4471,
    "preview": "var turndownPluginGfm = (function (exports) {\n  'use strict';\n\n  var highlightRegExp = /highlight-(?:text|source)-([a-z0"
  },
  {
    "path": "ChatGPT/src-tauri/src/vendors/turndown.js",
    "chars": 10471,
    "preview": "var TurndownService=function(){\"use strict\";function u(e,n){return Array(n+1).join(e)}var n=[\"ADDRESS\",\"ARTICLE\",\"ASIDE\""
  },
  {
    "path": "ChatGPT/src-tauri/tauri.conf.json",
    "chars": 2299,
    "preview": "{\n  \"build\": {\n    \"beforeDevCommand\": \"npm run dev:fe\",\n    \"beforeBuildCommand\": \"npm run build:fe\",\n    \"devPath\": \"h"
  },
  {
    "path": "ChatGPT/tsconfig.json",
    "chars": 734,
    "preview": "{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"DOM\", \"DOM.Iterable\","
  },
  {
    "path": "ChatGPT/tsconfig.node.json",
    "chars": 184,
    "preview": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"allowSynthe"
  },
  {
    "path": "ChatGPT/vite.config.ts",
    "chars": 1493,
    "preview": "import { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport tsconfigPaths from 'vite-tsconfig-"
  },
  {
    "path": "LICENSE",
    "chars": 1067,
    "preview": "MIT License\n\nCopyright (c) 2023 NsLearning\n\nPermission is hereby granted, free of charge, to any person obtaining a copy"
  },
  {
    "path": "LangHelper/Assess/IflytekAssessment.py",
    "chars": 8584,
    "preview": "# -*- coding:utf-8 -*-\n\nfrom builtins import Exception, str, bytes\n\nimport websocket\nimport datetime\nimport hashlib\nimpo"
  },
  {
    "path": "LangHelper/Assess/SpeechSuper.py",
    "chars": 4823,
    "preview": "#_*_encoding:utf-8_*_\nimport time\nimport json\nimport asyncio\nimport hashlib\nimport websockets\n\n#In order to try it out f"
  },
  {
    "path": "LangHelper/Assess/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "LangHelper/Recognition/IflytekRec.py",
    "chars": 4703,
    "preview": "\nimport hmac\nimport base64\nimport websocket\nimport hashlib\nimport json, time, threading,os\nfrom urllib.parse import quot"
  },
  {
    "path": "LangHelper/Recognition/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "LangHelper/Resource/cn/read_sentence_cn.txt",
    "chars": 7,
    "preview": "今天天气怎么样"
  },
  {
    "path": "LangHelper/Resource/cn/read_syllable_cn.txt",
    "chars": 1,
    "preview": "好"
  },
  {
    "path": "LangHelper/Resource/en/oral_translation_en.txt",
    "chars": 5539,
    "preview": "[topic]\n1. British People\n1.1.  British people usually say \"\"hello\"\" or \"\"nice to meet you\"\" and shake your hand when th"
  },
  {
    "path": "LangHelper/Resource/en/picture_talk_en.txt",
    "chars": 11642,
    "preview": "[topic]\n1. Throw Litter\n1.1. Mary and her classmates went outing last weekend. Someone was flying kites, some people wer"
  },
  {
    "path": "LangHelper/Resource/en/read_choice_en.txt",
    "chars": 96,
    "preview": "[choice]\n1. Snakes.\n2. Children.\n3. Cats.\n[keywords]\ncats\n[question]\nWhat did the woman dislike?"
  },
  {
    "path": "LangHelper/Resource/en/read_sentence_en.txt",
    "chars": 50,
    "preview": "[content]\nthere was a gentleman live near my house"
  },
  {
    "path": "LangHelper/Resource/en/read_word_en.txt",
    "chars": 12,
    "preview": "[word]\nhouse"
  },
  {
    "path": "LangHelper/Resource/en/retell_en.txt",
    "chars": 3321,
    "preview": "[topic]\n1. The Goose Thief\n1.1.  Tom went to primary school in the countryside. Near his classroom, there was a small po"
  },
  {
    "path": "LangHelper/Resource/en/topic_en.txt",
    "chars": 3322,
    "preview": "[topic]\n1. The Goose Thief\n1.1.  Tom went to primary school in the countryside. Near his classroom, there was a small po"
  },
  {
    "path": "LangHelper/Resource/speaker-info.txt",
    "chars": 4028,
    "preview": "ID  AGE  GENDER  ACCENTS  REGION COMMENTS \np225  23  F    English    Southern  England\np226  22  M    English    Surrey\n"
  },
  {
    "path": "LangHelper/Resource/tts_models--en--vctk--vits/config.json",
    "chars": 11927,
    "preview": "{\n    \"output_path\": null,\n    \"logger_uri\": null,\n    \"run_name\": \"\",\n    \"project_name\": null,\n    \"run_description\": "
  },
  {
    "path": "LangHelper/Resource/tts_models--en--vctk--vits/speaker_ids.json",
    "chars": 1745,
    "preview": "{\n    \"ED\\n\": 0,\n    \"p225\": 1,\n    \"p226\": 2,\n    \"p227\": 3,\n    \"p228\": 4,\n    \"p229\": 5,\n    \"p230\": 6,\n    \"p231\": 7"
  },
  {
    "path": "LangHelper/main.py",
    "chars": 13909,
    "preview": "# -*- encoding:utf-8 -*-\nimport Assess.SpeechSuper,Assess.IflytekAssessment\nimport Recognition.IflytekRec\nimport recoder"
  },
  {
    "path": "LangHelper/recoder.py",
    "chars": 1771,
    "preview": "import pyaudio\nimport os\nimport wave\n\nclass VoiceRecorder:\n    def __init__(self, root_path):\n\n        self.root_path = "
  },
  {
    "path": "README.md",
    "chars": 3581,
    "preview": "\n\n## ✨ Features / 功能\n1. talk to ChatGPT / 口语对话\n\n    - support different speech types, web, AI with hundreds accents (VCT"
  }
]

// ... and 11 more files (download for full content)

About this extraction

This page contains the full source code of the NsLearning/LangHelper GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 128 files (958.2 KB), approximately 346.3k tokens, and a symbol index with 466 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!