新增 XSLPrintDot 项目,包含打印服务的核心功能和相关配置。实现打印机查询、打印任务处理、远程转发功能,并支持多平台设备ID获取。优化打印数据准备逻辑,增强系统的可维护性和扩展性,同时更新工作区配置以支持新项目。

This commit is contained in:
geht
2026-05-14 12:04:18 +08:00
parent 296bc2a4b2
commit 687b9bebed
65 changed files with 9080 additions and 1 deletions

View File

@@ -0,0 +1,154 @@
name: release
on:
push:
tags:
- "v*"
permissions:
contents: write
jobs:
build:
name: build-${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- os: windows-latest
platform: windows/amd64
package: windows
- os: macos-latest
platform: darwin/universal
package: macos-universal
- os: ubuntu-22.04
platform: linux/amd64
package: linux
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: "1.22.x"
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: "20.x"
cache: "npm"
cache-dependency-path: frontend/package-lock.json
- name: Install Wails
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
- name: Install Linux build dependencies
if: matrix.os == 'ubuntu-22.04'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev pkg-config
- name: Build
if: matrix.os != 'windows-latest'
run: wails build -clean -platform ${{ matrix.platform }}
- name: Build (Windows installer)
if: matrix.os == 'windows-latest'
shell: pwsh
run: |
choco install nsis -y
$env:Path = "C:\Program Files (x86)\NSIS;" + $env:Path
if (-not (Get-Command makensis -ErrorAction SilentlyContinue)) {
Write-Error "makensis not found after NSIS install"
}
wails build -clean -nsis -platform windows/amd64
- name: Package (Windows)
if: matrix.os == 'windows-latest'
shell: pwsh
run: |
Write-Host "Listing build/bin contents:"
Get-ChildItem -Path build/bin -Recurse | Select-Object FullName | Format-Table -AutoSize
$installer = Get-ChildItem -Path build/bin -Recurse -File -Filter "*.exe" |
Where-Object { $_.Name -match "installer|setup" } |
Select-Object -First 1
if (-not $installer) {
$installer = Get-ChildItem -Path build/bin -Recurse -File -Filter "*.msi" | Select-Object -First 1
}
if (-not $installer) {
Write-Error "No Windows installer found in build/bin"
}
$renamed = Join-Path $installer.DirectoryName "XSL-PrintDot-setup-windows.exe"
Copy-Item -Path $installer.FullName -Destination $renamed -Force
Compress-Archive -Path $renamed -DestinationPath build/XSL-PrintDot-windows.zip
- name: Package (macOS)
if: matrix.os == 'macos-latest'
run: |
APP_PATH=$(find build/bin -maxdepth 2 -type d -name "*.app" | head -n 1)
if [ -z "$APP_PATH" ]; then
echo "No .app found in build/bin" >&2
exit 1
fi
if [ ! -d "$APP_PATH/Contents" ]; then
echo "Invalid .app bundle: $APP_PATH" >&2
exit 1
fi
echo "Packaging $APP_PATH"
APP_NAME=$(basename "$APP_PATH" .app)
BIN_PATH="$APP_PATH/Contents/MacOS/$APP_NAME"
if [ ! -f "$BIN_PATH" ]; then
echo "Binary not found: $BIN_PATH" >&2
exit 1
fi
ARM_APP="build/bin/${APP_NAME}-arm64.app"
AMD_APP="build/bin/${APP_NAME}-amd64.app"
rm -rf "$ARM_APP" "$AMD_APP"
cp -R "$APP_PATH" "$ARM_APP"
cp -R "$APP_PATH" "$AMD_APP"
lipo -thin arm64 "$BIN_PATH" -output "$ARM_APP/Contents/MacOS/$APP_NAME"
lipo -thin x86_64 "$BIN_PATH" -output "$AMD_APP/Contents/MacOS/$APP_NAME"
ditto -c -k --sequesterRsrc --keepParent "$ARM_APP" build/XSL-PrintDot-macos-arm64.zip
ditto -c -k --sequesterRsrc --keepParent "$AMD_APP" build/XSL-PrintDot-macos-amd64.zip
- name: Package (Linux)
if: matrix.os == 'ubuntu-22.04'
run: |
if [ ! -d "build/bin" ]; then
echo "build/bin not found" >&2
exit 1
fi
tar -czf build/XSL-PrintDot-linux.tar.gz -C build/bin .
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: XSL-PrintDot-${{ matrix.os }}
path: build/XSL-PrintDot-*
release:
name: create-release
runs-on: ubuntu-latest
needs: build
steps:
- name: Download Artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
- name: Publish Release
uses: softprops/action-gh-release@v2
with:
files: artifacts/**/*

13
XSLPrintDot/.gitignore vendored Normal file
View File

@@ -0,0 +1,13 @@
build/bin
node_modules
frontend/dist
frontend/components.d.ts
frontend/wailsjs/
# Build-time artifacts
build/windows/installer/resources/*.zip
build/windows/installer/resources/sumatra_tmp/
build/windows/installer/tmp/
build/windows/installer/wails_tools.nsh
frontend/package.json.md5

649
XSLPrintDot/LICENSE Normal file
View File

@@ -0,0 +1,649 @@
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, that 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 License 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/>.

120
XSLPrintDot/README.md Normal file
View File

@@ -0,0 +1,120 @@
<div align="center">
# PrintDot Client
**中文** | [English](README_EN.md)
<img src="build/appicon.png" alt="PrintDot Client Logo" width="96" />
</div>
## 简介
PrintDot Client 是一款基于 Wails 与 Vue 的桌面打印助手,主打“稳定、快速、好上手”。它将设备发现、连接管理与转发能力打包到一个轻量客户端里,让你用更少的配置成本,获得更高的打印链路稳定性与可用性。本项目是 [Vue Print Designer](https://github.com/0ldFive/Vue-Print-Designer) 的配套客户端。
## 界面预览
<table>
<tr>
<td align="center">
<img src="docs/images/1.png" width="300" alt="主界面" /><br />
<em>主界面 - 设备状态与连接管理</em>
</td>
<td align="center">
<img src="docs/images/2.png" width="300" alt="设置页面" /><br />
<em>设置页面 - 偏好与配置选项</em>
</td>
</tr>
</table>
## 优势
- 秒级启动与响应,日常操作几乎零等待
- 稳定可靠的发现与转发链路,长时间运行也很安心
- 跨平台一致体验,减少环境差异带来的折腾
- 轻量架构、低资源占用,老机器也能顺滑跑
- 细节打磨的设置与多语言体验,新手上手更快
- 现代化界面与清晰信息层级,关键状态一眼可见
## 支持平台
- Windows
- macOS
- Linux
## 功能概览
- 自动发现与识别本地/网络设备
- 稳定的连接维护与转发队列
- 简洁的可视化状态与告警提示
- 多语言界面与基础偏好设置
- 适合长期后台运行的轻量模式
## 架构与模块
- 前端Vue 3 + Vite + Tailwind负责界面与交互
- 桌面容器Wails提供跨平台窗口与系统能力
- 后端Go 服务层,负责发现、连接、转发与配置
## 安装与运行
### 开发模式
1. 安装 Wails 与 Node.js 依赖
2. 运行开发命令
```bash
wails dev
```
### 生产构建
```bash
wails build
```
#### Windows
```bash
wails build -clean -nsis
```
#### macOS
```bash
wails build -clean -platform darwin/amd64
wails build -clean -platform darwin/arm64
```
#### Linux
```bash
wails build -clean -platform linux/amd64
```
## 配置说明
- 配置文件由应用自动生成并维护
- 可在设置页中调整设备与转发相关选项
- 修改配置后即时生效,无需重启
## 常见问题
**Q: 设备没有出现或连接不稳定怎么办?**
- 请检查同一网络与防火墙放行
- 重启客户端后重新发现
- 若仍异常,请参考使用手册排查
**Q: 是否支持后台常驻?**
- 支持,应用优化了低资源占用与持续转发
## 贡献与开发
- 欢迎提交 Issue 与 Pull Request
- 建议先阅读使用手册与配置说明,保持一致的行为与体验
## 使用手册
- 中文: [docs/usage_guide_zh.md](docs/usage_guide_zh.md)
- English: [docs/usage_guide_en.md](docs/usage_guide_en.md)

121
XSLPrintDot/README_EN.md Normal file
View File

@@ -0,0 +1,121 @@
<div align="center">
# PrintDot Client
[中文](README.md) | **English**
<img src="build/appicon.png" alt="PrintDot Client Logo" width="96" />
</div>
## Introduction
PrintDot Client is a desktop printing assistant built with Wails and Vue, focusing on "stability, speed, and ease of use". It packages device discovery, connection management, and forwarding capabilities into a lightweight client, allowing you to achieve higher printing stability and availability with less configuration effort. This project is the companion client for [Vue Print Designer](https://github.com/0ldFive/Vue-Print-Designer).
## Screenshots
<table>
<tr>
<td align="center">
<img src="docs/images/1.png" width="300" alt="Main Interface" /><br />
<em>Main Interface - Device Status & Connection Management</em>
</td>
<td align="center">
<img src="docs/images/2.png" width="300" alt="Settings Page" /><br />
<em>Settings Page - Preferences & Configuration</em>
</td>
</tr>
</table>
## Advantages
- Instant startup and response, virtually zero wait for daily operations
- Stable and reliable discovery and forwarding, worry-free for long-term running
- Consistent cross-platform experience, less hassle from environment differences
- Lightweight architecture with low resource usage, runs smoothly even on older machines
- Polished settings and multilingual experience, easier for beginners
- Modern interface with clear information hierarchy, key status visible at a glance
## Supported Platforms
- Windows
- macOS
- Linux
## Features
- Auto-discovery and identification of local/network devices
- Stable connection maintenance and forwarding queue
- Clean visual status and alert notifications
- Multilingual interface and basic preferences
- Lightweight mode suitable for long-term background running
## Architecture & Modules
- Frontend: Vue 3 + Vite + Tailwind for UI and interactions
- Desktop Container: Wails for cross-platform windowing and system capabilities
- Backend: Go service layer for discovery, connection, forwarding, and configuration
## Installation & Usage
### Development Mode
1. Install Wails and Node.js dependencies
2. Run the development command
```bash
wails dev
```
### Production Build
```bash
wails build
```
#### Windows
```bash
wails build -clean -nsis
```
#### macOS
```bash
wails build -clean -platform darwin/amd64
wails build -clean -platform darwin/arm64
```
#### Linux
```bash
wails build -clean -platform linux/amd64
```
## Configuration
- Configuration files are automatically generated and maintained by the application
- Device and forwarding options can be adjusted in the settings page
- Changes take effect immediately without restart
## FAQ
**Q: What if the device doesn't appear or the connection is unstable?**
- Check if devices are on the same network and firewall is properly configured
- Restart the client and rediscover
- If issues persist, refer to the user manual for troubleshooting
**Q: Does it support running in background?**
- Yes, the application is optimized for low resource usage and continuous forwarding
## Contributing
- Issues and Pull Requests are welcome
- Please read the user manual and configuration guide first to maintain consistent behavior and experience
## User Manual
- 中文: [docs/usage_guide_zh.md](docs/usage_guide_zh.md)
- English: [docs/usage_guide_en.md](docs/usage_guide_en.md)

280
XSLPrintDot/app.go Normal file
View File

@@ -0,0 +1,280 @@
package main
import (
"context"
"embed"
"fmt"
"os"
"os/exec"
"strconv"
"sync"
"github.com/wailsapp/wails/v2/pkg/menu"
"github.com/wailsapp/wails/v2/pkg/menu/keys"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
//go:embed docs
var usageGuides embed.FS
// App struct
type App struct {
ctx context.Context
AppMode string
LogPort int
bridge *Bridge
settings *SettingsManager
isQuitting bool
logsMu sync.Mutex
settingsCmd *exec.Cmd
logsCmd *exec.Cmd
helpCmd *exec.Cmd
}
// NewApp creates a new App application struct
func NewApp(mode string, logPort int) *App {
return &App{
AppMode: mode,
LogPort: logPort,
bridge: NewBridge(),
settings: NewSettingsManager(),
}
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
// Bind logger
a.bridge.SetLogger(func(msg string) {
runtime.EventsEmit(ctx, "log", msg)
})
// Bind client count
a.bridge.SetCountCallback(func(count int) {
runtime.EventsEmit(ctx, "client_count", count)
})
// Bind reload callback
a.bridge.SetReloadCallback(func() {
a.Reload()
})
a.bridge.SetForwarderStatusProvider(func() RemoteForwarderStatus {
status := a.bridge.GetRemoteForwarderStatus()
status.AutoReconnect = a.settings.Get().RemoteAutoConnect
return status
})
a.bridge.SetForwarderConnectHandler(func() {
a.bridge.StartRemoteForwarderWithSettings(a.settings.Get(), true)
})
a.bridge.SetForwarderDisconnectHandler(func() {
a.bridge.StopRemoteForwarder()
})
// Bind client connect
a.bridge.SetClientConnectCallback(func(clientInfo string) {
runtime.EventsEmit(ctx, "client_connected", clientInfo)
})
if a.AppMode == "main" {
// Start Log Server
if err := a.bridge.StartLogServer(); err != nil {
fmt.Printf("Failed to start log server: %v\n", err)
} else {
a.LogPort = a.bridge.logPort
a.bridge.Log(fmt.Sprintf("Log server started on port %d", a.LogPort))
}
a.bridge.ConfigureRemoteForwarder(a.settings.Get())
}
}
func (a *App) domReady(ctx context.Context) {
// Add any dom ready logic
}
func (a *App) beforeClose(ctx context.Context) (prevent bool) {
return false
}
func (a *App) shutdown(ctx context.Context) {
a.Cleanup()
}
func (a *App) Cleanup() {
if a.AppMode == "main" {
a.bridge.StopServer()
a.bridge.StopLogServer()
a.bridge.StopRemoteForwarder()
// Kill child windows
if a.settingsCmd != nil && a.settingsCmd.Process != nil {
a.settingsCmd.Process.Kill()
}
if a.logsCmd != nil && a.logsCmd.Process != nil {
a.logsCmd.Process.Kill()
}
if a.helpCmd != nil && a.helpCmd.Process != nil {
a.helpCmd.Process.Kill()
}
}
}
func (a *App) Quit() {
a.isQuitting = true
if a.ctx != nil {
runtime.Quit(a.ctx)
} else {
os.Exit(0)
}
}
// Wails Methods
func (a *App) GetUsageGuide() string {
lang := a.settings.Get().Language
filename := "docs/usage_guide_en.md"
if lang == "zh-CN" {
filename = "docs/usage_guide_zh.md"
}
content, err := usageGuides.ReadFile(filename)
if err != nil {
return "# Error\n\nFailed to load usage guide: " + err.Error()
}
return string(content)
}
func (a *App) GetSettings() AppSettings {
return a.settings.Get()
}
func (a *App) SaveSettings(s AppSettings) error {
return a.settings.Save(s)
}
func (a *App) GetPrinters() ([]PrinterInfo, error) {
return a.bridge.GetPrinters()
}
// PrintCurrentView uses the CDP hack to silent print the current WebView content
func (a *App) StartServer(port, key string) error {
return a.bridge.StartServer(port, key)
}
func (a *App) StopServer() error {
return a.bridge.StopServer()
}
func (a *App) GetAppMode() string {
return a.AppMode
}
func (a *App) Restart() {
runtime.Quit(a.ctx)
}
func (a *App) ShowHelp() {
a.logsMu.Lock()
defer a.logsMu.Unlock()
a.spawnWindow("help", &a.helpCmd)
}
func (a *App) ShowLogs() {
a.logsMu.Lock()
defer a.logsMu.Unlock()
a.spawnWindow("logs", &a.logsCmd)
}
func (a *App) ShowSettings() {
a.logsMu.Lock()
defer a.logsMu.Unlock()
a.spawnWindow("settings", &a.settingsCmd)
}
func (a *App) spawnWindow(mode string, cmdStore **exec.Cmd) {
exe, err := os.Executable()
if err != nil {
a.bridge.Log(fmt.Sprintf("Failed to get executable: %v", err))
return
}
cmd := exec.Command(exe, mode, strconv.Itoa(a.LogPort))
cmd.Start()
*cmdStore = cmd
}
func (a *App) GetLogPort() int {
return a.LogPort
}
func (a *App) GetRemoteForwarderStatus() RemoteForwarderStatus {
return a.bridge.GetRemoteForwarderStatus()
}
func (a *App) DisconnectRemoteForwarder() {
a.bridge.StopRemoteForwarder()
}
func (a *App) ConnectRemoteForwarder() {
a.bridge.StartRemoteForwarderWithSettings(a.settings.Get(), true)
}
func (a *App) CreateMenu(lang string) *menu.Menu {
// Ensure locales are loaded
LoadLocales(lang)
appMenu := menu.NewMenu()
// Main App Configuration
menuTitle := T("menu.title")
settingsTitle := T("menu.settings")
logsTitle := T("menu.logs")
helpTitle := T("menu.help")
quitTitle := T("menu.quit")
// Menu (菜单)
MenuMenu := appMenu.AddSubmenu(menuTitle)
MenuMenu.AddText(logsTitle, keys.CmdOrCtrl("l"), func(_ *menu.CallbackData) {
a.ShowLogs()
})
MenuMenu.AddSeparator()
MenuMenu.AddText(quitTitle, keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) {
a.Quit()
})
// Help (帮助)
HelpMenu := appMenu.AddSubmenu(helpTitle)
HelpMenu.AddText(helpTitle, keys.CmdOrCtrl("h"), func(_ *menu.CallbackData) {
a.ShowHelp()
})
// Settings (设置)
SettingsMenu := appMenu.AddSubmenu(settingsTitle)
SettingsMenu.AddText(settingsTitle, keys.CmdOrCtrl("i"), func(_ *menu.CallbackData) {
a.ShowSettings()
})
return appMenu
}
func (a *App) UpdateUI(lang string) {
if a.ctx != nil && a.AppMode == "main" {
runtime.MenuSetApplicationMenu(a.ctx, a.CreateMenu(lang))
// Emit event for frontend updates
runtime.EventsEmit(a.ctx, "reload_settings")
}
}
func (a *App) Reload() {
// Reload settings from disk
a.settings.Load()
// Reload locale
LoadLocales(a.settings.Get().Language)
// Update menu and UI
a.UpdateUI(a.settings.Get().Language)
a.bridge.ConfigureRemoteForwarder(a.settings.Get())
a.bridge.Log("Settings reloaded")
}

View File

@@ -0,0 +1,7 @@
//go:build !windows
package main
func setAutoStart(enabled bool) {
_ = enabled
}

View File

@@ -0,0 +1,27 @@
//go:build windows
package main
import (
"os"
"os/exec"
"syscall"
)
func setAutoStart(enabled bool) {
exe, err := os.Executable()
if err != nil {
return
}
if enabled {
cmd := exec.Command("reg", "add", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", "/v", "PrintDotClient", "/t", "REG_SZ", "/d", exe, "/f")
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
_ = cmd.Run()
return
}
cmd := exec.Command("reg", "delete", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", "/v", "PrintDotClient", "/f")
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
_ = cmd.Run()
}

950
XSLPrintDot/backend.go Normal file
View File

@@ -0,0 +1,950 @@
package main
import (
"bufio"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"math"
"net"
"net/http"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
)
type Bridge struct {
server *http.Server
port string
key string
mu sync.Mutex
log func(string) // Callback to log to frontend
// Log related
logFileMu sync.Mutex
logServer *http.Server
logPort int
// Connection tracking
clientCount int
countMu sync.Mutex
onCountChange func(int) // Callback to update frontend
conns map[*websocket.Conn]bool
// Restart callback
onRestart func()
onReload func()
onClientConnect func(string)
// Remote forwarding
remoteMu sync.Mutex
remoteStop chan struct{}
remoteWg sync.WaitGroup
remoteCfg RemoteConfig
remoteConn *websocket.Conn
remoteStatus RemoteForwarderStatus
forwarderStatusProvider func() RemoteForwarderStatus
forwarderConnect func()
forwarderDisconnect func()
}
func NewBridge() *Bridge {
b := &Bridge{
port: "1122",
key: "",
conns: make(map[*websocket.Conn]bool),
}
b.ensureLogDir()
return b
}
func (b *Bridge) SetLogger(logger func(string)) {
b.log = logger
}
func (b *Bridge) SetCountCallback(cb func(int)) {
b.onCountChange = cb
}
func (b *Bridge) SetRestartCallback(cb func()) {
b.onRestart = cb
}
func (b *Bridge) SetReloadCallback(cb func()) {
b.onReload = cb
}
func (b *Bridge) SetClientConnectCallback(cb func(string)) {
b.onClientConnect = cb
}
func (b *Bridge) SetForwarderStatusProvider(cb func() RemoteForwarderStatus) {
b.forwarderStatusProvider = cb
}
func (b *Bridge) SetForwarderConnectHandler(cb func()) {
b.forwarderConnect = cb
}
func (b *Bridge) SetForwarderDisconnectHandler(cb func()) {
b.forwarderDisconnect = cb
}
func (b *Bridge) updateClientCount(delta int) {
b.countMu.Lock()
b.clientCount += delta
count := b.clientCount
b.countMu.Unlock()
if b.onCountChange != nil {
b.onCountChange(count)
}
}
func (b *Bridge) Log(msg string) {
timestamp := time.Now().Format("15:04:05")
entry := fmt.Sprintf("[%s] %s", timestamp, msg)
if err := b.appendLogLine(entry); err != nil {
log.Println(entry)
} else if b.log != nil {
b.log(msg)
}
}
func (b *Bridge) GetPrinters() ([]PrinterInfo, error) {
return b.getPrintersPlatform()
}
type PrinterInfo struct {
Name string `json:"name"`
IsDefault bool `json:"isDefault"`
}
func (b *Bridge) GetPrinterCapabilities(printerName string) (map[string]interface{}, error) {
return b.getPrinterCapabilitiesPlatform(printerName)
}
func (b *Bridge) StartServer(port string, key string) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.server != nil {
return fmt.Errorf("server already running")
}
b.port = port
b.key = key
mux := http.NewServeMux()
mux.HandleFunc("/ws", b.handleWebSocket)
b.server = &http.Server{
Addr: ":" + port,
Handler: mux,
}
go func() {
b.Log(fmt.Sprintf("Starting server on port %s...", port))
if err := b.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
b.Log(fmt.Sprintf("Server error: %v", err))
}
b.Log("Server stopped")
}()
return nil
}
func (b *Bridge) StopServer() error {
b.mu.Lock()
defer b.mu.Unlock()
if b.server == nil {
return nil
}
// Close all active connections first
b.countMu.Lock()
for conn := range b.conns {
conn.Close()
}
// Clear the map
b.conns = make(map[*websocket.Conn]bool)
b.countMu.Unlock()
if err := b.server.Shutdown(context.Background()); err != nil {
return err
}
b.server = nil
return nil
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // Allow all origins
},
}
type PrintRequest struct {
Printer string `json:"printer"`
Content string `json:"content"` // Base64 encoded PDF
Key string `json:"key"`
Job struct {
Name string `json:"name"`
Copies int `json:"copies"`
IntervalMs int `json:"intervalMs"`
} `json:"job"`
Pages struct {
Range string `json:"range"`
Set string `json:"set"`
} `json:"pages"`
Layout struct {
Scale string `json:"scale"`
Orientation string `json:"orientation"`
} `json:"layout"`
Color struct {
Mode string `json:"mode"`
} `json:"color"`
Sides struct {
Mode string `json:"mode"`
} `json:"sides"`
Paper PaperSpec `json:"paper"`
Tray struct {
Bin string `json:"bin"`
} `json:"tray"`
}
type PaperSpec struct {
Size string `json:"size"`
}
type PrintOptions struct {
PageRange string
PageSet string
Duplex string
ColorMode string
Paper string
Scale string
Orientation string
TrayBin string
Copies int
}
type Response struct {
Status string `json:"status"`
Message string `json:"message"`
}
func (b *Bridge) handleWebSocket(w http.ResponseWriter, r *http.Request) {
// Authentication check
if b.key != "" {
pass := r.URL.Query().Get("key")
if pass == "" {
pass = r.URL.Query().Get("password")
}
if pass != b.key {
b.Log(fmt.Sprintf("Authentication failed for %s", r.RemoteAddr))
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
b.Log(fmt.Sprintf("Upgrade error: %v", err))
return
}
defer c.Close()
b.countMu.Lock()
b.conns[c] = true
b.countMu.Unlock()
b.updateClientCount(1)
defer func() {
b.countMu.Lock()
delete(b.conns, c)
b.countMu.Unlock()
b.updateClientCount(-1)
}()
b.Log(fmt.Sprintf("Client connected from %s", c.RemoteAddr()))
if b.onClientConnect != nil {
b.onClientConnect(c.RemoteAddr().String())
}
// Send printer list immediately upon connection
printers, err := b.GetPrinters()
if err == nil {
msg := map[string]interface{}{
"type": "printer_list",
"data": printers,
}
if jsonBytes, err := json.Marshal(msg); err == nil {
b.Log(fmt.Sprintf("Sent WS message: %s", string(jsonBytes)))
}
c.WriteJSON(msg)
} else {
b.Log(fmt.Sprintf("Failed to get printers on connect: %v", err))
errMsg := fmt.Sprintf("Failed to get printer list: %v", err)
c.WriteJSON(Response{Status: "error", Message: errMsg})
}
for {
// Read message as raw JSON map first to check type
var rawMsg map[string]interface{}
err := c.ReadJSON(&rawMsg)
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
b.Log(fmt.Sprintf("Client disconnected: %v", err))
} else {
// Normal closure or other error
}
break
}
if jsonBytes, err := json.Marshal(rawMsg); err == nil {
b.Log(fmt.Sprintf("Received WS message: %s", string(jsonBytes)))
}
// Check message type
if msgType, ok := rawMsg["type"].(string); ok && msgType == "get_printers" {
printers, err := b.GetPrinters()
if err == nil {
msg := map[string]interface{}{
"type": "printer_list",
"data": printers,
}
if jsonBytes, err := json.Marshal(msg); err == nil {
b.Log(fmt.Sprintf("Sent WS message: %s", string(jsonBytes)))
}
c.WriteJSON(msg)
} else {
resp := Response{Status: "error", Message: fmt.Sprintf("Failed to get printer list: %v", err)}
if jsonBytes, err := json.Marshal(resp); err == nil {
b.Log(fmt.Sprintf("Sent WS message: %s", string(jsonBytes)))
}
c.WriteJSON(resp)
}
continue
}
if msgType, ok := rawMsg["type"].(string); ok && msgType == "get_printer_caps" {
printer, _ := rawMsg["printer"].(string)
printer = strings.TrimSpace(printer)
if printer == "" {
resp := Response{Status: "error", Message: "printer is required"}
c.WriteJSON(resp)
continue
}
caps, err := b.GetPrinterCapabilities(printer)
if err != nil {
b.Log(fmt.Sprintf("Failed to get printer capabilities for '%s': %v", printer, err))
resp := Response{Status: "error", Message: err.Error()}
c.WriteJSON(resp)
continue
}
msg := map[string]interface{}{
"type": "printer_caps",
"printer": printer,
"data": caps,
}
c.WriteJSON(msg)
continue
}
// Handle as PrintRequest (default)
jsonBody, _ := json.Marshal(rawMsg)
var req PrintRequest
if err := json.Unmarshal(jsonBody, &req); err != nil {
b.Log(fmt.Sprintf("Invalid print request: %v", err))
resp := Response{Status: "error", Message: "Invalid request format"}
c.WriteJSON(resp)
continue
}
msg, err := b.processPrintRequest(req)
if err == nil {
resp := Response{Status: "success", Message: msg}
c.WriteJSON(resp)
} else {
c.WriteJSON(Response{Status: "error", Message: msg})
}
}
}
func (b *Bridge) processPrintRequest(req PrintRequest) (string, error) {
jobName := strings.TrimSpace(req.Job.Name)
copies := req.Job.Copies
if copies <= 0 {
copies = 1
}
intervalMs := req.Job.IntervalMs
contentToDecode := req.Content
if strings.HasPrefix(contentToDecode, "data:") {
if idx := strings.Index(contentToDecode, ","); idx != -1 {
contentToDecode = contentToDecode[idx+1:]
}
}
decoded, err := base64.StdEncoding.DecodeString(contentToDecode)
if err != nil {
b.Log("Error decoding Base64 content")
return "Invalid Base64 content", fmt.Errorf("invalid base64 content")
}
if len(decoded) < 4 || string(decoded[0:4]) != "%PDF" {
b.Log("Content is not a valid PDF (missing %PDF header)")
return "Content must be a PDF file", fmt.Errorf("invalid pdf")
}
autoPaper := ""
if strings.TrimSpace(req.Paper.Size) == "" {
if name, ok := detectPaperFromPDF(decoded); ok {
autoPaper = name
b.Log(fmt.Sprintf("Auto paper size detected: %s", name))
}
}
options := PrintOptions{
PageRange: strings.TrimSpace(req.Pages.Range),
PageSet: strings.TrimSpace(req.Pages.Set),
Duplex: strings.TrimSpace(req.Sides.Mode),
ColorMode: strings.TrimSpace(req.Color.Mode),
Paper: strings.TrimSpace(firstNonEmpty(req.Paper.Size, autoPaper)),
Scale: strings.TrimSpace(req.Layout.Scale),
Orientation: strings.TrimSpace(req.Layout.Orientation),
TrayBin: strings.TrimSpace(req.Tray.Bin),
}
runCount := 1
perRunCopies := copies
if intervalMs > 0 {
runCount = copies
perRunCopies = 1
}
options.Copies = perRunCopies
successCount := 0
var lastErr error
for i := 0; i < runCount; i++ {
if i > 0 && intervalMs > 0 {
time.Sleep(time.Duration(intervalMs) * time.Millisecond)
}
err = b.printPDF(req.Printer, jobName, decoded, options)
if err != nil {
lastErr = err
b.Log(fmt.Sprintf("Print error (copy %d): %v", i+1, err))
break
} else {
successCount += perRunCopies
}
}
if successCount == copies {
b.Log("Print success")
return "Printed successfully", nil
}
msg := fmt.Sprintf("Printed %d/%d copies. Error: %v", successCount, copies, lastErr)
b.Log(msg)
return msg, fmt.Errorf("print failed")
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
var (
mediaBoxRegex = regexp.MustCompile(`/MediaBox\s*\[\s*([-0-9.]+)\s+([-0-9.]+)\s+([-0-9.]+)\s+([-0-9.]+)\s*\]`)
cropBoxRegex = regexp.MustCompile(`/CropBox\s*\[\s*([-0-9.]+)\s+([-0-9.]+)\s+([-0-9.]+)\s+([-0-9.]+)\s*\]`)
)
func detectPaperFromPDF(pdfData []byte) (string, bool) {
limit := len(pdfData)
if limit > 5*1024*1024 {
limit = 5 * 1024 * 1024
}
chunk := string(pdfData[:limit])
match := cropBoxRegex.FindStringSubmatch(chunk)
if len(match) != 5 {
match = mediaBoxRegex.FindStringSubmatch(chunk)
}
if len(match) != 5 {
return "", false
}
llx, err1 := strconv.ParseFloat(match[1], 64)
lly, err2 := strconv.ParseFloat(match[2], 64)
urx, err3 := strconv.ParseFloat(match[3], 64)
ury, err4 := strconv.ParseFloat(match[4], 64)
if err1 != nil || err2 != nil || err3 != nil || err4 != nil {
return "", false
}
widthPt := math.Abs(urx - llx)
heightPt := math.Abs(ury - lly)
return matchStandardPaper(widthPt, heightPt)
}
type paperSize struct {
Name string
Wmm float64
Hmm float64
}
func matchStandardPaper(widthPt, heightPt float64) (string, bool) {
mmPerPt := 25.4 / 72.0
widthMm := widthPt * mmPerPt
heightMm := heightPt * mmPerPt
if widthMm <= 0 || heightMm <= 0 {
return "", false
}
if widthMm > heightMm {
widthMm, heightMm = heightMm, widthMm
}
standard := []paperSize{
{Name: "A2", Wmm: 420, Hmm: 594},
{Name: "A3", Wmm: 297, Hmm: 420},
{Name: "A4", Wmm: 210, Hmm: 297},
{Name: "A5", Wmm: 148, Hmm: 210},
{Name: "A6", Wmm: 105, Hmm: 148},
{Name: "letter", Wmm: 216, Hmm: 279},
{Name: "legal", Wmm: 216, Hmm: 356},
{Name: "tabloid", Wmm: 279, Hmm: 432},
{Name: "statement", Wmm: 140, Hmm: 216},
}
const tolerance = 2.0
for _, size := range standard {
if math.Abs(widthMm-size.Wmm) <= tolerance && math.Abs(heightMm-size.Hmm) <= tolerance {
return size.Name, true
}
}
return "", false
}
func (b *Bridge) printPDF(printerName string, jobName string, pdfData []byte, options PrintOptions) error {
// 1. Write to temp file
tmpFile, err := ioutil.TempFile("", "print-dot-*.pdf")
if err != nil {
return fmt.Errorf("create temp file failed: %v", err)
}
defer os.Remove(tmpFile.Name()) // Clean up on exit
if _, err := tmpFile.Write(pdfData); err != nil {
tmpFile.Close()
return fmt.Errorf("write temp file failed: %v", err)
}
tmpFile.Close()
absPath, _ := filepath.Abs(tmpFile.Name())
if jobName != "" {
b.Log(fmt.Sprintf("Printing job '%s': %s to %s", jobName, absPath, printerName))
} else {
b.Log(fmt.Sprintf("Printing PDF file: %s to %s", absPath, printerName))
}
return b.printPDFPlatform(printerName, absPath, options)
}
func (b *Bridge) StartLogServer() error {
b.ensureLogDir()
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
return err
}
b.logPort = listener.Addr().(*net.TCPAddr).Port
mux := http.NewServeMux()
mux.HandleFunc("/logs", b.handleLogs)
mux.HandleFunc("/api/logs", b.handleLogsJSON)
mux.HandleFunc("/api/logs/clear", b.handleClearLogs)
mux.HandleFunc("/api/restart", b.handleRestartRequest)
mux.HandleFunc("/api/reload", b.handleReloadRequest)
mux.HandleFunc("/api/forwarder/status", b.handleForwarderStatus)
mux.HandleFunc("/api/forwarder/connect", b.handleForwarderConnect)
mux.HandleFunc("/api/forwarder/disconnect", b.handleForwarderDisconnect)
mux.HandleFunc("/api/forwarder/stream", b.handleForwarderStream)
b.logServer = &http.Server{
Handler: mux,
}
go func() {
if err := b.logServer.Serve(listener); err != nil && err != http.ErrServerClosed {
b.Log(fmt.Sprintf("Log server error: %v", err))
}
}()
return nil
}
func (b *Bridge) ensureLogDir() {
logDir, err := b.logDirPath()
if err != nil {
return
}
_ = os.MkdirAll(logDir, 0755)
path := filepath.Join(logDir, time.Now().Format("20060102")+".txt")
if f, err := os.OpenFile(path, os.O_CREATE, 0644); err == nil {
f.Close()
}
}
func (b *Bridge) StopLogServer() error {
if b.logServer == nil {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := b.logServer.Shutdown(ctx); err != nil {
_ = b.logServer.Close()
return err
}
b.logServer = nil
return nil
}
func (b *Bridge) handleLogs(w http.ResponseWriter, r *http.Request) {
currentLogs, _ := b.readLogLines()
html := `<!DOCTYPE html>
<html>
<head>
<title>System Logs - XSL-PrintDot Client</title>
<meta http-equiv="refresh" content="2">
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #ffffff;
color: #333;
padding: 20px;
margin: 0;
}
h2 { border-bottom: 2px solid #eee; padding-bottom: 10px; margin-top: 0; color: #444; }
.log-entry {
border-bottom: 1px solid #f0f0f0;
padding: 8px 0;
font-family: Consolas, 'Courier New', monospace;
font-size: 13px;
}
.log-entry:hover { background-color: #f9f9f9; }
.empty { color: #999; font-style: italic; padding: 20px 0; }
.status { font-size: 12px; color: #888; margin-top: 5px; }
</style>
</head>
<body>
<h2>System Logs</h2>
<div class="status">Auto-refreshing every 2 seconds</div>
<div id="logs">
{{range .}}
<div class="log-entry">{{.}}</div>
{{else}}
<div class="empty">No logs available.</div>
{{end}}
</div>
</body>
</html>`
t, err := template.New("logs").Parse(html)
if err != nil {
http.Error(w, "Template error", http.StatusInternalServerError)
return
}
t.Execute(w, currentLogs)
}
func (b *Bridge) handleLogsJSON(w http.ResponseWriter, r *http.Request) {
currentLogs, _ := b.readLogLines()
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*") // Allow child process to fetch
json.NewEncoder(w).Encode(currentLogs)
}
func (b *Bridge) handleClearLogs(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
b.clearLogFile()
w.WriteHeader(http.StatusOK)
}
func (b *Bridge) logFilePath() (string, error) {
logDir, err := b.logDirPath()
if err != nil {
return "", err
}
fileName := time.Now().Format("20060102") + ".txt"
return filepath.Join(logDir, fileName), nil
}
func (b *Bridge) logDirPath() (string, error) {
baseDir, err := dataDirPath()
if err != nil {
return "", err
}
return filepath.Join(baseDir, "logs"), nil
}
func dataDirPath() (string, error) {
if programData := strings.TrimSpace(os.Getenv("ProgramData")); programData != "" {
return filepath.Join(programData, "PrintDot"), nil
}
if runtime.GOOS == "darwin" {
if home, err := os.UserHomeDir(); err == nil {
return filepath.Join(home, "Library", "Application Support", "PrintDot"), nil
}
}
if runtime.GOOS == "linux" {
if dataHome := strings.TrimSpace(os.Getenv("XDG_DATA_HOME")); dataHome != "" {
return filepath.Join(dataHome, "PrintDot"), nil
}
if home, err := os.UserHomeDir(); err == nil {
return filepath.Join(home, ".local", "share", "PrintDot"), nil
}
}
if wd, err := os.Getwd(); err == nil {
return filepath.Join(wd, "PrintDot"), nil
}
return "", fmt.Errorf("failed to resolve data directory")
}
func (b *Bridge) appendLogLine(line string) error {
b.ensureLogDir()
path, err := b.logFilePath()
if err != nil {
return err
}
if !strings.HasSuffix(line, "\n") {
line += "\n"
}
b.logFileMu.Lock()
defer b.logFileMu.Unlock()
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(line)
return err
}
func (b *Bridge) readLogLines() ([]string, error) {
b.ensureLogDir()
path, err := b.logFilePath()
if err != nil {
return nil, err
}
b.logFileMu.Lock()
defer b.logFileMu.Unlock()
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
return []string{}, nil
}
return nil, err
}
defer f.Close()
lines := []string{}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
text := strings.TrimSpace(scanner.Text())
if text == "" {
continue
}
lines = append(lines, text)
}
if err := scanner.Err(); err != nil {
return lines, err
}
// Reverse logs for display (newest top)
for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 {
lines[i], lines[j] = lines[j], lines[i]
}
return lines, nil
}
func (b *Bridge) clearLogFile() {
path, err := b.logFilePath()
if err != nil {
return
}
b.logFileMu.Lock()
defer b.logFileMu.Unlock()
_ = os.Remove(path)
}
func (b *Bridge) handleReloadRequest(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Reload initiated"))
// Trigger reload on main thread
if b.onReload != nil {
go func() {
time.Sleep(100 * time.Millisecond)
b.onReload()
}()
}
}
func (b *Bridge) handleForwarderStatus(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
status := RemoteForwarderStatus{}
if b.forwarderStatusProvider != nil {
status = b.forwarderStatusProvider()
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(status)
}
func (b *Bridge) handleForwarderConnect(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if b.forwarderConnect != nil {
b.forwarderConnect()
}
w.WriteHeader(http.StatusOK)
}
func (b *Bridge) handleForwarderDisconnect(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if b.forwarderDisconnect != nil {
b.forwarderDisconnect()
}
w.WriteHeader(http.StatusOK)
}
func (b *Bridge) handleForwarderStream(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
status := RemoteForwarderStatus{}
if b.forwarderStatusProvider != nil {
status = b.forwarderStatusProvider()
}
if data, err := json.Marshal(status); err == nil {
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
}
last := status
ctx := r.Context()
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
current := RemoteForwarderStatus{}
if b.forwarderStatusProvider != nil {
current = b.forwarderStatusProvider()
}
if current != last {
if data, err := json.Marshal(current); err == nil {
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
last = current
}
}
}
}
}

View File

@@ -0,0 +1,24 @@
package main
import (
"net/http"
"time"
)
func (b *Bridge) handleRestartRequest(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Restart initiated"))
// Trigger restart on main thread
if b.onRestart != nil {
go func() {
time.Sleep(500 * time.Millisecond) // Give time for response to be sent
b.onRestart()
}()
}
}

157
XSLPrintDot/backend_unix.go Normal file
View File

@@ -0,0 +1,157 @@
//go:build !windows
package main
import (
"fmt"
"os/exec"
"strings"
)
func (b *Bridge) getPrintersPlatform() ([]PrinterInfo, error) {
defaultName := ""
if out, err := exec.Command("lpstat", "-d").Output(); err == nil {
line := strings.TrimSpace(string(out))
if idx := strings.LastIndex(line, ":"); idx >= 0 {
defaultName = strings.TrimSpace(line[idx+1:])
}
}
cmd := exec.Command("sh", "-c", "lpstat -a | cut -d ' ' -f 1")
output, err := cmd.Output()
if err != nil {
return nil, err
}
lines := strings.Split(string(output), "\n")
var printers []PrinterInfo
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if trimmed != "" {
printers = append(printers, PrinterInfo{Name: trimmed, IsDefault: trimmed == defaultName})
}
}
return printers, nil
}
func (b *Bridge) getPrinterCapabilitiesPlatform(printerName string) (map[string]interface{}, error) {
printerName = strings.TrimSpace(printerName)
if printerName == "" {
return nil, fmt.Errorf("printer name is empty")
}
cmd := exec.Command("lpoptions", "-p", printerName, "-l")
output, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("lpoptions error: %v, output: %s", err, string(output))
}
options := map[string]map[string]interface{}{}
lines := strings.Split(string(output), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
parts := strings.SplitN(line, ":", 2)
if len(parts) != 2 {
continue
}
left := strings.TrimSpace(parts[0])
right := strings.TrimSpace(parts[1])
optName := left
if idx := strings.Index(left, "/"); idx >= 0 {
optName = strings.TrimSpace(left[:idx])
}
values := []string{}
defaultValue := ""
for _, token := range strings.Fields(right) {
if strings.HasPrefix(token, "*") {
clean := strings.TrimPrefix(token, "*")
defaultValue = clean
values = append(values, clean)
continue
}
values = append(values, token)
}
options[optName] = map[string]interface{}{
"values": values,
"default": defaultValue,
"raw": right,
}
}
return map[string]interface{}{
"printer": printerName,
"options": options,
}, nil
}
func (b *Bridge) printPDFPlatform(printerName, filePath string, options PrintOptions) error {
args := []string{"-d", printerName}
if options.Copies > 1 {
args = append(args, "-n", fmt.Sprintf("%d", options.Copies))
}
if options.PageRange != "" {
args = append(args, "-P", options.PageRange)
}
switch strings.ToLower(strings.TrimSpace(options.PageSet)) {
case "even":
args = append(args, "-o", "page-set=even")
case "odd":
args = append(args, "-o", "page-set=odd")
}
switch strings.ToLower(strings.TrimSpace(options.Duplex)) {
case "long-edge", "long", "duplex", "duplexlong":
args = append(args, "-o", "sides=two-sided-long-edge")
case "short-edge", "short", "duplexshort":
args = append(args, "-o", "sides=two-sided-short-edge")
case "simplex", "one-sided":
args = append(args, "-o", "sides=one-sided")
}
switch strings.ToLower(strings.TrimSpace(options.ColorMode)) {
case "color":
args = append(args, "-o", "ColorModel=RGB")
case "mono", "monochrome", "grayscale", "gray":
args = append(args, "-o", "ColorModel=Gray")
}
if options.Paper != "" {
args = append(args, "-o", fmt.Sprintf("media=%s", options.Paper))
}
switch strings.ToLower(strings.TrimSpace(options.Scale)) {
case "noscale", "none", "actual":
args = append(args, "-o", "scaling=100")
case "shrink":
// Default CUPS behavior already shrinks to fit if needed
case "fit":
args = append(args, "-o", "fit-to-page")
}
switch strings.ToLower(strings.TrimSpace(options.Orientation)) {
case "portrait":
args = append(args, "-o", "orientation-requested=3")
case "landscape":
args = append(args, "-o", "orientation-requested=4")
}
if options.TrayBin != "" {
args = append(args, "-o", fmt.Sprintf("InputSlot=%s", options.TrayBin))
}
args = append(args, filePath)
cmd := exec.Command("lp", args...)
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("lp error: %v, output: %s", err, string(out))
}
return nil
}

View File

@@ -0,0 +1,498 @@
//go:build windows
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"time"
"unsafe"
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procMultiByteToWideChar = kernel32.NewProc("MultiByteToWideChar")
)
// ansiToUtf8 converts ANSI (CP_ACP) bytes to UTF-8 string
func ansiToUtf8(b []byte) (string, error) {
if len(b) == 0 {
return "", nil
}
// CP_ACP = 0
// 1. Get required length
ret, _, _ := procMultiByteToWideChar.Call(
0, // CP_ACP
0,
uintptr(unsafe.Pointer(&b[0])),
uintptr(len(b)),
0,
0,
)
if ret == 0 {
return "", fmt.Errorf("MultiByteToWideChar failed")
}
// 2. Allocate buffer
utf16buf := make([]uint16, ret)
// 3. Convert
ret, _, _ = procMultiByteToWideChar.Call(
0,
0,
uintptr(unsafe.Pointer(&b[0])),
uintptr(len(b)),
uintptr(unsafe.Pointer(&utf16buf[0])),
ret,
)
if ret == 0 {
return "", fmt.Errorf("MultiByteToWideChar failed")
}
return syscall.UTF16ToString(utf16buf), nil
}
// decodeCmdOutput handles WMIC encoding quirks (UTF-16LE BOM or ANSI)
func decodeCmdOutput(output []byte) (string, error) {
if len(output) >= 2 && output[0] == 0xFF && output[1] == 0xFE {
// UTF-16LE BOM detected
// Skip BOM
raw16 := output[2:]
// Make sure even number of bytes
if len(raw16)%2 != 0 {
raw16 = append(raw16, 0)
}
u16s := make([]uint16, len(raw16)/2)
for i := 0; i < len(u16s); i++ {
u16s[i] = uint16(raw16[i*2]) | uint16(raw16[i*2+1])<<8
}
return syscall.UTF16ToString(u16s), nil
}
// Assume ANSI (e.g. GBK on Chinese Windows)
return ansiToUtf8(output)
}
func (b *Bridge) getPrintersPlatform() ([]PrinterInfo, error) {
// Use WMIC to get printer names and default flags in CSV format
cmd := exec.Command("wmic", "printer", "get", "name,default", "/format:csv")
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
output, err := cmd.Output()
if err != nil {
return getPrintersViaPowerShell()
}
decodedStr, err := decodeCmdOutput(output)
if err != nil {
// Fallback
decodedStr = string(output)
}
reader := csv.NewReader(strings.NewReader(decodedStr))
reader.FieldsPerRecord = -1
reader.LazyQuotes = true
records, err := reader.ReadAll()
if err != nil {
return getPrintersViaPowerShell()
}
var printers []PrinterInfo
for _, record := range records {
if len(record) < 3 {
continue
}
if strings.EqualFold(record[1], "Default") && strings.EqualFold(record[2], "Name") {
continue
}
name := strings.TrimSpace(record[len(record)-1])
if name == "" {
continue
}
if strings.EqualFold(name, "Name") {
continue
}
isDefault := strings.EqualFold(strings.TrimSpace(record[1]), "TRUE")
printers = append(printers, PrinterInfo{Name: name, IsDefault: isDefault})
}
if len(printers) == 0 {
return getPrintersViaPowerShell()
}
return printers, nil
}
func getPrintersViaPowerShell() ([]PrinterInfo, error) {
ps := `Get-Printer | Select-Object Name,Default | ConvertTo-Json -Depth 3`
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", ps)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
output, err := cmd.Output()
if err != nil {
return nil, err
}
decoded, err := decodeCmdOutput(output)
if err != nil {
decoded = string(output)
}
var list []struct {
Name string `json:"Name"`
Default bool `json:"Default"`
}
if err := json.Unmarshal([]byte(decoded), &list); err == nil {
printers := make([]PrinterInfo, 0, len(list))
for _, item := range list {
name := strings.TrimSpace(item.Name)
if name == "" {
continue
}
printers = append(printers, PrinterInfo{Name: name, IsDefault: item.Default})
}
return printers, nil
}
var single struct {
Name string `json:"Name"`
Default bool `json:"Default"`
}
if err := json.Unmarshal([]byte(decoded), &single); err != nil {
return nil, err
}
name := strings.TrimSpace(single.Name)
if name == "" {
return nil, fmt.Errorf("no printers found")
}
return []PrinterInfo{{Name: name, IsDefault: single.Default}}, nil
}
func (b *Bridge) getPrinterCapabilitiesPlatform(printerName string) (map[string]interface{}, error) {
printerName = strings.TrimSpace(printerName)
if printerName == "" {
return nil, fmt.Errorf("printer name is empty")
}
escaped := strings.ReplaceAll(printerName, "'", "''")
ps := fmt.Sprintf(`$p = Get-CimInstance Win32_Printer -Filter "Name='%s'"; `+
`$c = Get-CimInstance Win32_PrinterConfiguration -Filter "Name='%s'"; `+
`if ($null -eq $p) { throw "Printer not found" }; `+
`[pscustomobject]@{ `+
`name = $p.Name; `+
`defaultPaperSize = $p.DefaultPaperSize; `+
`printerPaperNames = $p.PrinterPaperNames; `+
`paperSizes = $p.PaperSizes; `+
`colorSupported = $p.ColorSupported; `+
`duplexSupported = $p.DuplexSupported; `+
`driverName = $p.DriverName; `+
`portName = $p.PortName; `+
`printProcessor = $p.PrintProcessor; `+
`deviceId = $p.DeviceID; `+
`config = @{ `+
`paperSize = $c.PaperSize; `+
`orientation = $c.Orientation; `+
`color = $c.Color; `+
`duplex = $c.Duplex; `+
`copies = $c.Copies `+
`} `+
`} | ConvertTo-Json -Depth 4`, escaped, escaped)
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", ps)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
output, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("get printer capabilities failed: %v", err)
}
decoded, err := decodeCmdOutput(output)
if err != nil {
decoded = string(output)
}
var caps map[string]interface{}
if err := json.Unmarshal([]byte(decoded), &caps); err != nil {
return nil, fmt.Errorf("parse printer capabilities failed: %v", err)
}
return caps, nil
}
func (b *Bridge) printPDFPlatform(printerName, filePath string, options PrintOptions) error {
sumatraPath, err := findSumatraPDF()
if err != nil {
return err
}
settings := buildSumatraPrintSettings(options)
args := []string{"-print-to", printerName}
if settings != "" {
args = append(args, "-print-settings", settings)
}
args = append(args, filePath)
cmd := exec.Command(sumatraPath, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
queueSnapshot, _ := getPrintJobIDs(printerName)
if err := cmd.Start(); err != nil {
return fmt.Errorf("sumatra print failed to start: %v", err)
}
cmdDone := make(chan error, 1)
go func() {
cmdDone <- cmd.Wait()
}()
if err := waitForWindowsPrintCompletion(printerName, queueSnapshot, cmdDone); err != nil {
return err
}
return nil
}
type windowsPrintJob struct {
Id int `json:"Id"`
JobStatus interface{} `json:"JobStatus"`
DocumentName string `json:"DocumentName"`
}
const (
printQueuePollInterval = 500 * time.Millisecond
printQueueAppearTimeout = 120 * time.Second
printQueueCompleteTimeout = 5 * time.Minute
)
func getPrintJobs(printerName string) ([]windowsPrintJob, error) {
printerName = strings.TrimSpace(printerName)
if printerName == "" {
return nil, fmt.Errorf("printer name is empty")
}
escaped := strings.ReplaceAll(printerName, "'", "''")
ps := fmt.Sprintf(`Get-PrintJob -PrinterName '%s' | Select-Object Id,JobStatus,DocumentName | ConvertTo-Json -Depth 3`, escaped)
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", ps)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
output, err := cmd.Output()
if err != nil {
return nil, err
}
decoded, err := decodeCmdOutput(output)
if err != nil {
decoded = string(output)
}
decoded = strings.TrimSpace(decoded)
if decoded == "" || decoded == "null" {
return nil, nil
}
var list []windowsPrintJob
if err := json.Unmarshal([]byte(decoded), &list); err == nil {
return list, nil
}
var single windowsPrintJob
if err := json.Unmarshal([]byte(decoded), &single); err != nil {
return nil, err
}
return []windowsPrintJob{single}, nil
}
func getPrintJobIDs(printerName string) (map[int]bool, error) {
jobs, err := getPrintJobs(printerName)
if err != nil {
return nil, err
}
ids := make(map[int]bool, len(jobs))
for _, job := range jobs {
if job.Id > 0 {
ids[job.Id] = true
}
}
return ids, nil
}
func waitForWindowsPrintCompletion(printerName string, existingIDs map[int]bool, cmdDone <-chan error) error {
appearDeadline := time.Now().Add(printQueueAppearTimeout)
completeDeadline := time.Now().Add(printQueueCompleteTimeout)
queued := false
jobID := 0
for {
select {
case err := <-cmdDone:
if err != nil && !queued {
return fmt.Errorf("sumatra print failed: %v", err)
}
default:
}
now := time.Now()
if !queued && now.After(appearDeadline) {
return fmt.Errorf("print job not queued within %s", printQueueAppearTimeout)
}
if queued && now.After(completeDeadline) {
return fmt.Errorf("print job not completed within %s", printQueueCompleteTimeout)
}
jobs, err := getPrintJobs(printerName)
if err == nil {
if !queued {
for _, job := range jobs {
if !existingIDs[job.Id] {
jobID = job.Id
queued = true
break
}
}
} else {
found := false
var statusList []string
for _, job := range jobs {
if job.Id == jobID {
found = true
statusList = normalizeJobStatus(job.JobStatus)
break
}
}
if !found {
return nil
}
if isWindowsJobFailed(statusList) {
return fmt.Errorf("print job failed: %s", strings.Join(statusList, ", "))
}
}
}
time.Sleep(printQueuePollInterval)
}
}
func normalizeJobStatus(status interface{}) []string {
switch v := status.(type) {
case string:
if strings.TrimSpace(v) == "" {
return nil
}
return []string{strings.TrimSpace(v)}
case []interface{}:
out := make([]string, 0, len(v))
for _, item := range v {
if s, ok := item.(string); ok {
if strings.TrimSpace(s) != "" {
out = append(out, strings.TrimSpace(s))
}
}
}
return out
default:
return nil
}
}
func isWindowsJobFailed(statuses []string) bool {
for _, status := range statuses {
value := strings.ToLower(status)
if strings.Contains(value, "error") || strings.Contains(value, "offline") || strings.Contains(value, "paused") {
return true
}
}
return false
}
func findSumatraPDF() (string, error) {
if envPath := strings.TrimSpace(os.Getenv("SUMATRAPDF_PATH")); envPath != "" {
if fileExists(envPath) {
return envPath, nil
}
}
if exe, err := os.Executable(); err == nil {
candidate := filepath.Join(filepath.Dir(exe), "SumatraPDF.exe")
if fileExists(candidate) {
return candidate, nil
}
}
if path, err := exec.LookPath("SumatraPDF.exe"); err == nil {
return path, nil
}
if path, err := exec.LookPath("SumatraPDF"); err == nil {
return path, nil
}
return "", fmt.Errorf("SumatraPDF.exe not found. Place it next to the app, add it to PATH, or set SUMATRAPDF_PATH")
}
func fileExists(path string) bool {
info, err := os.Stat(path)
return err == nil && !info.IsDir()
}
func buildSumatraPrintSettings(options PrintOptions) string {
var settings []string
if options.PageRange != "" {
settings = append(settings, options.PageRange)
}
switch strings.ToLower(strings.TrimSpace(options.PageSet)) {
case "even":
settings = append(settings, "even")
case "odd":
settings = append(settings, "odd")
}
switch strings.ToLower(strings.TrimSpace(options.Scale)) {
case "fit":
settings = append(settings, "fit")
case "shrink":
settings = append(settings, "shrink")
case "none", "actual", "noscale":
settings = append(settings, "noscale")
}
switch strings.ToLower(strings.TrimSpace(options.Orientation)) {
case "portrait":
settings = append(settings, "portrait")
case "landscape":
settings = append(settings, "landscape")
}
switch strings.ToLower(strings.TrimSpace(options.Duplex)) {
case "simplex", "one-sided":
settings = append(settings, "simplex")
case "long-edge", "long", "duplex", "duplexlong":
settings = append(settings, "duplex")
case "short-edge", "short", "duplexshort":
settings = append(settings, "duplexshort")
}
switch strings.ToLower(strings.TrimSpace(options.ColorMode)) {
case "color":
settings = append(settings, "color")
case "mono", "monochrome", "grayscale", "gray":
settings = append(settings, "monochrome")
}
if options.Paper != "" {
settings = append(settings, fmt.Sprintf("paper=%s", options.Paper))
}
if options.TrayBin != "" {
settings = append(settings, fmt.Sprintf("bin=%s", options.TrayBin))
}
if options.Copies > 1 {
settings = append(settings, fmt.Sprintf("%dx", options.Copies))
}
return strings.Join(settings, ",")
}

View File

@@ -0,0 +1,35 @@
# Build Directory
The build directory is used to house all the build files and assets for your application.
The structure is:
* bin - Output directory
* darwin - macOS specific files
* windows - Windows specific files
## Mac
The `darwin` directory holds files specific to Mac builds.
These may be customised and used as part of the build. To return these files to the default state, simply delete them
and
build with `wails build`.
The directory contains the following files:
- `Info.plist` - the main plist file used for Mac builds. It is used when building using `wails build`.
- `Info.dev.plist` - same as the main plist file but used when building using `wails dev`.
## Windows
The `windows` directory contains the manifest and rc files used when building with `wails build`.
These may be customised for your application. To return these files to the default state, simply delete them and
build with `wails build`.
- `icon.ico` - The icon used for the application. This is used when building using `wails build`. If you wish to
use a different icon, simply replace this file with your own. If it is missing, a new `icon.ico` file
will be created using the `appicon.png` file in the build directory.
- `installer/*` - The files used to create the Windows installer. These are used when building using `wails build`.
- `info.json` - Application details used for Windows builds. The data here will be used by the Windows installer,
as well as the application itself (right click the exe -> properties -> details)
- `wails.exe.manifest` - The main application manifest file.

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

View File

@@ -0,0 +1,68 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleName</key>
<string>{{.Info.ProductName}}</string>
<key>CFBundleExecutable</key>
<string>{{.OutputFilename}}</string>
<key>CFBundleIdentifier</key>
<string>com.wails.{{.Name}}</string>
<key>CFBundleVersion</key>
<string>{{.Info.ProductVersion}}</string>
<key>CFBundleGetInfoString</key>
<string>{{.Info.Comments}}</string>
<key>CFBundleShortVersionString</key>
<string>{{.Info.ProductVersion}}</string>
<key>CFBundleIconFile</key>
<string>iconfile</string>
<key>LSMinimumSystemVersion</key>
<string>10.13.0</string>
<key>NSHighResolutionCapable</key>
<string>true</string>
<key>NSHumanReadableCopyright</key>
<string>{{.Info.Copyright}}</string>
{{if .Info.FileAssociations}}
<key>CFBundleDocumentTypes</key>
<array>
{{range .Info.FileAssociations}}
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>{{.Ext}}</string>
</array>
<key>CFBundleTypeName</key>
<string>{{.Name}}</string>
<key>CFBundleTypeRole</key>
<string>{{.Role}}</string>
<key>CFBundleTypeIconFile</key>
<string>{{.IconName}}</string>
</dict>
{{end}}
</array>
{{end}}
{{if .Info.Protocols}}
<key>CFBundleURLTypes</key>
<array>
{{range .Info.Protocols}}
<dict>
<key>CFBundleURLName</key>
<string>com.wails.{{.Scheme}}</string>
<key>CFBundleURLSchemes</key>
<array>
<string>{{.Scheme}}</string>
</array>
<key>CFBundleTypeRole</key>
<string>{{.Role}}</string>
</dict>
{{end}}
</array>
{{end}}
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
</dict>
</plist>

View File

@@ -0,0 +1,63 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleName</key>
<string>{{.Info.ProductName}}</string>
<key>CFBundleExecutable</key>
<string>{{.OutputFilename}}</string>
<key>CFBundleIdentifier</key>
<string>com.wails.{{.Name}}</string>
<key>CFBundleVersion</key>
<string>{{.Info.ProductVersion}}</string>
<key>CFBundleGetInfoString</key>
<string>{{.Info.Comments}}</string>
<key>CFBundleShortVersionString</key>
<string>{{.Info.ProductVersion}}</string>
<key>CFBundleIconFile</key>
<string>iconfile</string>
<key>LSMinimumSystemVersion</key>
<string>10.13.0</string>
<key>NSHighResolutionCapable</key>
<string>true</string>
<key>NSHumanReadableCopyright</key>
<string>{{.Info.Copyright}}</string>
{{if .Info.FileAssociations}}
<key>CFBundleDocumentTypes</key>
<array>
{{range .Info.FileAssociations}}
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>{{.Ext}}</string>
</array>
<key>CFBundleTypeName</key>
<string>{{.Name}}</string>
<key>CFBundleTypeRole</key>
<string>{{.Role}}</string>
<key>CFBundleTypeIconFile</key>
<string>{{.IconName}}</string>
</dict>
{{end}}
</array>
{{end}}
{{if .Info.Protocols}}
<key>CFBundleURLTypes</key>
<array>
{{range .Info.Protocols}}
<dict>
<key>CFBundleURLName</key>
<string>com.wails.{{.Scheme}}</string>
<key>CFBundleURLSchemes</key>
<array>
<string>{{.Scheme}}</string>
</array>
<key>CFBundleTypeRole</key>
<string>{{.Role}}</string>
</dict>
{{end}}
</array>
{{end}}
</dict>
</plist>

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

View File

@@ -0,0 +1,15 @@
{
"fixed": {
"file_version": "{{.Info.ProductVersion}}"
},
"info": {
"0000": {
"ProductVersion": "{{.Info.ProductVersion}}",
"CompanyName": "{{.Info.CompanyName}}",
"FileDescription": "{{.Info.ProductName}}",
"LegalCopyright": "{{.Info.Copyright}}",
"ProductName": "{{.Info.ProductName}}",
"Comments": "{{.Info.Comments}}"
}
}
}

View File

@@ -0,0 +1,120 @@
Unicode true
####
## Please note: Template replacements don't work in this file. They are provided with default defines like
## mentioned underneath.
## If the keyword is not defined, "wails_tools.nsh" will populate them with the values from ProjectInfo.
## If they are defined here, "wails_tools.nsh" will not touch them. This allows to use this project.nsi manually
## from outside of Wails for debugging and development of the installer.
##
## For development first make a wails nsis build to populate the "wails_tools.nsh":
## > wails build --target windows/amd64 --nsis
## Then you can call makensis on this file with specifying the path to your binary:
## For a AMD64 only installer:
## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app.exe
## For a ARM64 only installer:
## > makensis -DARG_WAILS_ARM64_BINARY=..\..\bin\app.exe
## For a installer with both architectures:
## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app-amd64.exe -DARG_WAILS_ARM64_BINARY=..\..\bin\app-arm64.exe
####
## The following information is taken from the ProjectInfo file, but they can be overwritten here.
####
## !define INFO_PROJECTNAME "MyProject" # Default "{{.Name}}"
## !define INFO_COMPANYNAME "MyCompany" # Default "{{.Info.CompanyName}}"
## !define INFO_PRODUCTNAME "MyProduct" # Default "{{.Info.ProductName}}"
## !define INFO_PRODUCTVERSION "1.0.0" # Default "{{.Info.ProductVersion}}"
## !define INFO_COPYRIGHT "Copyright" # Default "{{.Info.Copyright}}"
###
## !define PRODUCT_EXECUTABLE "Application.exe" # Default "${INFO_PROJECTNAME}.exe"
## !define UNINST_KEY_NAME "UninstKeyInRegistry" # Default "${INFO_COMPANYNAME}${INFO_PRODUCTNAME}"
####
## !define REQUEST_EXECUTION_LEVEL "admin" # Default "admin" see also https://nsis.sourceforge.io/Docs/Chapter4.html
####
## Include the wails tools
####
!include "wails_tools.nsh"
# The version information for this two must consist of 4 parts
VIProductVersion "${INFO_PRODUCTVERSION}.0"
VIFileVersion "${INFO_PRODUCTVERSION}.0"
VIAddVersionKey "CompanyName" "${INFO_COMPANYNAME}"
VIAddVersionKey "FileDescription" "${INFO_PRODUCTNAME} Installer"
VIAddVersionKey "ProductVersion" "${INFO_PRODUCTVERSION}"
VIAddVersionKey "FileVersion" "${INFO_PRODUCTVERSION}"
VIAddVersionKey "LegalCopyright" "${INFO_COPYRIGHT}"
VIAddVersionKey "ProductName" "${INFO_PRODUCTNAME}"
# Enable HiDPI support. https://nsis.sourceforge.io/Reference/ManifestDPIAware
ManifestDPIAware true
!include "MUI.nsh"
!define MUI_ICON "..\icon.ico"
!define MUI_UNICON "..\icon.ico"
# !define MUI_WELCOMEFINISHPAGE_BITMAP "resources\leftimage.bmp" #Include this to add a bitmap on the left side of the Welcome Page. Must be a size of 164x314
!define MUI_FINISHPAGE_NOAUTOCLOSE # Wait on the INSTFILES page so the user can take a look into the details of the installation steps
!define MUI_ABORTWARNING # This will warn the user if they exit from the installer.
!insertmacro MUI_PAGE_WELCOME # Welcome to the installer page.
# !insertmacro MUI_PAGE_LICENSE "resources\eula.txt" # Adds a EULA page to the installer
!insertmacro MUI_PAGE_DIRECTORY # In which folder install page.
!insertmacro MUI_PAGE_INSTFILES # Installing page.
!insertmacro MUI_PAGE_FINISH # Finished installation page.
!insertmacro MUI_UNPAGE_INSTFILES # Uinstalling page
!insertmacro MUI_LANGUAGE "English" # Set the Language of the installer
## The following two statements can be used to sign the installer and the uninstaller. The path to the binaries are provided in %1
#!uninstfinalize 'signtool --file "%1"'
#!finalize 'signtool --file "%1"'
Name "${INFO_PRODUCTNAME}"
OutFile "..\..\bin\${INFO_PROJECTNAME}-${ARCH}-installer.exe" # Name of the installer's file.
InstallDir "$PROGRAMFILES64\${INFO_PRODUCTNAME}" # Default installing folder ($PROGRAMFILES is Program Files folder).
ShowInstDetails show # This will always show the installation details.
Function .onInit
!insertmacro wails.checkArchitecture
FunctionEnd
Section
!insertmacro wails.setShellContext
!insertmacro wails.webview2runtime
SetOutPath $INSTDIR
!insertmacro wails.files
File "resources\SumatraPDF.exe"
CreateShortcut "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}"
CreateShortCut "$DESKTOP\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}"
!insertmacro wails.associateFiles
!insertmacro wails.associateCustomProtocols
!insertmacro wails.writeUninstaller
SectionEnd
Section "uninstall"
!insertmacro wails.setShellContext
RMDir /r "$AppData\${PRODUCT_EXECUTABLE}" # Remove the WebView2 DataPath
RMDir /r "$ProgramData\PrintDot"
Delete "$INSTDIR\SumatraPDF.exe"
RMDir /r $INSTDIR
Delete "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk"
Delete "$DESKTOP\${INFO_PRODUCTNAME}.lnk"
!insertmacro wails.unassociateFiles
!insertmacro wails.unassociateCustomProtocols
!insertmacro wails.deleteUninstaller
SectionEnd

View File

@@ -0,0 +1,94 @@
# For documentation, see https://www.sumatrapdfreader.org/settings/settings3-5-1.html
Theme = Light
FixedPageUI [
TextColor = #000000
BackgroundColor = #ffffff
SelectionColor = #f5fc0c
WindowMargin = 2 4 2 4
PageSpacing = 4 4
InvertColors = false
HideScrollbars = false
]
ComicBookUI [
WindowMargin = 0 0 0 0
PageSpacing = 4 4
CbxMangaMode = false
]
ChmUI [
UseFixedPageUI = false
]
SelectionHandlers [
]
ExternalViewers [
]
ZoomLevels = 8.33 12.5 18 25 33.33 50 66.67 75 100 125 150 200 300 400 600 800 1000 1200 1600 2000 2400 3200 4800 6400
ZoomIncrement = 0
PrinterDefaults [
PrintScale = shrink
]
ForwardSearch [
HighlightOffset = 0
HighlightWidth = 15
HighlightColor = #6581ff
HighlightPermanent = false
]
Annotations [
HighlightColor = #ffff00
UnderlineColor = #00ff00
SquigglyColor = #ff00ff
StrikeOutColor = #ff0000
FreeTextColor =
FreeTextSize = 12
FreeTextBorderWidth = 1
TextIconColor =
TextIconType =
DefaultAuthor =
]
RememberOpenedFiles = true
RememberStatePerDocument = true
RestoreSession = true
UiLanguage = cn
EnableTeXEnhancements = false
DefaultDisplayMode = automatic
DefaultZoom = fit page
Shortcuts [
]
EscToExit = false
ReuseInstance = false
ReloadModifiedDocuments = true
MainWindowBackground = #80fff200
FullPathInTitle = false
ShowMenubar = true
ShowToolbar = true
ShowFavorites = false
ShowToc = true
NoHomeTab = false
TocDy = 0
SidebarDx = 0
ToolbarSize = 18
TabWidth = 300
TreeFontSize = 0
TreeFontWeightOffset = 0
TreeFontName = automatic
SmoothScroll = false
ShowStartPage = true
CheckForUpdates = true
WindowState = 1
WindowPos = 520 0 880 1140
UseTabs = true
UseSysColors = false
CustomScreenDPI = 0
FileStates [
]
SessionData [
]
TimeOfLastUpdateCheck = 0 0
OpenCountWeek = 798
# Settings below are not recognized by the current version

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
<assemblyIdentity type="win32" name="com.wails.{{.Name}}" version="{{.Info.ProductVersion}}.0" processorArchitecture="*"/>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
</dependentAssembly>
</dependency>
<asmv3:application>
<asmv3:windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware> <!-- fallback for Windows 7 and 8 -->
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitorv2,permonitor</dpiAwareness> <!-- falls back to per-monitor if per-monitor v2 is not supported -->
</asmv3:windowsSettings>
</asmv3:application>
</assembly>

30
XSLPrintDot/device_id.go Normal file
View File

@@ -0,0 +1,30 @@
package main
import "strings"
func getNormalizedDeviceID() string {
id, err := getDeviceID()
if err != nil {
return ""
}
id = strings.TrimSpace(id)
if id == "" {
return ""
}
if strings.HasPrefix(id, "{") && strings.HasSuffix(id, "}") {
id = strings.TrimSpace(id[1 : len(id)-1])
}
clean := strings.ReplaceAll(id, "-", "")
clean = strings.ReplaceAll(clean, " ", "")
clean = strings.ReplaceAll(clean, "\t", "")
clean = strings.ReplaceAll(clean, "\n", "")
clean = strings.ReplaceAll(clean, "\r", "")
if len(clean) == 32 {
id = clean[0:8] + "-" + clean[8:12] + "-" + clean[12:16] + "-" + clean[16:20] + "-" + clean[20:32]
}
return strings.ToUpper(id)
}

View File

@@ -0,0 +1,33 @@
//go:build darwin
package main
import (
"bytes"
"os/exec"
"strings"
)
func getDeviceID() (string, error) {
out, err := exec.Command("ioreg", "-rd1", "-c", "IOPlatformExpertDevice").Output()
if err != nil {
return "", err
}
lines := bytes.Split(out, []byte("\n"))
for _, line := range lines {
text := strings.TrimSpace(string(line))
if !strings.Contains(text, "IOPlatformUUID") {
continue
}
if idx := strings.Index(text, "="); idx >= 0 {
value := strings.TrimSpace(text[idx+1:])
value = strings.Trim(value, "\"")
if value != "" {
return value, nil
}
}
}
return "", nil
}

View File

@@ -0,0 +1,28 @@
//go:build linux
package main
import (
"os"
"strings"
)
func getDeviceID() (string, error) {
paths := []string{
"/etc/machine-id",
"/var/lib/dbus/machine-id",
}
for _, path := range paths {
data, err := os.ReadFile(path)
if err != nil {
continue
}
value := strings.TrimSpace(string(data))
if value != "" {
return value, nil
}
}
return "", nil
}

View File

@@ -0,0 +1,9 @@
//go:build !windows && !darwin && !linux
package main
import "os"
func getDeviceID() (string, error) {
return os.Hostname()
}

View File

@@ -0,0 +1,19 @@
//go:build windows
package main
import "golang.org/x/sys/windows/registry"
func getDeviceID() (string, error) {
key, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Cryptography`, registry.QUERY_VALUE)
if err != nil {
return "", err
}
defer key.Close()
id, _, err := key.GetStringValue("MachineGuid")
if err != nil {
return "", err
}
return id, nil
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

View File

@@ -0,0 +1,257 @@
# XSL-PrintDot Client Usage Guide
## 1. Introduction
**XSL-PrintDot Client** is a local printing middleware developed based on Wails (Go + Vue 3). It acts as a bridge between browsers (or other clients) and the operating system's printers, receiving print instructions via the WebSocket protocol and invoking the system printer for printing.
Key Features:
- Automatically retrieves the list of installed printers in the operating system.
- Starts a WebSocket service to listen for print requests (default port 1122).
- Supports custom service ports and security keys (Secret Key).
- **Print Content Requirement**: Accepts Base64 encoded PDF content and invokes system printing commands.
- Supports advanced print parameters: copies, interval between copies, and more print settings.
- Provides a visual management interface to view logs and printer status in real-time.
- **Real-time Log Monitoring**: View system logs in real time.
---
## 2. Startup and Configuration
### 2.1 Starting the Application
You can run the compiled executable file (e.g., `XSL-PrintDot.exe`) directly.
**Note**: The program automatically starts the WebSocket service (default port 1122) upon startup.
**Windows printing note**:
- Ensure the Windows printing backend is available and accessible by the app.
### 2.2 Interface Configuration
After startup, the interface provides the following configuration options:
- **Port**: WebSocket service listening port (default `1122`).
- **Secret Key**: Security key (optional). If a key is set, clients must authenticate when connecting or sending requests.
- **Start/Stop Server**: Click the button to start or stop the WebSocket service.
- **Connection URL**: After the service starts, the interface displays the full connection address (e.g., `ws://localhost:1122/ws?key=...`).
**Operation Instructions**:
- **Exit Program**: Use the menu bar `Menu` -> `Quit` (Ctrl+Q) or the tray menu `Quit` to completely exit the program.
- **Run in Background**: Clicking the main window close button (X) will not exit the program but minimize it to the system tray. An icon appears in the system tray area, which can be used to quickly recall the window or exit.
- **Tray Menu**: Right-click the system tray icon to select `Show Main Window` or `Quit`.
- **Open Settings**: Use the menu bar `Menu` -> `Settings` (Ctrl+I) to open the settings window.
- **View Logs**: Use the menu bar `Menu` -> `System Logs` (Ctrl+L) to view logs in real time.
---
## 3. WebSocket Interface Specification
### 3.1 Connection Information
- **Protocol**: WebSocket (`ws://`)
- **Address**: `ws://localhost:<PORT>/ws`
- **Authentication**:
- If a `Secret Key` is set, it is recommended to carry it in the connection URL: `ws://localhost:1122/ws?key=YOUR_PASSWORD`
- If the key is not carried during connection, it can also be included in the message body sent (but not recommended, as the connection might be rejected).
### 3.2 Message Types
#### 3.2.1 Connection Success Response (Server -> Client)
After the connection is established, the server immediately sends the current printer list:
```json
{
"type": "printer_list",
"data": [
{"name": "Microsoft Print to PDF", "isDefault": true},
{"name": "ZDesigner GK888t", "isDefault": false}
]
}
```
#### 3.2.2 Get Printer List (Client -> Server)
The client can actively request the latest printer list at any time by sending the following JSON message:
```json
{
"type": "get_printers"
}
```
The server will reply with a `printer_list` message in the same format as **3.2.1**.
#### 3.2.3 Get Printer Capabilities (Client -> Server)
Request capabilities for a specific printer:
```json
{
"type": "get_printer_caps",
"printer": "Microsoft Print to PDF"
}
```
Example response:
```json
{
"type": "printer_caps",
"printer": "Microsoft Print to PDF",
"data": {
"paperSizes": ["A4", "Letter"],
"printerPaperNames": ["A4", "Letter"],
"duplexSupported": false,
"colorSupported": true
}
}
```
> Note: fields vary by platform. Windows returns Win32_Printer/Win32_PrinterConfiguration info; Linux/macOS returns parsed lpoptions data.
#### 3.2.4 Send Print Job (Client -> Server)
The JSON payload is grouped by feature:
```json
{
"printer": "Microsoft Print to PDF", // [Required] Target printer name
"content": "data:application/pdf;base64,JVBERi...", // [Required] Base64 encoded PDF content (Supports Data URI prefix or raw Base64)
"key": "123456", // [Optional] Auth key (can be omitted if verified during connection)
"job": {
"name": "My Print Job 001", // [Optional] Job name (for logging only)
"copies": 2, // [Optional] Number of copies, default 1
"intervalMs": 1000 // [Optional] Delay between copies (ms)
},
"pages": {
"range": "1-3,5", // [Optional] Page range (N / N-M / N,M / reverse ranges)
"set": "odd" // [Optional] odd | even
},
"layout": {
"scale": "fit", // [Optional] noscale | shrink | fit
"orientation": "portrait" // [Optional] portrait | landscape
},
"color": {
"mode": "color" // [Optional] color | monochrome
},
"sides": {
"mode": "duplex" // [Optional] simplex | duplex | duplexshort | duplexlong
},
"paper": {
"size": "A4" // [Optional] A4 | letter | legal | tabloid | statement | A2 | A3 | A5 | A6
},
"tray": {
"bin": "2" // [Optional] Tray number or name, e.g. 2 / Manual
}
}
```
> **Note**:
> 1. The `content` field must be a **Base64 encoded string of a PDF file**.
> - Supports standard Data URI format: `data:application/pdf;base64,JVBERi...`
> - Also supports raw Base64 string: `JVBERi...`
> - The server automatically strips the `data:` prefix (if present) and validates that the decoded content starts with `%PDF`.
| Field | Type | Description |
| :--- | :--- | :--- |
| `printer` | String | Target printer name. |
| `content` | String | **Base64 encoded PDF content**. |
| `job.name` | String | Print job name. |
| `job.copies` | Integer | **Number of copies**. If `intervalMs` is 0, handled by the system command. |
| `job.intervalMs` | Integer | **Interval (ms)**. When > 0, the server prints one copy per run. |
| `pages.range` | String | **Page range**: `N` / `N-M` / `N,M` / reverse ranges. |
| `pages.set` | String | **Odd/Even**: `odd` / `even`. |
| `layout.scale` | String | **Scaling**: `noscale` / `shrink` / `fit`. |
| `layout.orientation` | String | **Orientation**: `portrait` / `landscape`. |
| `color.mode` | String | **Color mode**: `color` / `monochrome`. |
| `sides.mode` | String | **Duplex**: `simplex` / `duplex` / `duplexshort` / `duplexlong`. |
| `paper.size` | String | **Paper size**: e.g. `A4`, `letter`, `legal`. If omitted, we try to auto-detect common sizes from PDF MediaBox. |
| `tray.bin` | String | **Tray**: number or name. |
#### 3.2.3.1 Platform Support
**Windows**
- `pages.range` / `pages.set` / `layout.scale` / `layout.orientation` / `color.mode` / `sides.mode` / `paper.size` / `tray.bin` / `job.copies` are converted to Windows print options.
**Linux/macOS (lp/CUPS)**
- `pages.range` -> `-P`.
- `pages.set` -> `-o page-set=odd|even`.
- `layout.scale` -> `fit-to-page` / `scaling=100` (`shrink` uses default behavior).
- `layout.orientation` -> `-o orientation-requested=3|4` (may be ignored by drivers).
- `color.mode` -> `-o ColorModel=Gray` / `-o ColorModel=RGB` (may be ignored by drivers).
- `sides.mode` -> `-o sides=...`.
- `paper.size` -> `-o media=...`.
- `tray.bin` -> `-o InputSlot=...` (depends on driver support).
#### 3.2.4 Server Response (Server -> Client)
The server returns the result of each print:
**Success Response:**
```json
{
"status": "success",
"message": "Printed successfully"
}
```
**Failure Response:**
```json
{
"status": "error",
"message": "Content must be a PDF file"
}
```
**Windows queue tracking note:**
On Windows, the server waits for the print job to appear in the printer queue and complete before returning `success`.
If the job does not appear within 120 seconds, or does not complete within 5 minutes, it returns `error` with a timeout message.
### 3.3 Client Code Example
```javascript
const socket = new WebSocket('ws://localhost:1122/ws?key=123456');
socket.onopen = () => {
console.log('Connected');
};
socket.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === 'printer_list') {
console.log('Available printers:', msg.data);
const targetPrinter = msg.data.find(p => p.isDefault) || msg.data[0];
// Example: Actively refresh printer list
// socket.send(JSON.stringify({ type: 'get_printers' }));
// Fetch printer capabilities (paper/duplex/color, etc.)
socket.send(JSON.stringify({
type: 'get_printer_caps',
printer: targetPrinter?.name
}));
} else if (msg.type === 'printer_caps') {
const caps = msg.data || {};
const sizes = caps.printerPaperNames || caps.paperSizes || [];
const paperSize = sizes[0] || 'A4';
// Send print job (grouped by feature)
socket.send(JSON.stringify({
printer: msg.printer,
content: "JVBERi0xLjQKJ...", // Base64 PDF Data
job: {
name: "Test Job",
copies: 2,
intervalMs: 0
},
pages: {
range: "1-3,5",
set: "odd"
},
layout: {
scale: "fit",
orientation: "portrait"
},
color: {
mode: "color"
},
sides: {
mode: "duplex"
},
paper: {
size: paperSize
},
tray: {
bin: "2"
}
}));
} else {
console.log('Response:', msg);
}
};
```

View File

@@ -0,0 +1,263 @@
# XSL-PrintDot Client 使用指南与规范
## 1. 项目简介
**XSL-PrintDot Client** 是一个基于 Wails (Go + Vue 3) 开发的本地打印中间件。它充当浏览器(或其他客户端)与操作系统打印机之间的桥梁,通过 WebSocket 协议接收打印指令,并调用系统打印机进行打印。
主要功能:
- 自动获取操作系统已安装的打印机列表。
- 启动 WebSocket 服务监听打印请求(默认端口 1122
- 支持自定义服务端口和安全密钥Secret Key
- **打印内容要求**:接收 Base64 编码的 PDF 文件内容,并调用系统打印命令进行打印。
- 支持高级打印参数:打印份数、份数间隔,以及更多打印设置。
- 提供可视化的管理界面,实时查看日志和打印机状态。
- **日志实时监控**:支持实时查看系统日志。
---
## 2. 启动与配置
### 2.1 启动应用
可以直接运行编译后的可执行文件(如 `XSL-PrintDot.exe`),或在开发环境中使用:
```bash
wails dev
```
**注意**: 程序启动时会自动开启 WebSocket 服务(默认端口 1122
**Windows 打印说明**:
- 请确保 Windows 打印后端可用且程序有权限访问。
### 2.2 界面配置
启动后,界面提供以下配置项:
- **Port**: WebSocket 服务监听端口(默认 `1122`)。
- **Secret Key**: 安全密钥(可选)。如果设置了密钥,客户端在连接或发送请求时必须通过鉴权。
- **Start/Stop Server**: 点击按钮即可启动或停止 WebSocket 服务。
- **Connection URL**: 服务启动后,界面会显示完整的连接地址(如 `ws://localhost:1122/ws?key=...`)。
**操作说明**:
- **退出程序**: 使用菜单栏 `Menu` -> `Quit` (Ctrl+Q),或使用托盘菜单的 `Quit` 可完全退出程序。
- **后台运行**: 点击主窗口关闭按钮 (X) 不会退出程序,而是将程序最小化到系统托盘区。程序启动后会在系统托盘区显示图标,可用于快速唤起窗口或退出。
- **托盘菜单**: 在系统托盘图标上右键单击,可选择 `Show Main Window` 显示主窗口或 `Quit` 退出程序。
- **打开设置**: 使用菜单栏 `Menu` -> `Settings` (Ctrl+I) 可打开设置窗口。
- **查看日志**: 使用菜单栏 `Menu` -> `System Logs` (Ctrl+L) 可查看实时日志.
---
## 3. WebSocket 接口规范
### 3.1 连接信息
- **协议**: WebSocket (`ws://`)
- **地址**: `ws://localhost:<PORT>/ws`
- **鉴权**:
- 如果设置了 `Secret Key`,建议在连接 URL 中携带:`ws://localhost:1122/ws?key=YOUR_PASSWORD`
- 如果连接时未携带 key也可以在发送的消息体中包含 `key` 字段(但不推荐,连接可能被拒绝)。
### 3.2 消息类型
#### 3.2.1 连接成功响应 (Server -> Client)
连接建立后,服务端会立即发送当前的打印机列表:
```json
{
"type": "printer_list",
"data": [
{"name": "Microsoft Print to PDF", "isDefault": true},
{"name": "ZDesigner GK888t", "isDefault": false}
]
}
```
#### 3.2.2 获取打印机列表 (Client -> Server)
客户端可以随时发送以下 JSON 消息主动获取最新的打印机列表:
```json
{
"type": "get_printers"
}
```
服务端将回复与 **3.2.1** 相同格式的 `printer_list` 消息。
#### 3.2.3 获取打印机能力 (Client -> Server)
客户端可以请求指定打印机的可用参数:
```json
{
"type": "get_printer_caps",
"printer": "Microsoft Print to PDF"
}
```
服务端响应示例:
```json
{
"type": "printer_caps",
"printer": "Microsoft Print to PDF",
"data": {
"paperSizes": ["A4", "Letter"],
"printerPaperNames": ["A4", "Letter"],
"duplexSupported": false,
"colorSupported": true
}
}
```
> 说明不同系统返回字段会有差异Windows 返回 Win32_Printer/Win32_PrinterConfiguration 信息Linux/macOS 返回 lpoptions 解析结果。
#### 3.2.4 发送打印任务 (Client -> Server)
客户端发送的 JSON 数据包结构如下(按功能分类):
```json
{
"printer": "Microsoft Print to PDF", // [必填] 目标打印机名称
"content": "data:application/pdf;base64,JVBERi...", // [必填] Base64 编码的 PDF 内容 (支持带前缀或纯 Base64)
"key": "123456", // [选填] 鉴权密钥 (若连接时已验证可省略)
"job": {
"name": "My Print Job 001", // [选填] 任务名称 (仅用于日志记录)
"copies": 2, // [选填] 打印份数,默认 1
"intervalMs": 1000 // [选填] 份数间延迟(毫秒),用于手动隔张打印
},
"pages": {
"range": "1-3,5", // [选填] 页码范围 (支持 N / N-M / N,M / 反向区间)
"set": "odd" // [选填] odd | even
},
"layout": {
"scale": "fit", // [选填] noscale | shrink | fit
"orientation": "portrait" // [选填] portrait | landscape
},
"color": {
"mode": "color" // [选填] color | monochrome
},
"sides": {
"mode": "duplex" // [选填] simplex | duplex | duplexshort | duplexlong
},
"paper": {
"size": "A4" // [选填] A4 | letter | legal | tabloid | statement | A2 | A3 | A5 | A6
},
"tray": {
"bin": "2" // [选填] 纸盒编号或名称,例如 2 / Manual
}
}
```
> **注意**:
> 1. `content` 字段必须是 **PDF 文件的 Base64 编码字符串**。
> - 支持标准 Data URI 格式:`data:application/pdf;base64,JVBERi...`
> - 也支持纯 Base64 字符串:`JVBERi...`
> - 服务端会自动去除 `data:` 前缀(如果有)并校验解码后的内容是否以 `%PDF` 开头。
| 字段 | 类型 | 说明 |
| :--- | :--- | :--- |
| `printer` | String | 目标打印机名称。 |
| `content` | String | **Base64 编码的 PDF 内容**。 |
| `job.name` | String | 打印任务名称。 |
| `job.copies` | Integer | **打印份数**`intervalMs` 为 0 时由系统命令一次性处理。 |
| `job.intervalMs` | Integer | **隔张间隔 (ms)**。大于 0 时服务端逐份打印。 |
| `pages.range` | String | **页码范围**`N` / `N-M` / `N,M` / 反向区间。 |
| `pages.set` | String | **奇偶页**`odd` / `even`。 |
| `layout.scale` | String | **缩放**`noscale` / `shrink` / `fit`。 |
| `layout.orientation` | String | **方向**`portrait` / `landscape`。 |
| `color.mode` | String | **颜色模式**`color` / `monochrome`。 |
| `sides.mode` | String | **单双面**`simplex` / `duplex` / `duplexshort` / `duplexlong`。 |
| `paper.size` | String | **纸张**:如 `A4``letter``legal`。未提供时会尝试从 PDF 的 MediaBox 自动识别常见尺寸。 |
| `tray.bin` | String | **纸盒**:编号或名称。 |
#### 3.2.3.1 平台支持说明
**Windows**
- `pages.range` / `pages.set` / `layout.scale` / `layout.orientation` / `color.mode` / `sides.mode` / `paper.size` / `tray.bin` / `job.copies` 会被转换为 Windows 打印选项。
**Linux/macOS (lp/CUPS)**
- `pages.range` -> `-P`
- `pages.set` -> `-o page-set=odd|even`
- `layout.scale` -> `fit-to-page` / `scaling=100``shrink` 使用默认行为)。
- `layout.orientation` -> `-o orientation-requested=3|4`(驱动可能忽略)。
- `color.mode` -> `-o ColorModel=Gray` / `-o ColorModel=RGB`(部分驱动可能忽略)。
- `sides.mode` -> `-o sides=...`
- `paper.size` -> `-o media=...`
- `tray.bin` -> `-o InputSlot=...`(依赖驱动支持)。
#### 3.2.4 服务端响应 (Server -> Client)
服务端会返回每次打印的结果:
**成功响应:**
```json
{
"status": "success",
"message": "Printed successfully"
}
```
**失败响应:**
```json
{
"status": "error",
"message": "Content must be a PDF file"
}
```
**Windows 队列跟踪说明:**
Windows 下服务端会等待打印任务进入打印队列并完成后才返回 `success`
若 120 秒内未入队或 5 分钟内未完成,将返回 `error` 并给出超时提示。
---
## 4. 调用示例 (JavaScript)
```javascript
const socket = new WebSocket('ws://localhost:1122/ws?key=123456');
socket.onopen = () => {
console.log('已连接');
};
socket.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === 'printer_list') {
console.log('可用打印机:', msg.data);
const targetPrinter = msg.data.find(p => p.isDefault) || msg.data[0];
// 示例:主动刷新打印机列表
// socket.send(JSON.stringify({ type: 'get_printers' }));
// 获取打印机能力(纸张/单双面/彩色等)
socket.send(JSON.stringify({
type: 'get_printer_caps',
printer: targetPrinter?.name
}));
} else if (msg.type === 'printer_caps') {
const caps = msg.data || {};
const sizes = caps.printerPaperNames || caps.paperSizes || [];
const paperSize = sizes[0] || 'A4';
// 发送打印任务(按功能分组)
socket.send(JSON.stringify({
printer: msg.printer,
content: "JVBERi0xLjQKJ...", // Base64 PDF Data
job: {
name: "Test Job",
copies: 2,
intervalMs: 0
},
pages: {
range: "1-3,5",
set: "odd"
},
layout: {
scale: "fit",
orientation: "portrait"
},
color: {
mode: "color"
},
sides: {
mode: "duplex"
},
paper: {
size: paperSize
},
tray: {
bin: "2"
}
}));
} else {
console.log('收到回复:', msg);
}
};
```

513
XSLPrintDot/forwarder.go Normal file
View File

@@ -0,0 +1,513 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/gorilla/websocket"
)
const (
remotePingInterval = 20 * time.Second
remoteReportInterval = 10 * time.Second
remotePongWait = 70 * time.Second
remoteWriteWait = 5 * time.Second
)
type RemoteConfig struct {
Server string
AuthURL string
WsURL string
ClientID string
SecretKey string
ClientName string
}
type RemoteForwarderStatus struct {
Connected bool `json:"connected"`
LastError string `json:"lastError"`
LastChange int64 `json:"lastChange"`
AutoReconnect bool `json:"autoReconnect"`
}
type remoteLoginResponse struct {
Token string `json:"token"`
}
type remotePrintTask struct {
Cmd string `json:"cmd"`
TaskID string `json:"task_id"`
PrintRequest
}
func (b *Bridge) ConfigureRemoteForwarder(s AppSettings) {
b.StartRemoteForwarderWithSettings(s, false)
}
func (b *Bridge) StartRemoteForwarderWithSettings(s AppSettings, force bool) {
cfg := RemoteConfig{
Server: strings.TrimSpace(s.RemoteServer),
AuthURL: strings.TrimSpace(s.RemoteAuthURL),
WsURL: strings.TrimSpace(s.RemoteWsURL),
ClientID: strings.TrimSpace(firstNonEmpty(s.RemoteClientID, s.RemoteUser)),
SecretKey: strings.TrimSpace(firstNonEmpty(s.RemoteSecretKey, s.RemotePassword)),
ClientName: strings.TrimSpace(s.RemoteClientName),
}
if !force && !s.RemoteAutoConnect {
b.StopRemoteForwarder()
return
}
if (cfg.AuthURL == "" && cfg.Server == "") ||
(cfg.WsURL == "" && cfg.Server == "") ||
cfg.ClientID == "" || cfg.SecretKey == "" {
b.StopRemoteForwarder()
return
}
b.remoteMu.Lock()
same := cfg == b.remoteCfg && b.remoteStop != nil
b.remoteMu.Unlock()
if same {
return
}
b.StopRemoteForwarder()
b.remoteMu.Lock()
b.remoteCfg = cfg
b.remoteStop = make(chan struct{})
stop := b.remoteStop
b.remoteMu.Unlock()
b.remoteWg.Add(1)
go b.runRemoteForwarder(cfg, stop)
}
func (b *Bridge) StopRemoteForwarder() {
b.remoteMu.Lock()
stop := b.remoteStop
conn := b.remoteConn
b.remoteStop = nil
b.remoteMu.Unlock()
if stop != nil {
close(stop)
}
if conn != nil {
_ = conn.Close()
}
b.setRemoteConnected(false)
b.remoteWg.Wait()
}
func (b *Bridge) runRemoteForwarder(cfg RemoteConfig, stop <-chan struct{}) {
defer b.remoteWg.Done()
for {
if err := b.connectAndServeForwarder(cfg, stop); err != nil {
b.setRemoteError(err)
b.Log(fmt.Sprintf("Remote forwarder error: %v", err))
}
select {
case <-stop:
return
case <-time.After(3 * time.Second):
}
}
}
func (b *Bridge) connectAndServeForwarder(cfg RemoteConfig, stop <-chan struct{}) error {
loginURL, wsURL, err := buildRemoteURLsFromConfig(cfg)
if err != nil {
return err
}
token, err := b.remoteLogin(loginURL, cfg)
if err != nil {
return err
}
headers := http.Header{}
headers.Set("Authorization", "Bearer "+token)
headers.Set("X-Client-Id", cfg.ClientID)
if cfg.ClientName != "" {
headers.Set("X-Client-Name", cfg.ClientName)
}
conn, _, err := websocket.DefaultDialer.Dial(wsURL.String(), headers)
if err != nil {
return fmt.Errorf("ws connect failed: %v", err)
}
defer conn.Close()
conn.SetReadLimit(8 * 1024 * 1024)
_ = conn.SetReadDeadline(time.Now().Add(remotePongWait))
conn.SetPongHandler(func(string) error {
return conn.SetReadDeadline(time.Now().Add(remotePongWait))
})
b.setRemoteConn(conn)
b.setRemoteConnected(true)
defer func() {
b.clearRemoteConn(conn)
b.setRemoteConnected(false)
}()
b.Log(fmt.Sprintf("Remote forwarder connected: %s", wsURL.String()))
if err := b.reportPrinters(conn); err != nil {
b.Log(fmt.Sprintf("Report printers failed: %v", err))
}
pingStop := make(chan struct{})
go b.pingLoop(conn, pingStop)
go b.reportLoop(conn, pingStop)
defer close(pingStop)
for {
select {
case <-stop:
return nil
default:
}
_ = conn.SetReadDeadline(time.Now().Add(remotePongWait))
var rawMsg map[string]interface{}
if err := conn.ReadJSON(&rawMsg); err != nil {
return err
}
cmd, _ := rawMsg["cmd"].(string)
switch strings.ToLower(strings.TrimSpace(cmd)) {
case "print_task":
jsonBody, _ := json.Marshal(rawMsg)
var task remotePrintTask
if err := json.Unmarshal(jsonBody, &task); err != nil {
b.Log(fmt.Sprintf("Invalid print task: %v", err))
continue
}
message, err := b.processPrintRequest(task.PrintRequest)
status := "success"
if err != nil {
status = "failed"
}
resp := map[string]interface{}{
"cmd": "report_result",
"task_id": task.TaskID,
"status": status,
"message": message,
}
if err := writeJSONWithDeadline(conn, resp); err != nil {
b.Log(fmt.Sprintf("Report result failed: %v", err))
}
case "get_printers":
if err := b.reportPrinters(conn); err != nil {
b.Log(fmt.Sprintf("Report printers failed: %v", err))
}
case "auth_resp":
b.Log("Remote forwarder auth ok")
}
}
}
func (b *Bridge) remoteLogin(loginURL *url.URL, cfg RemoteConfig) (string, error) {
payload := map[string]string{
"client_id": cfg.ClientID,
"secret_key": cfg.SecretKey,
}
if cfg.ClientName != "" {
payload["client_name"] = cfg.ClientName
}
body, err := json.Marshal(payload)
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", loginURL.String(), bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return "", fmt.Errorf("login failed: status %d", resp.StatusCode)
}
var loginResp remoteLoginResponse
if err := json.NewDecoder(resp.Body).Decode(&loginResp); err != nil {
return "", err
}
if strings.TrimSpace(loginResp.Token) == "" {
return "", fmt.Errorf("login failed: empty token")
}
return loginResp.Token, nil
}
func (b *Bridge) reportPrinters(conn *websocket.Conn) error {
printers, err := b.GetPrinters()
if err != nil {
return err
}
list := make([]map[string]interface{}, 0, len(printers))
for _, p := range printers {
caps, capsErr := b.GetPrinterCapabilities(p.Name)
if capsErr != nil {
b.Log(fmt.Sprintf("Get printer capabilities failed: %s: %v", p.Name, capsErr))
caps = map[string]interface{}{}
}
list = append(list, map[string]interface{}{
"printer_name": p.Name,
"printer_type": "system",
"paper_spec": "",
"is_ready": true,
"supported_format": "pdf",
"capabilities": caps,
})
}
payload := map[string]interface{}{
"cmd": "report_printers",
"printers": list,
}
return writeJSONWithDeadline(conn, payload)
}
func (b *Bridge) pingLoop(conn *websocket.Conn, stop <-chan struct{}) {
ticker := time.NewTicker(remotePingInterval)
defer ticker.Stop()
for {
select {
case <-stop:
return
case <-ticker.C:
deadline := time.Now().Add(remoteWriteWait)
_ = conn.WriteControl(websocket.PingMessage, []byte("ping"), deadline)
}
}
}
func (b *Bridge) reportLoop(conn *websocket.Conn, stop <-chan struct{}) {
ticker := time.NewTicker(remoteReportInterval)
defer ticker.Stop()
for {
select {
case <-stop:
return
case <-ticker.C:
if err := b.reportPrinters(conn); err != nil {
b.Log(fmt.Sprintf("Report printers failed: %v", err))
}
}
}
}
func writeJSONWithDeadline(conn *websocket.Conn, payload interface{}) error {
_ = conn.SetWriteDeadline(time.Now().Add(remoteWriteWait))
return conn.WriteJSON(payload)
}
func buildRemoteURLs(raw string) (*url.URL, *url.URL, error) {
baseURL, err := normalizeRemoteBaseURL(raw)
if err != nil {
return nil, nil, err
}
loginBase := *baseURL
switch loginBase.Scheme {
case "ws":
loginBase.Scheme = "http"
case "wss":
loginBase.Scheme = "https"
}
wsBase := *baseURL
switch wsBase.Scheme {
case "http":
wsBase.Scheme = "ws"
case "https":
wsBase.Scheme = "wss"
}
loginURL := loginBase.ResolveReference(&url.URL{Path: "/api/client/login"})
wsURL := wsBase.ResolveReference(&url.URL{Path: "/ws/client"})
return loginURL, wsURL, nil
}
func buildRemoteURLsFromConfig(cfg RemoteConfig) (*url.URL, *url.URL, error) {
var loginURL *url.URL
var wsURL *url.URL
if cfg.AuthURL != "" {
parsed, err := normalizeAuthURL(cfg.AuthURL)
if err != nil {
return nil, nil, err
}
loginURL = parsed
}
if cfg.WsURL != "" {
parsed, err := normalizeWsURL(cfg.WsURL)
if err != nil {
return nil, nil, err
}
wsURL = parsed
}
if (loginURL == nil || wsURL == nil) && cfg.Server != "" {
baseLoginURL, baseWsURL, err := buildRemoteURLs(cfg.Server)
if err != nil {
return nil, nil, err
}
if loginURL == nil {
loginURL = baseLoginURL
}
if wsURL == nil {
wsURL = baseWsURL
}
}
if loginURL == nil || wsURL == nil {
return nil, nil, fmt.Errorf("auth or ws address is missing")
}
return loginURL, wsURL, nil
}
func normalizeAuthURL(raw string) (*url.URL, error) {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return nil, fmt.Errorf("auth address is empty")
}
if !strings.Contains(trimmed, "://") {
trimmed = "http://" + trimmed
}
parsed, err := url.Parse(trimmed)
if err != nil {
return nil, err
}
if parsed.Host == "" {
return nil, fmt.Errorf("invalid auth address")
}
if parsed.Path == "" || parsed.Path == "/" {
parsed.Path = "/api/client/login"
}
switch parsed.Scheme {
case "ws":
parsed.Scheme = "http"
case "wss":
parsed.Scheme = "https"
}
return parsed, nil
}
func normalizeWsURL(raw string) (*url.URL, error) {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return nil, fmt.Errorf("ws address is empty")
}
if !strings.Contains(trimmed, "://") {
trimmed = "ws://" + trimmed
}
parsed, err := url.Parse(trimmed)
if err != nil {
return nil, err
}
if parsed.Host == "" {
return nil, fmt.Errorf("invalid ws address")
}
if parsed.Path == "" || parsed.Path == "/" {
parsed.Path = "/ws/client"
}
switch parsed.Scheme {
case "http":
parsed.Scheme = "ws"
case "https":
parsed.Scheme = "wss"
}
return parsed, nil
}
func normalizeRemoteBaseURL(raw string) (*url.URL, error) {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return nil, fmt.Errorf("remote server is empty")
}
if !strings.Contains(trimmed, "://") {
trimmed = "http://" + trimmed
}
parsed, err := url.Parse(trimmed)
if err != nil {
return nil, err
}
if parsed.Host == "" {
return nil, fmt.Errorf("invalid remote server address")
}
parsed.Path = strings.TrimRight(parsed.Path, "/")
parsed.RawQuery = ""
parsed.Fragment = ""
return parsed, nil
}
func (b *Bridge) setRemoteConn(conn *websocket.Conn) {
b.remoteMu.Lock()
b.remoteConn = conn
b.remoteMu.Unlock()
}
func (b *Bridge) clearRemoteConn(conn *websocket.Conn) {
b.remoteMu.Lock()
if b.remoteConn == conn {
b.remoteConn = nil
}
b.remoteMu.Unlock()
}
func (b *Bridge) setRemoteConnected(connected bool) {
b.remoteMu.Lock()
b.remoteStatus.Connected = connected
if connected {
b.remoteStatus.LastError = ""
}
b.remoteStatus.LastChange = time.Now().Unix()
b.remoteMu.Unlock()
}
func (b *Bridge) setRemoteError(err error) {
if err == nil {
return
}
b.remoteMu.Lock()
b.remoteStatus.LastError = err.Error()
b.remoteStatus.LastChange = time.Now().Unix()
b.remoteMu.Unlock()
}
func (b *Bridge) GetRemoteForwarderStatus() RemoteForwarderStatus {
b.remoteMu.Lock()
defer b.remoteMu.Unlock()
return b.remoteStatus
}

View File

@@ -0,0 +1,23 @@
# Vue 3 + TypeScript + Vite
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue
3 `<script setup>` SFCs, check out
the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
## Recommended IDE Setup
- [VS Code](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar)
## Type Support For `.vue` Imports in TS
Since TypeScript cannot handle type information for `.vue` imports, they are shimmed to be a generic Vue component type
by default. In most cases this is fine if you don't really care about component prop types outside of templates.
However, if you wish to get actual prop types in `.vue` imports (for example to get props validation when using
manual `h(...)` calls), you can enable Volar's Take Over mode by following these steps:
1. Run `Extensions: Show Built-in Extensions` from VS Code's command palette, look
for `TypeScript and JavaScript Language Features`, then right click and select `Disable (Workspace)`. By default,
Take Over mode will enable itself if the default TypeScript extension is disabled.
2. Reload the VS Code window by running `Developer: Reload Window` from the command palette.
You can learn more about Take Over mode [here](https://github.com/johnsoncodehk/volar/discussions/471).

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>XSL-PrintDot</title>
</head>
<body>
<div id="app"></div>
<script src="./src/main.ts" type="module"></script>
</body>
</html>

2419
XSLPrintDot/frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,30 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview"
},
"dependencies": {
"marked": "^17.0.1",
"vue": "^3.2.37",
"vue-i18n": "^9.14.5"
},
"devDependencies": {
"@babel/types": "^7.18.10",
"@iconify-json/material-symbols": "^1.2.53",
"@tailwindcss/postcss": "^4.1.18",
"@vitejs/plugin-vue": "^3.0.3",
"autoprefixer": "^10.4.24",
"postcss": "^8.5.6",
"tailwindcss": "^4.1.18",
"typescript": "^4.6.4",
"unplugin-icons": "^23.0.1",
"unplugin-vue-components": "^31.0.0",
"vite": "^3.0.7",
"vue-tsc": "^1.8.27"
}
}

View File

@@ -0,0 +1,6 @@
export default {
plugins: {
'@tailwindcss/postcss': {},
autoprefixer: {},
},
}

View File

@@ -0,0 +1,454 @@
<script lang="ts" setup>
import { reactive, ref, onMounted, onUnmounted, computed } from 'vue'
import { GetPrinters, StartServer, StopServer, GetAppMode, GetLogPort, GetSettings, SaveSettings } from '../wailsjs/go/main/App'
import { EventsOn } from '../wailsjs/runtime/runtime'
import Help from './components/Help.vue'
import Settings from './components/Settings.vue'
import { useI18n } from 'vue-i18n'
const { t, locale } = useI18n()
const appMode = ref('main')
const logPort = ref(0)
const logs = ref<string[]>([])
const clientCount = ref(0)
let logPollInterval: number | null = null
let forwarderStream: EventSource | null = null
let forwarderPoll: number | null = null
const config = reactive({
port: '1122',
key: ''
})
const persistServerSettings = async () => {
try {
const s = await GetSettings()
if (s) {
s.serverPort = config.port
s.serverKey = config.key
await SaveSettings(s)
}
} catch (e) {
console.error('Failed to save server settings', e)
}
}
const connectionUrl = computed(() => {
let url = `ws://localhost:${config.port}/ws`
if (config.key) {
url += `?key=${encodeURIComponent(config.key)}`
}
return url
})
const serverStatus = ref('Stopped')
type PrinterInfo = {
name: string
isDefault: boolean
}
const printers = ref<PrinterInfo[]>([])
const isLoadingPrinters = ref(false)
const refreshPrinters = async () => {
if (isLoadingPrinters.value) return
isLoadingPrinters.value = true
printers.value = []
const minDelay = new Promise((resolve) => setTimeout(resolve, 800))
try {
const [fetchedPrinters] = await Promise.all([
GetPrinters(),
minDelay
])
printers.value = fetchedPrinters.slice().sort((a, b) => {
if (a.isDefault !== b.isDefault) {
return a.isDefault ? -1 : 1
}
return a.name.localeCompare(b.name)
})
} catch (e) {
console.error(e)
} finally {
isLoadingPrinters.value = false
}
}
const toggleServer = async () => {
if (serverStatus.value === 'Running') {
try {
await StopServer()
serverStatus.value = 'Stopped'
} catch (e) {
console.error(e)
}
} else {
try {
await StartServer(config.port, config.key)
serverStatus.value = 'Running'
} catch (e) {
console.error(e)
}
}
}
type RemoteStatus = {
connected: boolean
lastError: string
lastChange: number
autoReconnect?: boolean
}
const remoteStatus = ref<RemoteStatus>({
connected: false,
lastError: '',
lastChange: 0
})
const isConnecting = ref(false)
const isDisconnecting = ref(false)
const forwarderVisible = ref(false)
const fetchLogs = async () => {
try {
const res = await fetch(`http://localhost:${logPort.value}/api/logs`)
if (res.ok) {
const data = await res.json()
logs.value = data.reverse()
}
} catch (e) {
console.error('Failed to fetch logs', e)
}
}
const clearAllLogs = async () => {
logs.value = []
try {
await fetch(`http://localhost:${logPort.value}/api/logs/clear`, { method: 'POST' })
} catch (e) {
console.error('Failed to clear logs', e)
}
}
const refreshRemoteStatus = async () => {
if (logPort.value <= 0) return
try {
const resp = await fetch(`http://localhost:${logPort.value}/api/forwarder/status`)
if (resp.ok) {
remoteStatus.value = await resp.json()
}
} catch (e) {
console.error('Failed to fetch forwarder status', e)
}
}
const updateForwarderVisibility = (settings: any) => {
if (!settings) {
forwarderVisible.value = false
return
}
const auth = (settings.remoteAuthUrl || '').trim()
const ws = (settings.remoteWsUrl || '').trim()
const clientId = (settings.remoteClientId || '').trim()
const secret = (settings.remoteSecretKey || '').trim()
forwarderVisible.value = auth !== '' && ws !== '' && clientId !== '' && secret !== ''
}
const connectForwarder = async () => {
if (isConnecting.value || remoteStatus.value.connected || logPort.value <= 0) return
isConnecting.value = true
try {
await fetch(`http://localhost:${logPort.value}/api/forwarder/connect`, { method: 'POST' })
} catch (e) {
console.error('Failed to connect forwarder', e)
} finally {
isConnecting.value = false
}
}
const disconnectForwarder = async () => {
if (isDisconnecting.value || !remoteStatus.value.connected || logPort.value <= 0) return
isDisconnecting.value = true
try {
const s = await GetSettings()
if (s) {
s.remoteAutoConnect = false
await SaveSettings(s)
}
await fetch(`http://localhost:${logPort.value}/api/forwarder/disconnect`, { method: 'POST' })
await fetch(`http://localhost:${logPort.value}/api/reload`, { method: 'POST' })
} catch (e) {
console.error('Failed to disconnect forwarder', e)
} finally {
isDisconnecting.value = false
}
}
onMounted(async () => {
appMode.value = await GetAppMode()
// Load settings for language
try {
const s = await GetSettings()
if (s && s.language) {
locale.value = s.language
}
} catch (e) {
console.error("Failed to load settings", e)
}
if (appMode.value === "logs") {
logPort.value = await GetLogPort()
fetchLogs()
logPollInterval = setInterval(fetchLogs, 1000)
} else if (appMode.value === "main") {
// Main mode
logPort.value = await GetLogPort()
try {
const s = await GetSettings()
if (s) {
config.port = s.serverPort || config.port
config.key = s.serverKey || ''
updateForwarderVisibility(s)
}
} catch (e) {
console.error('Failed to load server settings', e)
}
await refreshPrinters()
await toggleServer()
await refreshRemoteStatus()
if (logPort.value > 0 && 'EventSource' in window) {
forwarderStream = new EventSource(`http://localhost:${logPort.value}/api/forwarder/stream`)
forwarderStream.onmessage = (event) => {
try {
remoteStatus.value = JSON.parse(event.data)
} catch (e) {
console.error(e)
}
}
forwarderStream.onerror = () => {
if (forwarderStream) {
forwarderStream.close()
forwarderStream = null
}
if (forwarderPoll === null) {
forwarderPoll = window.setInterval(refreshRemoteStatus, 3000)
}
}
} else {
forwarderPoll = window.setInterval(refreshRemoteStatus, 3000)
}
// Listen for client count updates
EventsOn("client_count", (count: number) => {
clientCount.value = count
})
// Listen for settings reload
EventsOn("reload_settings", async () => {
try {
const s = await GetSettings()
if (s && s.language) {
locale.value = s.language
}
if (s) {
config.port = s.serverPort || config.port
config.key = s.serverKey || ''
updateForwarderVisibility(s)
}
} catch (e) {
console.error("Failed to reload settings", e)
}
})
}
})
onUnmounted(() => {
if (logPollInterval) clearInterval(logPollInterval)
if (forwarderPoll !== null) {
window.clearInterval(forwarderPoll)
forwarderPoll = null
}
if (forwarderStream) {
forwarderStream.close()
forwarderStream = null
}
})
</script>
<template>
<Help v-if="appMode === 'help'" />
<Settings v-else-if="appMode === 'settings'" />
<div v-else class="h-screen w-screen overflow-hidden bg-white text-gray-900 font-sans text-left flex flex-col relative">
<!-- Content Area -->
<div class="flex-1 overflow-hidden relative">
<!-- LOGS MODE UI -->
<div v-if="appMode === 'logs'" class="w-full h-full flex flex-col">
<header class="p-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center">
<div>
<h1 class="text-xl font-bold text-gray-800 mb-1 flex items-center gap-2">
<i-material-symbols-terminal class="text-gray-700" />
{{ t('logs.title') }}
</h1>
<p class="text-xs text-gray-500">{{ t('logs.subtitle') }}</p>
</div>
<button @click="clearAllLogs" class="text-xs text-red-600 hover:bg-red-50 px-3 py-1.5 border border-red-200 rounded-md transition-colors flex items-center gap-1">
<i-material-symbols-delete-outline />
{{ t('logs.clearAll') }}
</button>
</header>
<div class="flex-1 bg-gray-900 text-gray-300 p-4 font-mono text-xs overflow-y-auto scrollbar-thin scrollbar-thumb-gray-700 scrollbar-track-transparent">
<div v-for="(log, i) in logs" :key="i" class="border-b border-gray-800 last:border-0 pb-1 mb-1 break-words hover:bg-gray-800/50">
{{ log }}
</div>
<div v-if="logs.length === 0" class="text-gray-600 italic py-4 text-center">{{ t('logs.empty') }}</div>
</div>
</div>
<!-- MAIN APP UI -->
<div v-else class="w-full h-full flex flex-col">
<!-- Header -->
<header
class="p-4 border-b border-gray-200 flex-none transition-colors duration-300"
:class="clientCount > 0 ? 'bg-green-600 text-white' : 'bg-gray-50 text-gray-900'"
>
<div class="flex justify-between items-center">
<div>
<h1 class="text-xl font-bold mb-1 flex items-center gap-2">
<i-material-symbols-print-connect :class="clientCount > 0 ? 'text-white' : 'text-blue-600'" />
{{ t('main.title') }}
</h1>
<p class="text-xs" :class="clientCount > 0 ? 'text-green-100' : 'text-gray-500'">
{{ t('main.subtitle') }}
</p>
</div>
<!-- Client Count Badge -->
<div
class="flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-bold transition-all"
:class="clientCount > 0 ? 'bg-white text-green-700 shadow-sm' : 'bg-gray-200 text-gray-600'"
>
<i-material-symbols-devices />
<span>{{ clientCount }} {{ t('main.clients') }}</span>
</div>
</div>
</header>
<div class="flex-1 overflow-y-auto scrollbar-hide">
<!-- Server Control -->
<div class="p-4 border-b border-gray-200">
<h2 class="text-base font-semibold mb-4 flex items-center gap-2">
<i-material-symbols-dns class="text-gray-600" />
<span class="w-2.5 h-2.5 rounded-full" :class="serverStatus === 'Running' ? 'bg-green-500' : 'bg-red-500'"></span>
{{ t('main.serverControl') }}
</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">{{ t('main.port') }}</label>
<input v-model="config.port" @change="persistServerSettings" type="text" class="w-full bg-white border border-gray-300 px-3 py-2 text-sm text-gray-800 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all rounded-md" :disabled="serverStatus === 'Running'" />
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">{{ t('main.secretKey') }}</label>
<input v-model="config.key" @change="persistServerSettings" type="password" class="w-full bg-white border border-gray-300 px-3 py-2 text-sm text-gray-800 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all rounded-md" :disabled="serverStatus === 'Running'" :placeholder="t('main.placeholderKey')" />
</div>
</div>
<button
@click="toggleServer"
class="w-full py-2 px-4 font-semibold text-white transition-all active:opacity-90 rounded-md flex items-center justify-center gap-2"
:class="serverStatus === 'Running' ? 'bg-red-500 hover:bg-red-600' : 'bg-blue-600 hover:bg-blue-700'"
>
<i-material-symbols-stop v-if="serverStatus === 'Running'" />
<i-material-symbols-play-arrow v-else />
{{ serverStatus === 'Running' ? t('main.stopServer') : t('main.startServer') }}
</button>
<div class="mt-4 p-3 bg-gray-50 border border-gray-200 rounded-md">
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">{{ t('main.connectionUrl') }}</label>
<div class="flex items-center gap-2">
<code class="flex-1 bg-white border border-gray-300 px-2 py-1.5 text-xs text-gray-600 rounded select-all font-mono break-all">
{{ connectionUrl }}
</code>
</div>
</div>
</div>
<!-- Forwarder -->
<div v-if="forwarderVisible" class="p-4 border-t border-gray-200">
<h2 class="text-base font-semibold mb-4 flex items-center gap-2">
<i-material-symbols-cloud-sync class="text-gray-600" />
<span class="w-2.5 h-2.5 rounded-full" :class="remoteStatus.connected ? 'bg-green-500' : 'bg-red-500'"></span>
{{ t('settings.forwarding') }}
</h2>
<button
@click="remoteStatus.connected ? disconnectForwarder() : connectForwarder()"
:disabled="isConnecting || isDisconnecting"
class="w-full py-2 px-4 font-semibold rounded-md transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
:class="remoteStatus.connected ? 'bg-red-500 hover:bg-red-600 text-white' : 'bg-blue-600 hover:bg-blue-700 text-white'"
>
<i-material-symbols-stop v-if="remoteStatus.connected" />
<i-material-symbols-play-arrow v-else />
{{ remoteStatus.connected ? (isDisconnecting ? t('settings.disconnecting') : t('settings.disconnect')) : (isConnecting ? t('settings.connecting') : t('settings.connect')) }}
</button>
<p v-if="remoteStatus.lastError" class="text-xs text-red-500 mt-2">
<span class="font-medium">{{ t('settings.lastError') }}:</span>
<span class="break-words">{{ remoteStatus.lastError }}</span>
</p>
</div>
<!-- Printers -->
<div class="p-4 border-t border-gray-200">
<div class="flex justify-between items-center mb-4">
<h2 class="text-base font-semibold text-gray-800 flex items-center gap-2">
<i-material-symbols-print class="text-gray-600" />
{{ t('main.availablePrinters') }}
</h2>
<button
@click="refreshPrinters"
class="text-xs bg-gray-100 hover:bg-gray-200 text-blue-600 px-3 py-1.5 border border-gray-200 transition-colors rounded-md flex items-center gap-1"
:disabled="isLoadingPrinters"
>
<i-material-symbols-refresh :class="{ 'animate-spin': isLoadingPrinters }" />
{{ t('main.refresh') }}
</button>
</div>
<div v-if="isLoadingPrinters" class="text-gray-500 italic text-center py-6 bg-gray-50 border border-dashed border-gray-200 flex flex-col items-center gap-2">
<span>{{ t('main.loading') }}</span>
</div>
<div v-else-if="printers.length === 0" class="text-gray-400 italic text-center py-6 bg-gray-50 border border-dashed border-gray-200">
{{ t('main.noPrinters') }}
</div>
<ul v-else class="grid grid-cols-1 gap-0 border border-gray-200 divide-y divide-gray-200">
<li v-for="p in printers" :key="p.name" class="px-3 py-2 flex items-center gap-2 hover:bg-gray-50 transition-colors text-sm bg-white">
<i-material-symbols-print class="text-lg opacity-70 text-gray-500" />
<span class="font-medium truncate text-gray-700" :title="p.name">{{ p.name }}</span>
<span v-if="p.isDefault" class="ml-auto text-[10px] px-2 py-0.5 rounded-full bg-blue-50 text-blue-700 border border-blue-100">
{{ t('main.defaultPrinter') }}
</span>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</template>
<style>
/* Reset some Wails default styles if needed */
body {
margin: 0;
background-color: #f9fafb; /* gray-50 */
}
</style>

View File

@@ -0,0 +1,93 @@
Copyright 2016 The Nunito Project Authors (contact@sansoxygen.com),
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

View File

@@ -0,0 +1,70 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { GetUsageGuide } from '../../wailsjs/go/main/App'
import { marked } from 'marked'
const content = ref('')
onMounted(async () => {
try {
const markdown = await GetUsageGuide()
content.value = await marked.parse(markdown)
} catch (e) {
console.error(e)
content.value = '<p class="text-red-500">Failed to load usage guide.</p>'
}
})
</script>
<template>
<div class="h-screen w-screen bg-white flex flex-col">
<div class="flex-1 overflow-y-auto p-8 prose prose-sm max-w-none prose-slate">
<div v-html="content"></div>
</div>
</div>
</template>
<style>
@reference "tailwindcss";
/* Add some basic markdown styling overrides if needed */
.prose h1 {
@apply text-2xl font-bold mb-4 pb-2 border-b border-gray-200 text-gray-800;
}
.prose h2 {
@apply text-xl font-bold mt-6 mb-3 text-gray-800;
}
.prose h3 {
@apply text-lg font-bold mt-4 mb-2 text-gray-800;
}
.prose p {
@apply mb-4 leading-relaxed text-gray-600;
}
.prose ul {
@apply list-disc list-inside mb-4 pl-4 text-gray-600;
}
.prose code {
@apply bg-gray-100 px-1 py-0.5 rounded text-sm font-mono text-pink-600;
}
.prose pre {
@apply bg-gray-900 text-gray-100 p-4 rounded-md overflow-x-auto mb-4 text-sm font-mono;
}
.prose pre code {
@apply bg-transparent p-0 text-gray-100;
}
.prose table {
@apply min-w-full border-collapse border border-gray-300 mb-4;
}
.prose thead {
@apply bg-gray-100;
}
.prose th {
@apply border border-gray-300 px-4 py-2 text-left font-semibold text-gray-700;
}
.prose td {
@apply border border-gray-300 px-4 py-2 text-gray-600;
}
.prose tr:nth-child(even) {
@apply bg-gray-50;
}
</style>

View File

@@ -0,0 +1,338 @@
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { GetSettings, SaveSettings, Restart, GetLogPort, GetRemoteForwarderStatus, DisconnectRemoteForwarder, ConnectRemoteForwarder } from '../../wailsjs/go/main/App'
import { main } from '../../wailsjs/go/models'
const { t, locale } = useI18n()
const settings = ref(new main.AppSettings({
language: 'zh-CN',
autoStart: false,
remoteAutoConnect: true,
remoteServer: '',
remoteAuthUrl: '',
remoteWsUrl: '',
remoteClientId: '',
remoteSecretKey: '',
remoteClientName: '',
windowWidth: 0,
windowHeight: 0,
windowX: 0,
windowY: 0,
maximized: false
}))
const logPort = ref(0)
const isConnecting = ref(false)
const isDisconnecting = ref(false)
const isSyncing = ref(false)
const hasLoaded = ref(false)
let autoSaveTimer: number | null = null
type RemoteStatus = {
connected: boolean
lastError: string
lastChange: number
autoReconnect?: boolean
}
const remoteStatus = ref<RemoteStatus>({
connected: false,
lastError: '',
lastChange: 0
})
let remoteStatusTimer: number | null = null
let remoteStatusStream: EventSource | null = null
const refreshRemoteStatus = async () => {
try {
if (logPort.value > 0) {
const resp = await fetch(`http://localhost:${logPort.value}/api/forwarder/status`)
if (resp.ok) {
remoteStatus.value = await resp.json()
if (typeof remoteStatus.value.autoReconnect === 'boolean') {
setSettingsSilently(() => {
settings.value.remoteAutoConnect = remoteStatus.value.autoReconnect as boolean
})
}
return
}
}
remoteStatus.value = await GetRemoteForwarderStatus()
if (typeof remoteStatus.value.autoReconnect === 'boolean') {
setSettingsSilently(() => {
settings.value.remoteAutoConnect = remoteStatus.value.autoReconnect as boolean
})
}
} catch (e) {
console.error(e)
}
}
const setSettingsSilently = (update: () => void) => {
isSyncing.value = true
try {
update()
} finally {
isSyncing.value = false
}
}
onMounted(async () => {
try {
const s = await GetSettings()
setSettingsSilently(() => {
settings.value = s
locale.value = s.language
})
logPort.value = await GetLogPort()
await refreshRemoteStatus()
if (logPort.value > 0 && 'EventSource' in window) {
remoteStatusStream = new EventSource(`http://localhost:${logPort.value}/api/forwarder/stream`)
remoteStatusStream.onmessage = (event) => {
try {
remoteStatus.value = JSON.parse(event.data)
if (typeof remoteStatus.value.autoReconnect === 'boolean') {
settings.value.remoteAutoConnect = remoteStatus.value.autoReconnect
}
} catch (e) {
console.error(e)
}
}
remoteStatusStream.onerror = () => {
if (remoteStatusStream) {
remoteStatusStream.close()
remoteStatusStream = null
}
if (remoteStatusTimer === null) {
remoteStatusTimer = window.setInterval(refreshRemoteStatus, 3000)
}
}
} else {
remoteStatusTimer = window.setInterval(refreshRemoteStatus, 3000)
}
} catch (e) {
console.error(e)
}
hasLoaded.value = true
})
onBeforeUnmount(() => {
if (remoteStatusTimer !== null) {
window.clearInterval(remoteStatusTimer)
remoteStatusTimer = null
}
if (autoSaveTimer !== null) {
window.clearTimeout(autoSaveTimer)
autoSaveTimer = null
}
if (remoteStatusStream) {
remoteStatusStream.close()
remoteStatusStream = null
}
})
const isSaving = ref(false)
const saveSettings = async () => {
if (isSaving.value) return
isSaving.value = true
try {
// Save settings
await SaveSettings(settings.value)
// Update locale immediately in this window
locale.value = settings.value.language
// Notify main process to reload settings
try {
if (logPort.value > 0) {
await fetch(`http://localhost:${logPort.value}/api/reload`, { method: 'POST' })
}
} catch (e) {
console.log("Main process reload trigger failed", e)
}
} catch (e) {
console.error(e)
} finally {
isSaving.value = false
}
}
watch(settings, () => {
if (isSyncing.value || !hasLoaded.value) return
if (autoSaveTimer !== null) {
window.clearTimeout(autoSaveTimer)
}
autoSaveTimer = window.setTimeout(() => {
saveSettings()
}, 400)
}, { deep: true })
const disconnectRemote = async () => {
if (isDisconnecting.value || !remoteStatus.value.connected) return
isDisconnecting.value = true
try {
settings.value.remoteAutoConnect = false
remoteStatus.value.autoReconnect = false
await saveSettings()
if (logPort.value > 0) {
await fetch(`http://localhost:${logPort.value}/api/forwarder/disconnect`, { method: 'POST' })
} else {
await DisconnectRemoteForwarder()
}
await refreshRemoteStatus()
} catch (e) {
console.error(e)
} finally {
isDisconnecting.value = false
}
}
const connectRemote = async () => {
if (isConnecting.value || remoteStatus.value.connected) return
isConnecting.value = true
try {
if (logPort.value > 0) {
await fetch(`http://localhost:${logPort.value}/api/forwarder/connect`, { method: 'POST' })
} else {
await ConnectRemoteForwarder()
}
await refreshRemoteStatus()
} catch (e) {
console.error(e)
} finally {
isConnecting.value = false
}
}
const toggleRemote = async () => {
if (remoteStatus.value.connected) {
await disconnectRemote()
} else {
await connectRemote()
}
}
</script>
<template>
<div class="h-screen w-screen bg-gray-50 flex flex-col p-4 relative">
<h1 class="text-2xl font-bold mb-6 text-gray-800 flex items-center gap-2">
<i-material-symbols-settings-outline />
{{ t('settings.title') }}
</h1>
<div class="space-y-6 flex-1 overflow-y-auto">
<!-- Language -->
<div class="bg-white p-4 rounded-lg border border-gray-200 shadow-sm">
<label class="block text-sm font-medium text-gray-700 mb-2 flex items-center gap-2">
<i-material-symbols-language class="text-gray-500" />
{{ t('settings.language') }}
</label>
<select v-model="settings.language" class="w-full border border-gray-300 rounded-md p-2 text-sm focus:ring-blue-500 focus:border-blue-500">
<option value="zh-CN">简体中文</option>
<option value="en">English</option>
</select>
</div>
<!-- Auto Start -->
<div class="bg-white p-4 rounded-lg border border-gray-200 shadow-sm flex items-center justify-between">
<label class="text-sm font-medium text-gray-700 flex items-center gap-2">
<i-material-symbols-power class="text-gray-500" />
{{ t('settings.autoStart') }}
</label>
<label class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" v-model="settings.autoStart" class="sr-only peer">
<div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
</label>
</div>
<!-- Forwarding Service -->
<div class="bg-white p-4 rounded-lg border border-gray-200 shadow-sm space-y-4">
<h3 class="text-sm font-semibold text-gray-800 border-b border-gray-100 pb-2 flex items-center gap-2">
<i-material-symbols-cloud-sync class="text-gray-600" />
<span class="w-2.5 h-2.5 rounded-full" :class="remoteStatus.connected ? 'bg-green-500' : 'bg-red-500'"></span>
{{ t('settings.forwarding') }}
</h3>
<div class="flex items-center justify-between">
<label class="text-sm font-medium text-gray-700 flex items-center gap-2">
<i-material-symbols-sync class="text-gray-500" />
{{ t('settings.autoConnect') }}
</label>
<label class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" v-model="settings.remoteAutoConnect" class="sr-only peer">
<div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
</label>
</div>
<div>
<button
@click="toggleRemote"
:disabled="isConnecting || isDisconnecting"
class="w-full py-2 px-4 font-semibold rounded-md shadow-sm transition-colors duration-200 text-sm disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
:class="remoteStatus.connected ? 'bg-red-500 hover:bg-red-600 text-white' : 'bg-blue-600 hover:bg-blue-700 text-white'"
>
<i-material-symbols-stop v-if="remoteStatus.connected" />
<i-material-symbols-play-arrow v-else />
{{ remoteStatus.connected ? (isDisconnecting ? t('settings.disconnecting') : t('settings.disconnect')) : (isConnecting ? t('settings.connecting') : t('settings.connect')) }}
</button>
</div>
<p v-if="remoteStatus.lastError" class="text-xs text-red-500">
<span class="font-medium">{{ t('settings.lastError') }}:</span>
<span class="break-words">{{ remoteStatus.lastError }}</span>
</p>
<div>
<label class="block text-xs font-medium text-gray-500 mb-1 flex items-center gap-1">
<i-material-symbols-lock-outline class="text-gray-400" />
{{ t('settings.authAddress') }}
</label>
<input v-model="settings.remoteAuthUrl" type="text" class="w-full border border-gray-300 rounded-md p-2 text-sm focus:ring-blue-500 focus:border-blue-500" placeholder="http://server:8080/api/client/login" />
</div>
<div>
<label class="block text-xs font-medium text-gray-500 mb-1 flex items-center gap-1">
<i-material-symbols-link class="text-gray-400" />
{{ t('settings.wsAddress') }}
</label>
<input v-model="settings.remoteWsUrl" type="text" class="w-full border border-gray-300 rounded-md p-2 text-sm focus:ring-blue-500 focus:border-blue-500" placeholder="ws://server:8081/ws/client" />
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-xs font-medium text-gray-500 mb-1 flex items-center gap-1">
<i-material-symbols-badge class="text-gray-400" />
{{ t('settings.clientId') }}
</label>
<input v-model="settings.remoteClientId" type="text" disabled class="w-full border border-gray-200 bg-gray-100 text-gray-500 rounded-md p-2 text-sm cursor-not-allowed" :title="t('settings.deviceIdReadonly')" />
<p class="text-[11px] text-gray-400 mt-1">{{ t('settings.deviceIdReadonly') }}</p>
</div>
<div>
<label class="block text-xs font-medium text-gray-500 mb-1 flex items-center gap-1">
<i-material-symbols-key class="text-gray-400" />
{{ t('settings.secretKey') }}
</label>
<input v-model="settings.remoteSecretKey" type="password" class="w-full border border-gray-300 rounded-md p-2 text-sm focus:ring-blue-500 focus:border-blue-500" />
</div>
</div>
<div>
<label class="block text-xs font-medium text-gray-500 mb-1 flex items-center gap-1">
<i-material-symbols-badge class="text-gray-400" />
{{ t('settings.clientName') }}
</label>
<input v-model="settings.remoteClientName" type="text" class="w-full border border-gray-300 rounded-md p-2 text-sm focus:ring-blue-500 focus:border-blue-500" />
</div>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,15 @@
import { createI18n } from 'vue-i18n'
import en from './locales/en.json'
import zh from './locales/zh.json'
const i18n = createI18n({
legacy: false,
locale: 'zh-CN', // default locale
fallbackLocale: 'en',
messages: {
'en': en,
'zh-CN': zh
}
})
export default i18n

View File

@@ -0,0 +1,58 @@
{
"settings": {
"title": "Settings",
"language": "Language",
"autoStart": "Start on Boot",
"remotePrint": "Remote Print Server",
"forwarding": "Cloud Print Forwarder",
"serverAddress": "Server Address",
"authAddress": "Auth Address",
"wsAddress": "WS Address",
"autoConnect": "Auto Reconnect",
"username": "Username",
"password": "Password",
"clientId": "Client ID",
"secretKey": "Secret Key",
"clientName": "Client Name (Optional)",
"deviceIdReadonly": "Device ID is auto-detected and cannot be edited",
"forwarderStatus": "Connection Status",
"connected": "Connected",
"disconnected": "Disconnected",
"connect": "Connect",
"connecting": "Connecting...",
"disconnect": "Disconnect",
"disconnecting": "Disconnecting...",
"lastError": "Last Error",
"save": "Save Settings",
"saving": "Saving...",
"saved": "Saved",
"restart": "Restart Now",
"confirmRestart": "Restart Required",
"confirmRestartMessage": "Applying these settings requires a restart. Do you want to restart now?",
"cancel": "Cancel"
},
"main": {
"title": "XSL-PrintDot",
"subtitle": "WebSocket Printer Bridge",
"clients": "connections",
"serverControl": "Server Control",
"port": "Port",
"secretKey": "Secret Key (Optional)",
"placeholderKey": "Leave empty for no auth",
"startServer": "Start Server",
"stopServer": "Stop Server",
"connectionUrl": "Connection URL",
"availablePrinters": "Available Printers",
"defaultPrinter": "Default",
"refresh": "Refresh",
"loading": "Loading...",
"noPrinters": "No printers found.",
"clientConnected": "Client Connected"
},
"logs": {
"title": "System Logs",
"subtitle": "Live system events",
"clearAll": "Clear All",
"empty": "No logs available yet..."
}
}

View File

@@ -0,0 +1,58 @@
{
"settings": {
"title": "设置",
"language": "语言",
"autoStart": "开机自启动",
"remotePrint": "远程打印服务器",
"forwarding": "云打印中转服务",
"serverAddress": "服务器地址",
"authAddress": "鉴权地址",
"wsAddress": "WS地址",
"autoConnect": "自动重连",
"username": "用户名",
"password": "密码",
"clientId": "客户端ID",
"secretKey": "密钥",
"clientName": "客户端名称(可选)",
"deviceIdReadonly": "设备ID自动获取无法修改",
"forwarderStatus": "连接状态",
"connected": "已连接",
"disconnected": "未连接",
"connect": "连接",
"connecting": "连接中...",
"disconnect": "断开",
"disconnecting": "断开中...",
"lastError": "最近错误",
"save": "保存",
"saving": "保存中...",
"saved": "已保存",
"restart": "立即重启",
"confirmRestart": "需要重启",
"confirmRestartMessage": "应用这些设置需要重启程序。是否立即重启?",
"cancel": "取消"
},
"main": {
"title": "XSL-PrintDot",
"subtitle": "WebSocket 打印桥接器",
"clients": "个连接",
"serverControl": "服务控制",
"port": "端口",
"secretKey": "密钥 (可选)",
"placeholderKey": "留空则无需认证",
"startServer": "启动服务",
"stopServer": "停止服务",
"connectionUrl": "连接地址",
"availablePrinters": "可用打印机",
"defaultPrinter": "默认",
"refresh": "刷新",
"loading": "加载中...",
"noPrinters": "未找到打印机",
"clientConnected": "客户端已连接"
},
"logs": {
"title": "系统日志",
"subtitle": "实时系统事件",
"clearAll": "清除所有",
"empty": "暂无日志..."
}
}

View File

@@ -0,0 +1,6 @@
import {createApp} from 'vue'
import App from './App.vue'
import './style.css';
import i18n from './i18n'
createApp(App).use(i18n).mount('#app')

View File

@@ -0,0 +1,42 @@
@import "tailwindcss";
html {
background-color: white;
/* text-align: center; Removed to fix left alignment issues */
color: #1a202c;
overflow: hidden; /* Prevent window scrollbar */
}
body {
margin: 0;
color: #1a202c;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
"Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
overflow: hidden; /* Prevent body scrollbar */
}
/* Hide scrollbar for Chrome, Safari and Opera */
::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE, Edge and Firefox */
html, body, #app {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
@font-face {
font-family: "Nunito";
font-style: normal;
font-weight: 400;
src: local(""),
url("assets/fonts/nunito-v16-latin-regular.woff2") format("woff2");
}
#app {
height: 100vh;
/* text-align: center; Removed to fix left alignment issues */
}

View File

@@ -0,0 +1,7 @@
/// <reference types="vite/client" />
declare module '*.vue' {
import type {DefineComponent} from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}

View File

@@ -0,0 +1,11 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}

View File

@@ -0,0 +1,30 @@
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": [
"ESNext",
"DOM"
],
"skipLibCheck": true
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue"
],
"references": [
{
"path": "./tsconfig.node.json"
}
]
}

View File

@@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "Node",
"allowSyntheticDefaultImports": true
},
"include": [
"vite.config.ts"
]
}

View File

@@ -0,0 +1,23 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Icons from 'unplugin-icons/vite'
import Components from 'unplugin-vue-components/vite'
import IconsResolver from 'unplugin-icons/resolver'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
Components({
resolvers: [
IconsResolver({
prefix: 'i', // Prefix for components, e.g. <i-material-symbols-print />
enabledCollections: ['material-symbols']
})
]
}),
Icons({
autoInstall: true
})
]
})

44
XSLPrintDot/go.mod Normal file
View File

@@ -0,0 +1,44 @@
module print-dot-client
go 1.24.0
require (
github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21
github.com/energye/systray v1.0.3
github.com/gorilla/websocket v1.5.3
github.com/wailsapp/wails/v2 v2.12.0
golang.org/x/sys v0.40.0
)
require (
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 // indirect
github.com/bep/debounce v1.2.1 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e // indirect
github.com/labstack/echo/v4 v4.13.3 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/leaanthony/go-ansi-parser v1.6.1 // indirect
github.com/leaanthony/gosod v1.0.4 // indirect
github.com/leaanthony/slicer v1.6.0 // indirect
github.com/leaanthony/u v1.1.1 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/onsi/ginkgo v1.16.5 // indirect
github.com/onsi/gomega v1.39.1 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/samber/lo v1.49.1 // indirect
github.com/tkrajina/go-reflector v0.5.8 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/wailsapp/go-webview2 v1.0.22 // indirect
github.com/wailsapp/mimetype v1.4.1 // indirect
golang.org/x/crypto v0.47.0 // indirect
golang.org/x/net v0.49.0 // indirect
golang.org/x/text v0.33.0 // indirect
)
// replace github.com/wailsapp/wails/v2 v2.11.0 => C:\Users\admin\go\pkg\mod

164
XSLPrintDot/go.sum Normal file
View File

@@ -0,0 +1,164 @@
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 h1:N3IGoHHp9pb6mj1cbXbuaSXV/UMKwmbKLf53nQmtqMA=
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3/go.mod h1:QtOLZGz8olr4qH2vWK0QH0w0O4T9fEIjMuWpKUsH7nc=
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21 h1:tuijfIjZyjZaHq9xDUh0tNitwXshJpbLkqMOJv4H3do=
github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21/go.mod h1:po7NpZ/QiTKzBKyrsEAxwnTamCoh8uDk/egRpQ7siIc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/energye/systray v1.0.3 h1:XnyjJCeRU5z00bpNOic2fGTKz/7yHZMZjWiGIVXDS+4=
github.com/energye/systray v1.0.3/go.mod h1:HelKhC3PXwv3ryDxbuQqV+7kAxAYNzE5cfdrerGOZTc=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e h1:Q3+PugElBCf4PFpxhErSzU3/PY5sFL5Z6rfv4AbGAck=
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
github.com/labstack/echo/v4 v4.13.3 h1:pwhpCPrTl5qry5HRdM5FwdXnhXSLSY+WE+YQSeCaafY=
github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/leaanthony/debme v1.2.1 h1:9Tgwf+kjcrbMQ4WnPcEIUcQuIZYqdWftzZkBr+i/oOc=
github.com/leaanthony/debme v1.2.1/go.mod h1:3V+sCm5tYAgQymvSOfYQ5Xx2JCr+OXiD9Jkw3otUjiA=
github.com/leaanthony/go-ansi-parser v1.6.1 h1:xd8bzARK3dErqkPFtoF9F3/HgN8UQk0ed1YDKpEz01A=
github.com/leaanthony/go-ansi-parser v1.6.1/go.mod h1:+vva/2y4alzVmmIEpk9QDhA7vLC5zKDTRwfZGOp3IWU=
github.com/leaanthony/gosod v1.0.4 h1:YLAbVyd591MRffDgxUOU1NwLhT9T1/YiwjKZpkNFeaI=
github.com/leaanthony/gosod v1.0.4/go.mod h1:GKuIL0zzPj3O1SdWQOdgURSuhkF+Urizzxh26t9f1cw=
github.com/leaanthony/slicer v1.6.0 h1:1RFP5uiPJvT93TAHi+ipd3NACobkW53yUiBqZheE/Js=
github.com/leaanthony/slicer v1.6.0/go.mod h1:o/Iz29g7LN0GqH3aMjWAe90381nyZlDNquK+mtH2Fj8=
github.com/leaanthony/u v1.1.1 h1:TUFjwDGlNX+WuwVEzDqQwC2lOv0P4uhTQw7CMFdiK7M=
github.com/leaanthony/u v1.1.1/go.mod h1:9+o6hejoRljvZ3BzdYlVL0JYCwtnAsVuN9pVTQcaRfI=
github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ=
github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28=
github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/samber/lo v1.49.1 h1:4BIFyVfuQSEpluc7Fua+j1NolZHiEHEpaSEKdsH0tew=
github.com/samber/lo v1.49.1/go.mod h1:dO6KHFzUKXgP8LDhU0oI8d2hekjXnGOu0DB8Jecxd6o=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ=
github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/wailsapp/go-webview2 v1.0.22 h1:YT61F5lj+GGaat5OB96Aa3b4QA+mybD0Ggq6NZijQ58=
github.com/wailsapp/go-webview2 v1.0.22/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc=
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
github.com/wailsapp/wails/v2 v2.12.0 h1:BHO/kLNWFHYjCzucxbzAYZWUjub1Tvb4cSguQozHn5c=
github.com/wailsapp/wails/v2 v2.12.0/go.mod h1:mo1bzK1DEJrobt7YrBjgxvb5Sihb1mhAY09hppbibQg=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

84
XSLPrintDot/i18n.go Normal file
View File

@@ -0,0 +1,84 @@
package main
import (
"embed"
"encoding/json"
"fmt"
"strings"
"sync"
)
//go:embed locales/*.json
var localeFS embed.FS
var (
translations map[string]interface{}
i18nMu sync.RWMutex
)
// LoadLocales loads the locale file based on the language code
func LoadLocales(lang string) error {
i18nMu.Lock()
defer i18nMu.Unlock()
// Map generic codes to file names
filename := "locales/en.json"
if lang == "zh-CN" || lang == "zh" {
filename = "locales/zh.json"
}
content, err := localeFS.ReadFile(filename)
if err != nil {
// Fallback to en if specific locale fails
if filename != "locales/en.json" {
content, err = localeFS.ReadFile("locales/en.json")
if err != nil {
return err
}
} else {
return err
}
}
var data map[string]interface{}
if err := json.Unmarshal(content, &data); err != nil {
return err
}
translations = data
return nil
}
// T translates a key. Nested keys can be accessed with dot notation (e.g., "menu.title")
func T(key string, args ...interface{}) string {
i18nMu.RLock()
defer i18nMu.RUnlock()
if translations == nil {
return key
}
keys := strings.Split(key, ".")
var val interface{} = translations
for _, k := range keys {
if m, ok := val.(map[string]interface{}); ok {
if v, exists := m[k]; exists {
val = v
} else {
return key
}
} else {
return key
}
}
if str, ok := val.(string); ok {
if len(args) > 0 {
return fmt.Sprintf(str, args...)
}
return str
}
return key
}

View File

@@ -0,0 +1,25 @@
{
"menu": {
"title": "Menu",
"settings": "Settings",
"logs": "System Logs",
"help": "Help",
"quit": "Quit"
},
"tray": {
"show": "Show Main Window",
"quit": "Quit",
"title": "XSL-PrintDot",
"tooltip": "XSL-PrintDot"
},
"window": {
"logs": "System Logs",
"help": "Help - Usage Guide",
"settings": "Settings",
"main": "XSL-PrintDot"
},
"notification": {
"title": "XSL-PrintDot",
"connected": "Client connected: %s"
}
}

View File

@@ -0,0 +1,25 @@
{
"menu": {
"title": "菜单",
"settings": "设置",
"logs": "系统日志",
"help": "帮助",
"quit": "退出"
},
"tray": {
"show": "显示主窗口",
"quit": "退出",
"title": "XSL-PrintDot",
"tooltip": "XSL-PrintDot"
},
"window": {
"logs": "系统日志",
"help": "帮助 - 使用指南",
"settings": "设置",
"main": "XSL-PrintDot"
},
"notification": {
"title": "XSL-PrintDot",
"connected": "客户端已连接: %s"
}
}

230
XSLPrintDot/main.go Normal file
View File

@@ -0,0 +1,230 @@
package main
import (
"context"
"embed"
sys_runtime "runtime"
"os"
"strconv"
"github.com/wailsapp/wails/v2"
"github.com/wailsapp/wails/v2/pkg/menu"
"github.com/wailsapp/wails/v2/pkg/options"
"github.com/wailsapp/wails/v2/pkg/options/assetserver"
"github.com/wailsapp/wails/v2/pkg/options/mac"
"github.com/wailsapp/wails/v2/pkg/options/windows"
"github.com/wailsapp/wails/v2/pkg/runtime"
"github.com/energye/systray"
)
//go:embed all:frontend/dist
var assets embed.FS
//go:embed build/appicon.png
var icon []byte
//go:embed build/windows/icon.ico
var iconIco []byte
func main() {
// Check command line args
mode := "main"
logPort := 0
if len(os.Args) > 1 {
switch os.Args[1] {
case "logs":
mode = "logs"
if len(os.Args) > 2 {
if p, err := strconv.Atoi(os.Args[2]); err == nil {
logPort = p
}
}
case "help":
mode = "help"
case "settings":
mode = "settings"
if len(os.Args) > 2 {
if p, err := strconv.Atoi(os.Args[2]); err == nil {
logPort = p
}
}
}
}
// Create an instance of the app structure
app := NewApp(mode, logPort)
// Load settings to determine menu language
sm := NewSettingsManager()
currentLang := sm.Get().Language
LoadLocales(currentLang)
// Configure based on mode
title := T("window.main")
width := 380
height := 660
minWidth := 380
minHeight := 600
var onBeforeClose func(ctx context.Context) bool
var appMenu *menu.Menu
if mode == "main" {
appMenu = app.CreateMenu(currentLang)
onBeforeClose = func(ctx context.Context) bool {
if app.isQuitting {
app.Cleanup()
return false
}
runtime.WindowHide(ctx)
return true
}
// Start system tray
go func() {
sys_runtime.LockOSThread()
systray.Run(func() {
if sys_runtime.GOOS == "windows" {
systray.SetIcon(iconIco)
} else {
systray.SetIcon(icon)
}
systray.SetTitle(T("tray.title"))
systray.SetTooltip(T("tray.tooltip"))
systray.SetOnClick(func(menu systray.IMenu) {
go func() {
if app.ctx != nil {
runtime.WindowShow(app.ctx)
}
}()
})
systray.SetOnRClick(func(menu systray.IMenu) {
menu.ShowMenu()
})
mShow := systray.AddMenuItem(T("tray.show"), T("tray.show"))
mHelp := systray.AddMenuItem(T("menu.help"), T("menu.help"))
mSettings := systray.AddMenuItem(T("menu.settings"), T("menu.settings"))
systray.AddSeparator()
mQuit := systray.AddMenuItem(T("tray.quit"), T("tray.quit"))
mShow.Click(func() {
go func() {
if app.ctx != nil {
runtime.WindowShow(app.ctx)
}
}()
})
mHelp.Click(func() {
go app.ShowHelp()
})
mSettings.Click(func() {
go app.ShowSettings()
})
mQuit.Click(func() {
go app.Quit()
})
}, func() {
// Cleanup if needed
})
}()
} else if mode == "logs" {
// Logs Window Configuration
title = T("window.logs")
width = 700
height = 500
// No special menu or close behavior for logs window (it just closes)
} else if mode == "help" {
title = T("window.help")
width = 800
height = 600
minWidth = 600
minHeight = 400
} else if mode == "settings" {
title = T("window.settings")
}
// Create application with options
appOptions := &options.App{
Title: title,
Width: width,
Height: height,
MinWidth: minWidth,
MinHeight: minHeight,
AssetServer: &assetserver.Options{
Assets: assets,
},
BackgroundColour: &options.RGBA{R: 255, G: 255, B: 255, A: 1},
OnStartup: func(ctx context.Context) {
app.startup(ctx)
// Restore position if valid
if mode == "main" {
s := sm.Get()
if s.WindowX != 0 || s.WindowY != 0 {
runtime.WindowSetPosition(ctx, s.WindowX, s.WindowY)
}
if s.Maximized {
runtime.WindowMaximise(ctx)
}
}
},
OnBeforeClose: onBeforeClose,
Menu: appMenu,
Bind: []interface{}{
app,
},
Windows: &windows.Options{
WebviewIsTransparent: false,
WindowIsTranslucent: false,
BackdropType: windows.Mica,
},
Mac: &mac.Options{
TitleBar: mac.TitleBarHiddenInset(),
},
}
if mode == "main" {
appOptions.SingleInstanceLock = &options.SingleInstanceLock{
UniqueId: "56006c0a-0498-4228-a320-c2409044a14e",
OnSecondInstanceLaunch: func(secondInstanceData options.SecondInstanceData) {
runtime.WindowShow(app.ctx)
},
}
} else if mode == "logs" {
appOptions.SingleInstanceLock = &options.SingleInstanceLock{
UniqueId: "56006c0a-0498-4228-a320-c2409044a14e-logs",
OnSecondInstanceLaunch: func(secondInstanceData options.SecondInstanceData) {
runtime.WindowShow(app.ctx)
},
}
} else if mode == "help" {
appOptions.SingleInstanceLock = &options.SingleInstanceLock{
UniqueId: "56006c0a-0498-4228-a320-c2409044a14e-help",
OnSecondInstanceLaunch: func(secondInstanceData options.SecondInstanceData) {
runtime.WindowShow(app.ctx)
},
}
} else if mode == "settings" {
appOptions.SingleInstanceLock = &options.SingleInstanceLock{
UniqueId: "56006c0a-0498-4228-a320-c2409044a14e-settings",
OnSecondInstanceLaunch: func(secondInstanceData options.SecondInstanceData) {
runtime.WindowShow(app.ctx)
},
}
}
err := wails.Run(appOptions)
if mode == "main" {
systray.Quit()
}
if err != nil {
println("Error:", err.Error())
}
}

BIN
XSLPrintDot/npx-out.txt Normal file

Binary file not shown.

View File

@@ -0,0 +1,37 @@
#!/bin/sh
set -e
remove_data_linux() {
if [ -n "${XDG_DATA_HOME:-}" ]; then
BASE_DIR="$XDG_DATA_HOME/PrintDot"
elif [ -n "${HOME:-}" ]; then
BASE_DIR="$HOME/.local/share/PrintDot"
else
BASE_DIR=""
fi
if [ -n "$BASE_DIR" ]; then
rm -rf "$BASE_DIR"
fi
}
remove_data_macos() {
if [ -n "${HOME:-}" ]; then
rm -rf "$HOME/Library/Application Support/PrintDot"
fi
}
case "$(uname -s)" in
Darwin)
remove_data_macos
;;
Linux)
remove_data_linux
;;
*)
echo "Unsupported OS: $(uname -s)"
exit 1
;;
esac
echo "PrintDot data removed."

181
XSLPrintDot/settings.go Normal file
View File

@@ -0,0 +1,181 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"sync"
"github.com/cloudfoundry/jibber_jabber"
)
type AppSettings struct {
Language string `json:"language"`
AutoStart bool `json:"autoStart"`
RemoteAutoConnect bool `json:"remoteAutoConnect"`
ServerPort string `json:"serverPort"`
ServerKey string `json:"serverKey"`
RemoteServer string `json:"remoteServer"`
RemoteAuthURL string `json:"remoteAuthUrl"`
RemoteWsURL string `json:"remoteWsUrl"`
RemoteUser string `json:"remoteUser"`
RemotePassword string `json:"remotePassword"`
RemoteClientID string `json:"remoteClientId"`
RemoteSecretKey string `json:"remoteSecretKey"`
RemoteClientName string `json:"remoteClientName"`
// Window State
WindowWidth int `json:"windowWidth"`
WindowHeight int `json:"windowHeight"`
WindowX int `json:"windowX"`
WindowY int `json:"windowY"`
Maximized bool `json:"maximized"`
}
type SettingsManager struct {
settings AppSettings
mu sync.Mutex
filePath string
}
func NewSettingsManager() *SettingsManager {
appConfigDir, err := dataDirPath()
if err != nil {
configDir, _ := os.UserConfigDir()
appConfigDir = filepath.Join(configDir, "PrintDot")
}
os.MkdirAll(appConfigDir, 0755)
// Detect language
defaultLang := "en-US"
userLang, err := jibber_jabber.DetectLanguage()
if err == nil && strings.ToLower(userLang) == "zh" {
defaultLang = "zh-CN"
}
sm := &SettingsManager{
filePath: filepath.Join(appConfigDir, "settings.json"),
settings: AppSettings{
Language: defaultLang,
AutoStart: false,
RemoteAutoConnect: true,
ServerPort: "1122",
},
}
sm.Load()
return sm
}
func (sm *SettingsManager) Load() {
sm.mu.Lock()
defer sm.mu.Unlock()
data, err := os.ReadFile(sm.filePath)
if err == nil {
json.Unmarshal(data, &sm.settings)
var raw map[string]interface{}
if json.Unmarshal(data, &raw) == nil {
if _, ok := raw["remoteAutoConnect"]; !ok {
sm.settings.RemoteAutoConnect = true
}
}
}
if sm.settings.RemoteClientID == "" && sm.settings.RemoteUser != "" {
sm.settings.RemoteClientID = sm.settings.RemoteUser
}
if sm.settings.RemoteSecretKey == "" && sm.settings.RemotePassword != "" {
sm.settings.RemoteSecretKey = sm.settings.RemotePassword
}
if sm.settings.RemoteAuthURL == "" && sm.settings.RemoteWsURL == "" && sm.settings.RemoteServer != "" {
if loginURL, wsURL, err := buildRemoteURLs(sm.settings.RemoteServer); err == nil {
sm.settings.RemoteAuthURL = loginURL.String()
sm.settings.RemoteWsURL = wsURL.String()
}
}
if strings.TrimSpace(sm.settings.ServerPort) == "" {
sm.settings.ServerPort = "1122"
}
applyDefaultClientIdentity(&sm.settings)
}
func (sm *SettingsManager) Save(settings AppSettings) error {
sm.mu.Lock()
defer sm.mu.Unlock()
if settings.RemoteClientID == "" && settings.RemoteUser != "" {
settings.RemoteClientID = settings.RemoteUser
}
if settings.RemoteUser == "" && settings.RemoteClientID != "" {
settings.RemoteUser = settings.RemoteClientID
}
if settings.RemoteSecretKey == "" && settings.RemotePassword != "" {
settings.RemoteSecretKey = settings.RemotePassword
}
if settings.RemotePassword == "" && settings.RemoteSecretKey != "" {
settings.RemotePassword = settings.RemoteSecretKey
}
if settings.RemoteAuthURL == "" && settings.RemoteWsURL == "" && settings.RemoteServer != "" {
if loginURL, wsURL, err := buildRemoteURLs(settings.RemoteServer); err == nil {
settings.RemoteAuthURL = loginURL.String()
settings.RemoteWsURL = wsURL.String()
}
}
applyDefaultClientIdentity(&settings)
sm.settings = settings
data, err := json.MarshalIndent(settings, "", " ")
if err != nil {
return err
}
// Handle AutoStart
if settings.AutoStart != sm.settings.AutoStart {
setAutoStart(settings.AutoStart)
}
return os.WriteFile(sm.filePath, data, 0644)
}
func (sm *SettingsManager) Get() AppSettings {
sm.mu.Lock()
defer sm.mu.Unlock()
return sm.settings
}
func applyDefaultClientIdentity(settings *AppSettings) {
id, name := defaultClientIdentity()
if id != "" {
settings.RemoteClientID = id
}
if settings.RemoteClientName == "" {
settings.RemoteClientName = name
}
}
func defaultClientIdentity() (string, string) {
name := strings.TrimSpace(os.Getenv("COMPUTERNAME"))
if name == "" {
if host, err := os.Hostname(); err == nil {
name = strings.TrimSpace(host)
}
}
if name == "" {
name = "XSL-PrintDot"
}
id := getNormalizedDeviceID()
if id == "" {
id = strings.ToLower(name)
id = strings.ReplaceAll(id, " ", "-")
id = strings.ReplaceAll(id, "_", "-")
id = strings.ReplaceAll(id, "/", "-")
}
return id, name
}

BIN
XSLPrintDot/tmp_test.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 298 B

16
XSLPrintDot/wails.json Normal file
View File

@@ -0,0 +1,16 @@
{
"$schema": "https://wails.io/schemas/config.v2.json",
"name": "XSL-PrintDot",
"outputfilename": "XSL-PrintDot",
"frontend:install": "npm install",
"frontend:build": "npm run build",
"frontend:dev:watcher": "npm run dev",
"frontend:dev:serverUrl": "auto",
"author": {
"name": "Jonny",
"email": "1515188277@qq.com"
},
"info": {
"productVersion": "1.1.1"
}
}

View File

@@ -11,10 +11,14 @@
{ {
"path": "yy-admin-master", "path": "yy-admin-master",
"name": "桌面端 (yy-admin-master)" "name": "桌面端 (yy-admin-master)"
},
{
"path": "XSLPrintDot"
} }
], ],
"settings": { "settings": {
"java.compile.nullAnalysis.mode": "automatic", "java.compile.nullAnalysis.mode": "automatic",
"java.configuration.updateBuildConfiguration": "interactive" "java.configuration.updateBuildConfiguration": "interactive",
"java.jdt.ls.vmargs": "-XX:+UseParallelGC -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -Dsun.zip.disableMemoryMapping=true -Xmx4G -Xms100m -Xlog:disable"
} }
} }