原材料入库结存

This commit is contained in:
2026-05-15 11:37:52 +08:00
839 changed files with 41718 additions and 425 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

@@ -0,0 +1,28 @@
-- 升级脚本仅为缺失的列执行 ADD可重复执行不会因列已存在报错
-- 适用旧库 mes_xsl_biz_entity_field_detail 缺少 detail_property_name / detail_slot_kind
SET NAMES utf8mb4;
SELECT COUNT(*) INTO @jeecg_chk_dpn FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'mes_xsl_biz_entity_field_detail'
AND COLUMN_NAME = 'detail_property_name';
SET @jeecg_sql_dpn := IF(@jeecg_chk_dpn = 0,
'ALTER TABLE mes_xsl_biz_entity_field_detail ADD COLUMN detail_property_name varchar(128) DEFAULT NULL COMMENT ''主实体明细属性名与打印绑定 detailProperty 一致'' AFTER profile_id',
'SELECT ''detail_property_name 已存在跳过'' AS msg');
PREPARE jeecg_stmt_dpn FROM @jeecg_sql_dpn;
EXECUTE jeecg_stmt_dpn;
DEALLOCATE PREPARE jeecg_stmt_dpn;
SELECT COUNT(*) INTO @jeecg_chk_dsk FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'mes_xsl_biz_entity_field_detail'
AND COLUMN_NAME = 'detail_slot_kind';
SET @jeecg_sql_dsk := IF(@jeecg_chk_dsk = 0,
'ALTER TABLE mes_xsl_biz_entity_field_detail ADD COLUMN detail_slot_kind varchar(16) DEFAULT NULL COMMENT ''LIST OBJECT'' AFTER detail_property_name',
'SELECT ''detail_slot_kind 已存在跳过'' AS msg');
PREPARE jeecg_stmt_dsk FROM @jeecg_sql_dsk;
EXECUTE jeecg_stmt_dsk;
DEALLOCATE PREPARE jeecg_stmt_dsk;

View File

@@ -0,0 +1,38 @@
-- 业务实体字段配置主表 + 明细每条明细对应一类明细表及其字段列表
SET NAMES utf8mb4;
CREATE TABLE IF NOT EXISTS `mes_xsl_biz_entity_field_profile` (
`id` varchar(32) NOT NULL COMMENT '主键',
`business_name` varchar(200) NOT NULL COMMENT '业务名称',
`business_code` varchar(64) NOT NULL COMMENT '业务编码菜单 permission id与打印 biz_code 一致唯一',
`entity_class_name` varchar(512) DEFAULT NULL COMMENT '主实体 Java 全限定类名',
`main_fields_json` text COMMENT '主表实体字段列表JSON 数组元素可为字符串字段名或含 name/comment/javaType 的对象',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
`tenant_id` int DEFAULT NULL COMMENT '租户ID',
`create_by` varchar(32) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_by` varchar(32) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_mxbefp_bcode` (`business_code`),
KEY `idx_mxbefp_tenant` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='MES业务实体字段配置-主表';
CREATE TABLE IF NOT EXISTS `mes_xsl_biz_entity_field_detail` (
`id` varchar(32) NOT NULL COMMENT '主键',
`profile_id` varchar(32) NOT NULL COMMENT '主表ID',
`detail_property_name` varchar(128) DEFAULT NULL COMMENT '主实体明细属性名与打印绑定 detailProperty 一致',
`detail_slot_kind` varchar(16) DEFAULT NULL COMMENT 'LIST OBJECT',
`detail_name` varchar(200) DEFAULT NULL COMMENT '明细展示名称',
`detail_entity_class_name` varchar(512) DEFAULT NULL COMMENT '明细实体 Java 全限定类名',
`detail_fields_json` text COMMENT '明细表字段列表JSON 数组规则同 main_fields_json',
`sort_no` int DEFAULT NULL COMMENT '排序号',
`create_by` varchar(32) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_by` varchar(32) DEFAULT NULL COMMENT '更新人',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_mxbefd_profile` (`profile_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='MES业务实体字段配置-明细表字段清单';
-- 旧表缺列时执行 db/mes-xsl-biz-entity-field-detail-alter-slot-columns.sql Flyway V3.9.2_55

View File

@@ -213,6 +213,9 @@ public class ShiroConfig {
filterChainDefinitionMap.put("/xslmes/mesXslWarehouseArea/anon/**", "anon");
// MES密炼物料管理免密接口供桌面端调用
filterChainDefinitionMap.put("/mes/material/mixerMaterial/anon/**", "anon");
// 打印模板免密接口(供桌面端调用)
filterChainDefinitionMap.put("/print/template/anon/**", "anon");
filterChainDefinitionMap.put("/print/bizTemplateBind/anon/**", "anon");
// 系统分类字典免密接口(供桌面端调用)
filterChainDefinitionMap.put("/sys/category/anon/**", "anon");
// 桌面端用户反同步批量上报Outbox -> /sys/sync/batch

View File

@@ -198,6 +198,36 @@ public class PrintTemplateController extends JeecgController<PrintTemplate, IPri
return Result.OK(t);
}
// ═══════════════════════════ 桌面端免密接口 ═══════════════════════════
/**
* 免密-通过编码查询(供 WPF 桌面端匿名调用)
*/
@Operation(summary = "打印模板-免密通过编码查询(桌面端)")
@GetMapping(value = "/anon/queryByCode")
public Result<PrintTemplate> anonQueryByCode(@RequestParam(name = "code") String code) {
PrintTemplate t = service.getByCode(code);
if (t == null) {
return Result.error("未找到模板: " + code);
}
return Result.OK(t);
}
/**
* 免密-分页列表(供 WPF 桌面端匿名调用,用于打印设置页选择模板)
*/
@Operation(summary = "打印模板-免密分页列表(桌面端)")
@GetMapping(value = "/anon/list")
public Result<IPage<PrintTemplate>> anonList(PrintTemplate query,
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "100") Integer pageSize,
HttpServletRequest req) {
QueryWrapper<PrintTemplate> qw = QueryGenerator.initQueryWrapper(query, req.getParameterMap());
qw.orderByAsc("template_code");
Page<PrintTemplate> page = new Page<>(pageNo, pageSize);
return Result.OK(service.page(page, qw));
}
@AutoLog(value = "打印模板-图片分析生成原生JSON")
@Operation(summary = "打印模板-上传图片分析为原生模板JSON前端传 imageBase64可接 OpenAI 兼容视觉模型)")
@PostMapping(value = "/analyzeImageForNative")

View File

@@ -18,5 +18,11 @@
<groupId>org.jeecgframework.boot3</groupId>
<artifactId>jeecg-boot-base-core</artifactId>
</dependency>
<!-- 复用打印模板模块打印机枚举、业务绑定、PDF 提交队列 -->
<dependency>
<groupId>org.jeecgframework.boot3</groupId>
<artifactId>jeecg-system-biz</artifactId>
<version>${jeecgboot.version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,164 @@
package org.jeecg.modules.xslmes.bootstrap;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.print.entity.PrintBizPermEntity;
import org.jeecg.modules.print.service.IPrintBizPermEntityService;
import org.jeecg.modules.print.util.PrintBizDetailPropertyScanner;
import org.jeecg.modules.print.util.PrintBizEntityFieldIntrospector;
import org.jeecg.modules.print.vo.PrintBizDetailSlotVO;
import org.jeecg.modules.print.vo.PrintBizFieldItemVO;
import org.jeecg.modules.system.entity.SysPermission;
import org.jeecg.modules.system.service.ISysPermissionService;
import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldDetail;
import org.jeecg.modules.xslmes.service.IMesXslBizEntityFieldProfileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 启动后异步:遍历 {@code print_biz_perm_entity} 中已配置实体类的业务,反射主表与明细槽位字段并写入 {@code mes_xsl_biz_entity_field_*}
* 供「业务打印绑定」弹窗读取(避免运行时频繁反射)。
*
* <p>关闭:{@code jeecg.print.biz-entity-field-catalog-sync=false}
*
* <p>建议在 {@link org.jeecg.modules.print.bootstrap.PrintBizPermEntityWarmupRunner}Order 2000之后执行。
*/
@Slf4j
@Component
@Order(2100)
public class BizEntityFieldCatalogSyncRunner implements ApplicationRunner {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Resource
private IPrintBizPermEntityService printBizPermEntityService;
@Resource
private IMesXslBizEntityFieldProfileService bizEntityFieldProfileService;
@Resource
private ISysPermissionService sysPermissionService;
@Value("${jeecg.print.biz-entity-field-catalog-sync:true}")
private boolean syncEnabled;
/** 延迟执行秒数,便于晚于「打印菜单实体映射预热」写完 print_biz_perm_entity */
@Value("${jeecg.print.biz-entity-field-catalog-sync-delay-seconds:10}")
private int catalogSyncDelaySeconds;
@Override
public void run(ApplicationArguments args) {
if (!syncEnabled) {
log.info("业务实体字段缓存同步已关闭jeecg.print.biz-entity-field-catalog-sync=false");
return;
}
log.info(
"业务实体字段缓存:将在 {} 秒后异步同步(来源 print_biz_perm_entity → mes_xsl_biz_entity_field_*",
Math.max(0, catalogSyncDelaySeconds));
CompletableFuture.runAsync(
this::doSync,
CompletableFuture.delayedExecutor(
Math.max(0, catalogSyncDelaySeconds),
TimeUnit.SECONDS,
ForkJoinPool.commonPool()));
}
private void doSync() {
try {
log.info("业务实体字段缓存:开始异步同步(来源 print_biz_perm_entity");
List<PrintBizPermEntity> rows = printBizPermEntityService.list();
if (rows == null || rows.isEmpty()) {
log.info("业务实体字段缓存print_biz_perm_entity 无数据,跳过");
return;
}
int ok = 0;
int skip = 0;
for (PrintBizPermEntity row : rows) {
if (row == null || StringUtils.isBlank(row.getPermId())) {
skip++;
continue;
}
String permId = row.getPermId().trim();
String entityFqn = StringUtils.trimToNull(row.getEntityClass());
if (entityFqn == null) {
skip++;
continue;
}
Class<?> clazz = PrintBizEntityFieldIntrospector.tryLoadClass(entityFqn);
if (clazz == null) {
skip++;
continue;
}
try {
syncOne(permId, clazz, entityFqn);
ok++;
} catch (Exception ex) {
log.warn("业务实体字段缓存同步失败 permId={} entity={}", permId, entityFqn, ex);
skip++;
}
}
log.info("业务实体字段缓存同步完成:成功 {} 条,跳过 {} 条", ok, skip);
} catch (Exception e) {
log.warn("业务实体字段缓存同步异常(不影响系统启动)", e);
}
}
private void syncOne(String permId, Class<?> clazz, String entityFqn) throws Exception {
List<PrintBizFieldItemVO> mainFields = PrintBizEntityFieldIntrospector.listFields(clazz);
String mainJson = OBJECT_MAPPER.writeValueAsString(mainFields);
List<PrintBizDetailSlotVO> slots = PrintBizDetailPropertyScanner.listSlots(clazz);
List<MesXslBizEntityFieldDetail> detailRows = new ArrayList<>();
int sort = 0;
Date now = new Date();
for (PrintBizDetailSlotVO slot : slots) {
Class<?> itemClazz =
PrintBizDetailPropertyScanner.resolveItemClassForSlot(
clazz, slot.getPropertyName(), slot.getSlotKind());
if (itemClazz == null) {
continue;
}
List<PrintBizFieldItemVO> itemFields = PrintBizEntityFieldIntrospector.listFields(itemClazz);
MesXslBizEntityFieldDetail d = new MesXslBizEntityFieldDetail();
d.setDetailPropertyName(slot.getPropertyName());
d.setDetailSlotKind(slot.getSlotKind());
d.setDetailName(slot.getLabel());
d.setDetailEntityClassName(fqn(itemClazz));
d.setDetailFieldsJson(OBJECT_MAPPER.writeValueAsString(itemFields));
d.setSortNo(sort++);
d.setCreateTime(now);
d.setUpdateTime(now);
detailRows.add(d);
}
String bizName = resolveMenuName(permId);
bizEntityFieldProfileService.upsertScannedProfile(permId, bizName, entityFqn, mainJson, detailRows);
}
private static String fqn(Class<?> c) {
if (c == null) {
return null;
}
String cn = c.getCanonicalName();
return cn != null ? cn : c.getName();
}
private String resolveMenuName(String permId) {
SysPermission p = sysPermissionService.getById(permId);
if (p != null && StringUtils.isNotBlank(p.getName())) {
return p.getName().trim();
}
return permId;
}
}

View File

@@ -0,0 +1,16 @@
package org.jeecg.modules.xslmes.capacity;
import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea;
import java.util.List;
/**
* 库区展示用「实际存放量」数据源贡献者(可多实现并按 Spring Order 编排)
*/
public interface WarehouseAreaActualCapacityContribution {
/**
* @param areas 通常为列表/分页的一段记录(内存回填,不写库)
*/
void contribute(List<MesXslWarehouseArea> areas);
}

View File

@@ -0,0 +1,31 @@
package org.jeecg.modules.xslmes.capacity;
import lombok.RequiredArgsConstructor;
import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* 编排库区「实际存放量」展示回填(可多 {@link WarehouseAreaActualCapacityContribution} 扩展)。
*/
@Component
@RequiredArgsConstructor
public class WarehouseAreaDisplayedActualCapacityMediator {
private final List<WarehouseAreaActualCapacityContribution> contributions;
public void apply(Collection<MesXslWarehouseArea> areas) {
if (areas == null || areas.isEmpty()) {
return;
}
List<MesXslWarehouseArea> list = new ArrayList<>(areas);
List<WarehouseAreaActualCapacityContribution> ordered = contributions.stream().sorted(AnnotationAwareOrderComparator.INSTANCE).toList();
for (WarehouseAreaActualCapacityContribution c : ordered) {
c.contribute(list);
}
}
}

View File

@@ -0,0 +1,134 @@
package org.jeecg.modules.xslmes.capacity.impl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.xslmes.capacity.WarehouseAreaActualCapacityContribution;
import org.jeecg.modules.xslmes.config.XslMesWarehouseAreaCapacityProperties;
import org.jeecg.modules.xslmes.dto.MesXslAreaRemainQtySumDTO;
import org.jeecg.modules.system.service.ISysCategoryService;
import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea;
import org.jeecg.modules.xslmes.mapper.MesXslRawMaterialCardMapper;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 用「原材料卡片」按库区(trim)汇总 remaining_quantity回填展示字段 actual_capacity不写库
*/
@Slf4j
@Component
@Order(100)
@RequiredArgsConstructor
public class RawMaterialCardRemainQtyCapacityContribution implements WarehouseAreaActualCapacityContribution {
private final XslMesWarehouseAreaCapacityProperties properties;
private final MesXslRawMaterialCardMapper mesXslRawMaterialCardMapper;
private final ISysCategoryService sysCategoryService;
@Override
public void contribute(List<MesXslWarehouseArea> areas) {
if (areas == null || areas.isEmpty()) {
return;
}
if (!properties.isEnabled()) {
return;
}
Set<String> allowedCategories = resolveAllowedWarehouseCategoryIds();
if (allowedCategories.isEmpty()) {
log.debug("[WarehouseAreaActualCapacity] 原材料库分类编码/ID 均未解析到有效 warehouse_category跳过 RawMaterialCard 策略");
return;
}
List<MesXslWarehouseArea> targets =
areas.stream().filter(a -> a != null && allowedCategories.contains(normId(a.getWarehouseCategory())) && StringUtils.isNotBlank(a.getAreaCode()))
.collect(Collectors.toList());
if (targets.isEmpty()) {
return;
}
Collection<String> codes =
targets.stream().map(MesXslWarehouseArea::getAreaCode).map(String::trim).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
Map<String, Long> sumMap = loadSumMap(codes);
for (MesXslWarehouseArea a : targets) {
String ck = trimKey(a.getAreaCode());
long sum = sumMap.getOrDefault(ck, 0L);
int display;
try {
display = Math.toIntExact(Math.min(sum, Integer.MAX_VALUE));
} catch (ArithmeticException ex) {
display = Integer.MAX_VALUE;
}
a.setActualCapacity(display);
}
}
private Map<String, Long> loadSumMap(Collection<String> codes) {
if (codes.isEmpty()) {
return Collections.emptyMap();
}
List<MesXslAreaRemainQtySumDTO> rows = mesXslRawMaterialCardMapper.sumRemainingQtyByTrimmedWarehouseArea(codes);
if (rows == null || rows.isEmpty()) {
return Collections.emptyMap();
}
Map<String, Long> map = new HashMap<>(Math.max(16, rows.size() * 2));
for (MesXslAreaRemainQtySumDTO row : rows) {
if (row == null || row.getAreaCode() == null) {
continue;
}
String k = row.getAreaCode().trim();
if (StringUtils.isBlank(k)) {
continue;
}
long v = row.getQtySum() == null ? 0L : row.getQtySum();
map.put(k, v);
}
return map;
}
private static String trimKey(String code) {
return code == null ? "" : code.trim();
}
private static String normId(String id) {
return StringUtils.trimToEmpty(id);
}
private static Set<String> normalizeIdSet(Collection<String> raw) {
if (raw == null) {
return Collections.emptySet();
}
return raw.stream().filter(StringUtils::isNotBlank).map(String::trim).collect(Collectors.toSet());
}
/** 配置的 id + 配置的 code 解析出的 id 合并 */
private Set<String> resolveAllowedWarehouseCategoryIds() {
Set<String> set = new HashSet<>(normalizeIdSet(properties.getRawMaterialWarehouseCategoryIds()));
Collection<String> codes = properties.getRawMaterialWarehouseCategoryCodes();
if (codes != null) {
for (String c : codes) {
if (StringUtils.isBlank(c)) {
continue;
}
try {
String id = sysCategoryService.queryIdByCode(c.trim());
if (StringUtils.isNotBlank(id)) {
set.add(id.trim());
}
} catch (Exception ex) {
log.warn("[WarehouseAreaActualCapacity] 解析原材料库分类编码失败 code={}: {}", c, ex.getMessage());
}
}
}
return set;
}
}

View File

@@ -0,0 +1,43 @@
package org.jeecg.modules.xslmes.config;
import lombok.Data;
import org.jeecg.modules.xslmes.constant.MesXslWarehouseCategory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* 库区列表「实际存放量」展示口径配置(不写库)
* <p>
* 推荐使用 {@link #rawMaterialWarehouseCategoryCodes},启动时解析为 sys_category.id
* 避免在配置里维护易变的雪花 id也可用 {@link #rawMaterialWarehouseCategoryIds} 直接指定 id。
*/
@Data
@Component
@ConfigurationProperties(prefix = "xslmes.warehouse-area.display-actual-capacity")
public class XslMesWarehouseAreaCapacityProperties {
/**

View File

@@ -0,0 +1,15 @@
package org.jeecg.modules.xslmes.constant;
/**
* 打印业务绑定 biz_code 使用菜单 permission id与 print_biz_perm_entity、Flyway 中原材料卡片菜单一致。
*/
public final class MesXslPrintConstants {
/** 原材料卡片页面菜单sys_permission.id */
public static final String RAW_MATERIAL_CARD_PERM_ID = "1900000000000000540";
/** 原料入场记录页面菜单sys_permission.id与 Flyway 中 parent 菜单一致) */
public static final String RAW_MATERIAL_ENTRY_PERM_ID = "1900000000000000530";
private MesXslPrintConstants() {}
}

View File

@@ -1,7 +1,19 @@
package org.jeecg.modules.xslmes.constant;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* MES 仓库分类(分类字典 sys_category根编码 {@link #ROOT_CODE}
*
* <p>说明:历史版本曾在编码上使用 F1/F2 后缀;当前业务树已不再按楼层区分,
* 「F1」「F2」仅可能作为编码后缀保留请以 {@link #RAW_MATERIAL_CATEGORY_CODES}、
* 客户/供应商库编码集合为准做兼容。</p>
*/
public final class MesXslWarehouseCategory {
@@ -10,8 +22,37 @@ public final class MesXslWarehouseCategory {
/** 根节点编码,与 JCategorySelect 的 pcode 一致 */
public static final String ROOT_CODE = "XSLMES_WH";
/** 客户库(二楼):须关联客户 */
public static final String CUSTOMER_CATEGORY_CODE = "XSLMES_WH_F2_KH";
/** 供应商库(二楼):须关联供应商 */
public static final String SUPPLIER_CATEGORY_CODE = "XSLMES_WH_F2_GYS";
/** 兼容历史:原材料库在库中可能出现的分类编码(新环境多为 F1老数据可能仍为 F2 */
public static final List<String> RAW_MATERIAL_CATEGORY_CODES =
Collections.unmodifiableList(Arrays.asList("XSLMES_WH_F1_YCL", "XSLMES_WH_F2_YCL"));
/** 兼容历史编号的「客户库」分类编码集合 */
private static final Set<String> CUSTOMER_CATEGORY_CODES =
Collections.unmodifiableSet(new HashSet<>(Arrays.asList("XSLMES_WH_F1_KH", "XSLMES_WH_F2_KH")));
/** 兼容历史编号的「供应商库」分类编码集合 */
private static final Set<String> SUPPLIER_CATEGORY_CODES =
Collections.unmodifiableSet(new HashSet<>(Arrays.asList("XSLMES_WH_F1_GYS", "XSLMES_WH_F2_GYS")));
/**
* @deprecated 请改用 {@link #isCustomerWarehouseCategoryCode(String)}
*/
@Deprecated
public static final String CUSTOMER_CATEGORY_CODE = "XSLMES_WH_F1_KH";
/**
* @deprecated 请改用 {@link #isSupplierWarehouseCategoryCode(String)}
*/
@Deprecated
public static final String SUPPLIER_CATEGORY_CODE = "XSLMES_WH_F1_GYS";
/** 是否为「客户库」分类编码(兼容 XSLMES_WH_F1_KH / XSLMES_WH_F2_KH */
public static boolean isCustomerWarehouseCategoryCode(String code) {
return CUSTOMER_CATEGORY_CODES.contains(StringUtils.trimToEmpty(code));
}
/** 是否为「供应商库」分类编码(兼容 XSLMES_WH_F1_GYS / XSLMES_WH_F2_GYS */
public static boolean isSupplierWarehouseCategoryCode(String code) {
return SUPPLIER_CATEGORY_CODES.contains(StringUtils.trimToEmpty(code));
}
}

View File

@@ -0,0 +1,128 @@
package org.jeecg.modules.xslmes.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldProfile;
import org.jeecg.modules.xslmes.service.IMesXslBizEntityFieldProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
/**
* 业务实体字段配置:主表存业务名称与主实体字段 JSON子表存各明细表的字段 JSON。
*/
@Tag(name = "业务实体字段配置")
@RestController
@RequestMapping("/xslmes/mesXslBizEntityFieldProfile")
@Slf4j
public class MesXslBizEntityFieldProfileController extends JeecgController<MesXslBizEntityFieldProfile, IMesXslBizEntityFieldProfileService> {
@Autowired
private IMesXslBizEntityFieldProfileService bizEntityFieldProfileService;
@Operation(summary = "分页列表(不含明细,减轻负载)")
@GetMapping(value = "/list")
public Result<IPage<MesXslBizEntityFieldProfile>> queryPageList(
MesXslBizEntityFieldProfile query,
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
QueryWrapper<MesXslBizEntityFieldProfile> qw = QueryGenerator.initQueryWrapper(query, req.getParameterMap());
Page<MesXslBizEntityFieldProfile> page = new Page<>(pageNo, pageSize);
IPage<MesXslBizEntityFieldProfile> pageList = bizEntityFieldProfileService.page(page, qw);
return Result.OK(pageList);
}
@AutoLog(value = "业务实体字段配置-添加")
@Operation(summary = "添加(请求体可含 detailList")
@RequiresPermissions("xslmes:mes_xsl_biz_entity_field_profile:add")
@PostMapping(value = "/add")
public Result<String> add(@RequestBody MesXslBizEntityFieldProfile entity) {
if (oConvertUtils.isEmpty(entity.getBusinessName())) {
return Result.error("业务名称不能为空");
}
if (oConvertUtils.isEmpty(entity.getBusinessCode())) {
return Result.error("业务编码不能为空(建议填写菜单 permission id");
}
bizEntityFieldProfileService.saveWithDetails(entity);
return Result.OK("添加成功");
}
@AutoLog(value = "业务实体字段配置-编辑")
@Operation(summary = "编辑(明细全量替换)")
@RequiresPermissions("xslmes:mes_xsl_biz_entity_field_profile:edit")
@RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
public Result<String> edit(@RequestBody MesXslBizEntityFieldProfile entity) {
if (oConvertUtils.isEmpty(entity.getId())) {
return Result.error("主键不能为空");
}
if (oConvertUtils.isEmpty(entity.getBusinessName())) {
return Result.error("业务名称不能为空");
}
if (oConvertUtils.isEmpty(entity.getBusinessCode())) {
return Result.error("业务编码不能为空(建议填写菜单 permission id");
}
bizEntityFieldProfileService.updateWithDetails(entity);
return Result.OK("编辑成功");
}
@AutoLog(value = "业务实体字段配置-删除")
@Operation(summary = "删除")
@RequiresPermissions("xslmes:mes_xsl_biz_entity_field_profile:delete")
@DeleteMapping(value = "/delete")
public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
bizEntityFieldProfileService.removeWithDetails(id);
return Result.OK("删除成功");
}
@AutoLog(value = "业务实体字段配置-批量删除")
@Operation(summary = "批量删除")
@RequiresPermissions("xslmes:mes_xsl_biz_entity_field_profile:deleteBatch")
@DeleteMapping(value = "/deleteBatch")
public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
bizEntityFieldProfileService.removeBatchWithDetails(Arrays.asList(ids.split(",")));
return Result.OK("批量删除成功");
}
@Operation(summary = "按 id 查询(含 detailList")
@GetMapping(value = "/queryById")
public Result<MesXslBizEntityFieldProfile> queryById(@RequestParam(name = "id", required = true) String id) {
MesXslBizEntityFieldProfile entity = bizEntityFieldProfileService.getByIdWithDetails(id);
if (entity == null) {
return Result.error("未找到对应数据");
}
return Result.OK(entity);
}
@RequiresPermissions("xslmes:mes_xsl_biz_entity_field_profile:exportXls")
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, MesXslBizEntityFieldProfile query) {
return super.exportXls(request, query, MesXslBizEntityFieldProfile.class, "业务实体字段配置");
}
@RequiresPermissions("xslmes:mes_xsl_biz_entity_field_profile:importExcel")
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, MesXslBizEntityFieldProfile.class);
}
}

View File

@@ -9,10 +9,20 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.print.entity.PrintBizTemplateBind;
import org.jeecg.modules.print.entity.PrintTemplate;
import org.jeecg.modules.print.service.IPrintBizTemplateBindService;
import org.jeecg.modules.print.service.IPrintTemplateService;
import org.jeecg.modules.print.util.PrintBizDataMappingUtil;
import org.jeecg.modules.xslmes.constant.MesXslCustomerBizStatus;
import org.jeecg.modules.xslmes.constant.MesXslPrintConstants;
import org.jeecg.modules.xslmes.entity.MesXslCustomer;
import org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard;
import org.jeecg.modules.xslmes.entity.MesXslRawMaterialEntry;
@@ -33,6 +43,9 @@ import org.jeecg.modules.xslmes.service.MesXslStompNotifyService;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
@@ -59,6 +72,9 @@ public class MesXslDesktopAnonController {
private final IMesXslWarehouseService warehouseService;
private final IMesXslWarehouseAreaService warehouseAreaService;
private final MesXslStompNotifyService stompNotify;
private final IPrintBizTemplateBindService printBizTemplateBindService;
private final IPrintTemplateService printTemplateService;
private final ObjectMapper objectMapper;
// ═══════════════════════════ 车辆管理 ═══════════════════════════
@@ -606,6 +622,61 @@ public class MesXslDesktopAnonController {
return Result.OK((int) count);
}
@Operation(summary = "原材料卡片-免密准备原生打印数据(桌面端用)")
@GetMapping("/xslmes/mesXslRawMaterialCard/anon/prepareNativePrint")
public Result<Map<String, Object>> rawMaterialCardAnonPrepareNativePrint(@RequestParam(name = "id") String id) {
try {
MesXslRawMaterialCard card = rawMaterialCardService.getById(id);
if (card == null) return Result.error("未找到原材料卡片");
PrintBizTemplateBind bind =
printBizTemplateBindService.getByBizCode(MesXslPrintConstants.RAW_MATERIAL_CARD_PERM_ID);
if (bind == null) return Result.error("请先在「业务打印绑定」中配置原材料卡片与打印模板");
PrintTemplate tpl = printTemplateService.getById(bind.getTemplateId());
if (tpl == null) return Result.error("绑定的打印模板不存在");
ArrayNode mapping = PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson());
JsonNode bizRoot = objectMapper.valueToTree(card);
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping);
PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson());
Map<String, Object> out = new HashMap<>(8);
out.put("cardId", card.getId());
out.put("templateCode", bind.getTemplateCode());
out.put("templateJson", tpl.getTemplateJson());
out.put("printData", objectMapper.convertValue(printData, Map.class));
return Result.OK(out);
} catch (Exception e) {
log.error("原材料卡片-免密准备打印数据失败 id={}", id, e);
return Result.error("准备打印数据失败: " + e.getMessage());
}
}
@Operation(summary = "原料入场记录-免密准备原生打印数据(桌面端用)")
@GetMapping("/xslmes/mesXslRawMaterialEntry/anon/prepareNativePrint")
public Result<Map<String, Object>> rawMaterialEntryAnonPrepareNativePrint(@RequestParam(name = "id") String id) {
try {
MesXslRawMaterialEntry entry = rawMaterialEntryService.getById(id);
if (entry == null) return Result.error("未找到原料入场记录");
PrintBizTemplateBind bind =
printBizTemplateBindService.getByBizCode(MesXslPrintConstants.RAW_MATERIAL_ENTRY_PERM_ID);
if (bind == null) return Result.error("请先在「业务打印绑定」中配置原料入场记录与打印模板");
PrintTemplate tpl = printTemplateService.getById(bind.getTemplateId());
if (tpl == null) return Result.error("绑定的打印模板不存在");
ArrayNode mapping = PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson());
JsonNode bizRoot = objectMapper.valueToTree(entry);
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping);
PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson());
Map<String, Object> out = new HashMap<>(8);
out.put("entryId", entry.getId());
out.put("templateCode", bind.getTemplateCode());
out.put("templateJson", tpl.getTemplateJson());
out.put("printData", objectMapper.convertValue(printData, Map.class));
return Result.OK(out);
} catch (Exception e) {
log.error("原料入场记录-免密准备打印数据失败 id={}", id, e);
return Result.error("准备打印数据失败: " + e.getMessage());
}
}
// ═══════════════════════════ 仓库管理(只读,供桌面端下拉选取) ═══════════════════════════
@Operation(summary = "仓库-免密分页列表查询(供桌面端筛选使用)")
@@ -632,6 +703,7 @@ public class MesXslDesktopAnonController {
HttpServletRequest req) {
QueryWrapper<MesXslWarehouseArea> qw = QueryGenerator.initQueryWrapper(mesXslWarehouseArea, req.getParameterMap());
IPage<MesXslWarehouseArea> page = warehouseAreaService.page(new Page<>(pageNo, pageSize), qw);
warehouseAreaService.enrichDisplayedActualCapacity(page.getRecords());
return Result.OK(page);
}
@@ -639,7 +711,11 @@ public class MesXslDesktopAnonController {
@GetMapping("/xslmes/mesXslWarehouseArea/anon/queryById")
public Result<MesXslWarehouseArea> warehouseAreaAnonQueryById(@RequestParam(name = "id") String id) {
MesXslWarehouseArea entity = warehouseAreaService.getById(id);
return entity != null ? Result.OK(entity) : Result.error("未找到对应数据");
if (entity == null) {
return Result.error("未找到对应数据");
}
warehouseAreaService.enrichDisplayedActualCapacity(Collections.singletonList(entity));
return Result.OK(entity);
}
@Operation(summary = "库区-免密添加")

View File

@@ -1,27 +1,50 @@
package org.jeecg.modules.xslmes.controller;
import java.util.Arrays;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard;
import org.jeecg.modules.xslmes.service.IMesXslRawMaterialCardService;
import org.jeecg.modules.xslmes.service.MesXslStompNotifyService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.v3.oas.annotations.Operation;
import org.jeecg.common.aspect.annotation.AutoLog;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.oConvertUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.print.entity.PrintBizTemplateBind;
import org.jeecg.modules.print.entity.PrintTemplate;
import org.jeecg.modules.print.service.IPrintBizTemplateBindService;
import org.jeecg.modules.print.service.IPrintTemplateService;
import org.jeecg.modules.print.support.PrintServerEnvironmentService;
import org.jeecg.modules.print.support.PrintServerPdfJobService;
import org.jeecg.modules.print.util.PrintBizDataMappingUtil;
import org.jeecg.modules.xslmes.constant.MesXslPrintConstants;
import org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard;
import org.jeecg.modules.xslmes.service.IMesXslRawMaterialCardService;
import org.jeecg.modules.xslmes.service.MesXslStompNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
/**
* @Description: 原材料卡片
@@ -34,10 +57,21 @@ import org.apache.shiro.authz.annotation.RequiresPermissions;
@RequestMapping("/xslmes/mesXslRawMaterialCard")
@Slf4j
public class MesXslRawMaterialCardController extends JeecgController<MesXslRawMaterialCard, IMesXslRawMaterialCardService> {
@Autowired
private IMesXslRawMaterialCardService mesXslRawMaterialCardService;
@Autowired
private MesXslStompNotifyService stompNotify;
@Autowired
private PrintServerEnvironmentService printServerEnvironmentService;
@Autowired
private PrintServerPdfJobService printServerPdfJobService;
@Autowired
private IPrintBizTemplateBindService printBizTemplateBindService;
@Autowired
private IPrintTemplateService printTemplateService;
@Autowired
private ObjectMapper objectMapper;
/**
* 分页列表查询
@@ -48,7 +82,36 @@ public class MesXslRawMaterialCardController extends JeecgController<MesXslRawMa
@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
HttpServletRequest req) {
// 库区条件:去掉实体上的值避免 QueryGenerator 再拼一班;用 TRIM 与看板聚合一致(避免首尾空格导致「有汇总无明细」)
String rawWarehouseArea = mesXslRawMaterialCard != null ? mesXslRawMaterialCard.getWarehouseArea() : null;
String areaEq = oConvertUtils.isNotEmpty(rawWarehouseArea) ? rawWarehouseArea.trim() : "";
boolean filterByWarehouseArea = !areaEq.isEmpty();
if (filterByWarehouseArea) {
mesXslRawMaterialCard.setWarehouseArea(null);
}
QueryWrapper<MesXslRawMaterialCard> queryWrapper = QueryGenerator.initQueryWrapper(mesXslRawMaterialCard, req.getParameterMap());
if (filterByWarehouseArea) {
queryWrapper.apply("TRIM(COALESCE(warehouse_area,'')) = {0}", areaEq);
}
// 看板等扩展查询remaining_quantity「有剩余 / 无剩余」(非实体字段,单独拼条件)
String remainQtyFilter = req.getParameter("remainQtyFilter");
if ("has".equals(remainQtyFilter)) {
queryWrapper.gt("remaining_quantity", 0);
} else if ("none".equals(remainQtyFilter)) {
queryWrapper.and(w -> w.isNull("remaining_quantity").or().le("remaining_quantity", 0));
}
String mixKw = req.getParameter("mixKeyword");
if (StringUtils.isNotBlank(mixKw)) {
final String kw = mixKw.trim();
queryWrapper.and(
w -> w.like("barcode", kw)
.or()
.like("batch_no", kw)
.or()
.like("material_name", kw)
.or()
.like("material_id", kw));
}
Page<MesXslRawMaterialCard> page = new Page<>(pageNo, pageSize);
IPage<MesXslRawMaterialCard> pageList = mesXslRawMaterialCardService.page(page, queryWrapper);
return Result.OK(pageList);
@@ -122,6 +185,88 @@ public class MesXslRawMaterialCardController extends JeecgController<MesXslRawMa
return Result.OK("批量删除成功!");
}
/**
* 查询可用打印机(与 /print/template/queryPrinters 返回结构一致)
*/
@Operation(summary = "原材料卡片-查询可用打印机")
@GetMapping(value = "/queryPrinters")
/** 有 list 可进页拉打印机;有 edit 可打印拉打印机,避免单权限缺另一项时 403 */
@RequiresPermissions(
value = {"xslmes:mes_xsl_raw_material_card:list", "xslmes:mes_xsl_raw_material_card:edit"},
logical = Logical.OR)
public Result<Map<String, Object>> queryPrinters() {
return Result.OK(printServerEnvironmentService.buildPrinterQueryResult());
}
/**
* 根据业务打印绑定生成模板 JSON + 映射后的 printData供前端生成 PDF 后调用 printPdf
*/
@Operation(summary = "原材料卡片-准备原生打印数据")
@GetMapping(value = "/prepareNativePrint")
/** 与 printPdf 一致:准备模板与打印数据属于「打印」动作,使用 edit 权限 */
@RequiresPermissions("xslmes:mes_xsl_raw_material_card:edit")
public Result<Map<String, Object>> prepareNativePrint(@RequestParam(name = "id") String id) {
try {
MesXslRawMaterialCard card = mesXslRawMaterialCardService.getById(id);
if (card == null) {
return Result.error("未找到原材料卡片");
}
PrintBizTemplateBind bind =
printBizTemplateBindService.getByBizCode(MesXslPrintConstants.RAW_MATERIAL_CARD_PERM_ID);
if (bind == null) {
return Result.error("请先在「业务打印绑定」中配置原材料卡片与打印模板");
}
PrintTemplate tpl = printTemplateService.getById(bind.getTemplateId());
if (tpl == null) {
return Result.error("绑定的打印模板不存在");
}
ArrayNode mapping =
PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson());
JsonNode bizRoot = objectMapper.valueToTree(card);
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping);
PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson());
Map<String, Object> out = new HashMap<>(8);
out.put("cardId", card.getId());
out.put("templateCode", bind.getTemplateCode());
out.put("templateJson", tpl.getTemplateJson());
out.put("paperWidthMm", tpl.getPaperWidthMm());
out.put("paperHeightMm", tpl.getPaperHeightMm());
out.put("paperOrientation", tpl.getPaperOrientation());
out.put("printData", objectMapper.convertValue(printData, Map.class));
return Result.OK(out);
} catch (Exception e) {
log.error("原材料卡片准备打印数据失败 id={}", id, e);
return Result.error("准备打印数据失败: " + e.getMessage());
}
}
/**
* 将前端生成的 PDF Base64 提交到服务器打印机(与 /print/template/directPrintPdf 一致)
*/
@AutoLog(value = "原材料卡片-PDF后端打印")
@Operation(summary = "原材料卡片-PDF后端打印")
@PostMapping(value = "/printPdf")
@RequiresPermissions("xslmes:mes_xsl_raw_material_card:edit")
public Result<String> printPdf(@RequestBody Map<String, Object> body) {
String id = String.valueOf(body.getOrDefault("id", "")).trim();
String printerName = String.valueOf(body.getOrDefault("printerName", "")).trim();
String pdfBase64 = String.valueOf(body.getOrDefault("pdfBase64", "")).trim();
String fileName = String.valueOf(body.getOrDefault("fileName", "")).trim();
if (StringUtils.isBlank(id)) {
return Result.error("id 不能为空");
}
MesXslRawMaterialCard card = mesXslRawMaterialCardService.getById(id);
if (card == null) {
return Result.error("未找到原材料卡片");
}
String prefix =
StringUtils.isNotBlank(card.getBarcode()) ? card.getBarcode() : card.getId();
String fn =
StringUtils.isNotBlank(fileName) ? fileName : ("原材料卡片-" + prefix + ".pdf");
return printServerPdfJobService.submitPdfBase64(
printerName, pdfBase64, fn, "RAW_CARD_" + prefix);
}
/**
* 通过id查询
*/

View File

@@ -1,28 +1,50 @@
package org.jeecg.modules.xslmes.controller;
import java.util.Arrays;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.xslmes.entity.MesXslRawMaterialEntry;
import org.jeecg.modules.xslmes.service.IMesXslRawMaterialEntryService;
import org.jeecg.modules.xslmes.service.MesXslStompNotifyService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.v3.oas.annotations.Operation;
import org.jeecg.common.aspect.annotation.AutoLog;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.print.entity.PrintBizTemplateBind;
import org.jeecg.modules.print.entity.PrintTemplate;
import org.jeecg.modules.print.service.IPrintBizTemplateBindService;
import org.jeecg.modules.print.service.IPrintTemplateService;
import org.jeecg.modules.print.support.PrintServerEnvironmentService;
import org.jeecg.modules.print.support.PrintServerPdfJobService;
import org.jeecg.modules.print.util.PrintBizDataMappingUtil;
import org.jeecg.modules.xslmes.constant.MesXslPrintConstants;
import org.jeecg.modules.xslmes.entity.MesXslRawMaterialEntry;
import org.jeecg.modules.xslmes.service.IMesXslRawMaterialEntryService;
import org.jeecg.modules.xslmes.service.MesXslStompNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
/**
* @Description: 原料入场记录
@@ -40,6 +62,16 @@ public class MesXslRawMaterialEntryController extends JeecgController<MesXslRawM
private IMesXslRawMaterialEntryService mesXslRawMaterialEntryService;
@Autowired
private MesXslStompNotifyService stompNotify;
@Autowired
private PrintServerEnvironmentService printServerEnvironmentService;
@Autowired
private PrintServerPdfJobService printServerPdfJobService;
@Autowired
private IPrintBizTemplateBindService printBizTemplateBindService;
@Autowired
private IPrintTemplateService printTemplateService;
@Autowired
private ObjectMapper objectMapper;
@Operation(summary = "原料入场记录-分页列表查询")
@GetMapping(value = "/list")
@@ -117,6 +149,79 @@ public class MesXslRawMaterialEntryController extends JeecgController<MesXslRawM
return Result.OK(mesXslRawMaterialEntry);
}
@Operation(summary = "原料入场记录-查询可用打印机")
@GetMapping(value = "/queryPrinters")
@RequiresPermissions(
value = {"xslmes:mes_xsl_raw_material_entry:list", "xslmes:mes_xsl_raw_material_entry:edit"},
logical = Logical.OR)
public Result<Map<String, Object>> queryPrinters() {
return Result.OK(printServerEnvironmentService.buildPrinterQueryResult());
}
/**
* 根据业务打印绑定生成模板 JSON + 映射后的 printData供前端生成 PDF 后调用 printPdf
*/
@Operation(summary = "原料入场记录-准备原生打印数据")
@GetMapping(value = "/prepareNativePrint")
@RequiresPermissions("xslmes:mes_xsl_raw_material_entry:edit")
public Result<Map<String, Object>> prepareNativePrint(@RequestParam(name = "id") String id) {
try {
MesXslRawMaterialEntry entry = mesXslRawMaterialEntryService.getById(id);
if (entry == null) {
return Result.error("未找到原料入场记录");
}
PrintBizTemplateBind bind =
printBizTemplateBindService.getByBizCode(MesXslPrintConstants.RAW_MATERIAL_ENTRY_PERM_ID);
if (bind == null) {
return Result.error("请先在「业务打印绑定」中配置原料入场记录与打印模板");
}
PrintTemplate tpl = printTemplateService.getById(bind.getTemplateId());
if (tpl == null) {
return Result.error("绑定的打印模板不存在");
}
ArrayNode mapping = PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson());
JsonNode bizRoot = objectMapper.valueToTree(entry);
ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping);
PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson());
Map<String, Object> out = new HashMap<>(8);
out.put("entryId", entry.getId());
out.put("templateCode", bind.getTemplateCode());
out.put("templateJson", tpl.getTemplateJson());
out.put("paperWidthMm", tpl.getPaperWidthMm());
out.put("paperHeightMm", tpl.getPaperHeightMm());
out.put("paperOrientation", tpl.getPaperOrientation());
out.put("printData", objectMapper.convertValue(printData, Map.class));
return Result.OK(out);
} catch (Exception e) {
log.error("原料入场记录准备打印数据失败 id={}", id, e);
return Result.error("准备打印数据失败: " + e.getMessage());
}
}
@AutoLog(value = "原料入场记录-PDF后端打印")
@Operation(summary = "原料入场记录-PDF后端打印")
@PostMapping(value = "/printPdf")
@RequiresPermissions("xslmes:mes_xsl_raw_material_entry:edit")
public Result<String> printPdf(@RequestBody Map<String, Object> body) {
String id = String.valueOf(body.getOrDefault("id", "")).trim();
String printerName = String.valueOf(body.getOrDefault("printerName", "")).trim();
String pdfBase64 = String.valueOf(body.getOrDefault("pdfBase64", "")).trim();
String fileName = String.valueOf(body.getOrDefault("fileName", "")).trim();
if (StringUtils.isBlank(id)) {
return Result.error("id 不能为空");
}
MesXslRawMaterialEntry entry = mesXslRawMaterialEntryService.getById(id);
if (entry == null) {
return Result.error("未找到原料入场记录");
}
String prefix =
StringUtils.isNotBlank(entry.getBarcode()) ? entry.getBarcode() : entry.getId();
String fn =
StringUtils.isNotBlank(fileName) ? fileName : ("原料入场记录-" + prefix + ".pdf");
return printServerPdfJobService.submitPdfBase64(
printerName, pdfBase64, fn, "RAW_ENTRY_" + prefix);
}
@RequiresPermissions("xslmes:mes_xsl_raw_material_entry:exportXls")
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, MesXslRawMaterialEntry mesXslRawMaterialEntry) {

View File

@@ -0,0 +1,38 @@
package org.jeecg.modules.xslmes.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.xslmes.service.IMesXslRawMaterialWarehouseBoardService;
import org.jeecg.modules.xslmes.vo.MesXslRawMaterialWarehouseBoardVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* 原材料库区看板:库区主数据 + 原材料卡片聚合
*/
@Tag(name = "原材料库区看板")
@RestController
@RequestMapping("/xslmes/mesXslRawMaterialWarehouseBoard")
@Slf4j
public class MesXslRawMaterialWarehouseBoardController {
@Autowired
private IMesXslRawMaterialWarehouseBoardService mesXslRawMaterialWarehouseBoardService;
@Operation(summary = "原材料库区看板-汇总数据")
@RequiresPermissions("xslmes:mes_xsl_raw_material_warehouse_board:list")
@GetMapping(value = "/board")
public Result<MesXslRawMaterialWarehouseBoardVO> board(
@RequestParam(name = "warehouseId", required = false) String warehouseId,
@RequestParam(name = "keyword", required = false) String keyword,
@RequestParam(name = "measureType", required = false) String measureType) {
MesXslRawMaterialWarehouseBoardVO data = mesXslRawMaterialWarehouseBoardService.queryBoard(warehouseId, keyword, measureType);
return Result.OK(data);
}
}

View File

@@ -3,6 +3,7 @@ package org.jeecg.modules.xslmes.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
@@ -13,15 +14,22 @@ import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea;
import org.jeecg.modules.xslmes.service.IMesXslWarehouseAreaService;
import org.jeecg.modules.xslmes.service.MesXslStompNotifyService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
@@ -36,6 +44,9 @@ public class MesXslWarehouseAreaController extends JeecgController<MesXslWarehou
@Autowired
private IMesXslWarehouseAreaService mesXslWarehouseAreaService;
@Autowired
private JeecgBaseConfig jeecgBaseConfig;
@Autowired
private MesXslStompNotifyService stompNotify;
@@ -49,6 +60,7 @@ public class MesXslWarehouseAreaController extends JeecgController<MesXslWarehou
QueryWrapper<MesXslWarehouseArea> queryWrapper = QueryGenerator.initQueryWrapper(mesXslWarehouseArea, req.getParameterMap());
Page<MesXslWarehouseArea> page = new Page<>(pageNo, pageSize);
IPage<MesXslWarehouseArea> pageList = mesXslWarehouseAreaService.page(page, queryWrapper);
mesXslWarehouseAreaService.enrichDisplayedActualCapacity(pageList.getRecords());
return Result.OK(pageList);
}
@@ -166,13 +178,33 @@ public class MesXslWarehouseAreaController extends JeecgController<MesXslWarehou
if (entity == null) {
return Result.error("未找到对应数据");
}
mesXslWarehouseAreaService.enrichDisplayedActualCapacity(Collections.singletonList(entity));
return Result.OK(entity);
}
@RequiresPermissions("xslmes:mes_xsl_warehouse_area:exportXls")
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, MesXslWarehouseArea mesXslWarehouseArea) {
return super.exportXls(request, mesXslWarehouseArea, MesXslWarehouseArea.class, "MES库区管理");
QueryWrapper<MesXslWarehouseArea> queryWrapper = QueryGenerator.initQueryWrapper(mesXslWarehouseArea, request.getParameterMap());
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
String selections = request.getParameter("selections");
if (oConvertUtils.isNotEmpty(selections)) {
queryWrapper.in("id", Arrays.asList(selections.split(",")));
}
List<MesXslWarehouseArea> exportList = mesXslWarehouseAreaService.list(queryWrapper);
mesXslWarehouseAreaService.enrichDisplayedActualCapacity(exportList);
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
mv.addObject(NormalExcelConstants.FILE_NAME, "MES库区管理");
mv.addObject(NormalExcelConstants.CLASS, MesXslWarehouseArea.class);
ExportParams exportParams = new ExportParams("MES库区管理报表", "导出人:" + sysUser.getRealname(), "MES库区管理", ExcelType.XSSF);
exportParams.setImageBasePath(jeecgBaseConfig.getPath().getUpload());
mv.addObject(NormalExcelConstants.PARAMS, exportParams);
mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
String exportFields = request.getParameter(NormalExcelConstants.EXPORT_FIELDS);
if (oConvertUtils.isNotEmpty(exportFields)) {
mv.addObject(NormalExcelConstants.EXPORT_FIELDS, exportFields);
}
return mv;
}
@RequiresPermissions("xslmes:mes_xsl_warehouse_area:importExcel")

View File

@@ -0,0 +1,20 @@
package org.jeecg.modules.xslmes.dto;
import lombok.Data;
import java.io.Serializable;
/**
* 按库区(trim 后编码)聚合剩余数量汇总
*/
@Data
public class MesXslAreaRemainQtySumDTO implements Serializable {
private static final long serialVersionUID = 1L;
/** 库区编码(已 trim */
private String areaCode;
/** 剩余数量合计 */
private Long qtySum;
}

View File

@@ -0,0 +1,68 @@
package org.jeecg.modules.xslmes.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
/**
* 业务实体字段配置子表:一类明细表对应一行,字段清单存 JSON。
*/
@Data
@TableName("mes_xsl_biz_entity_field_detail")
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
@Schema(description = "业务实体字段配置-明细表字段清单")
public class MesXslBizEntityFieldDetail implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "主键")
private String id;
@Schema(description = "主表ID")
private String profileId;
@Schema(description = "主实体上明细属性名(与打印绑定 detailProperty 一致,如 lines")
private String detailPropertyName;
@Schema(description = "槽位类型LIST 或 OBJECT")
private String detailSlotKind;
@Schema(description = "明细展示名称")
private String detailName;
@Schema(description = "明细实体 Java 全限定类名")
private String detailEntityClassName;
/** 明细表字段列表 JSON */
@Schema(description = "明细表字段列表JSON 数组)")
private String detailFieldsJson;
@Schema(description = "排序号")
private Integer sortNo;
@Schema(description = "创建人")
private String createBy;
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "创建时间")
private Date createTime;
@Schema(description = "更新人")
private String updateBy;
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "更新时间")
private Date updateTime;
}

View File

@@ -0,0 +1,72 @@
package org.jeecg.modules.xslmes.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
/**
* 业务实体字段配置主表:业务名称、主实体类名、主表字段 JSON明细通过 detailList 关联子表。
*/
@Data
@TableName("mes_xsl_biz_entity_field_profile")
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
@Schema(description = "业务实体字段配置主表")
public class MesXslBizEntityFieldProfile implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "主键")
private String id;
@Schema(description = "业务名称")
private String businessName;
@Schema(description = "业务编码(菜单 permission id与业务打印绑定 biz_code、print_biz_perm_entity.perm_id 一致)")
private String businessCode;
@Schema(description = "主实体 Java 全限定类名")
private String entityClassName;
/** 主表实体字段列表 JSON */
@Schema(description = "主表实体字段列表JSON 数组)")
private String mainFieldsJson;
@Schema(description = "备注")
private String remark;
@Schema(description = "租户ID")
private Integer tenantId;
@Schema(description = "创建人")
private String createBy;
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "创建时间")
private Date createTime;
@Schema(description = "更新人")
private String updateBy;
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "更新时间")
private Date updateTime;
/** 各明细表对应的字段清单(不落主表) */
@TableField(exist = false)
@Schema(description = "明细表字段配置列表")
private List<MesXslBizEntityFieldDetail> detailList;
}

View File

@@ -0,0 +1,8 @@
package org.jeecg.modules.xslmes.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldDetail;
@Mapper
public interface MesXslBizEntityFieldDetailMapper extends BaseMapper<MesXslBizEntityFieldDetail> {}

View File

@@ -0,0 +1,8 @@
package org.jeecg.modules.xslmes.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldProfile;
@Mapper
public interface MesXslBizEntityFieldProfileMapper extends BaseMapper<MesXslBizEntityFieldProfile> {}

View File

@@ -1,7 +1,12 @@
package org.jeecg.modules.xslmes.mapper;
import org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.jeecg.modules.xslmes.dto.MesXslAreaRemainQtySumDTO;
import org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard;
import java.util.Collection;
import java.util.List;
/**
* @Description: 原材料卡片
@@ -10,4 +15,9 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
* @Version: V1.0
*/
public interface MesXslRawMaterialCardMapper extends BaseMapper<MesXslRawMaterialCard> {
/**
* 按 trim 后的库区编码汇总原材料卡片剩余数量(当前租户由拦截器补齐)
*/
List<MesXslAreaRemainQtySumDTO> sumRemainingQtyByTrimmedWarehouseArea(@Param("areaCodes") Collection<String> areaCodes);
}

View File

@@ -1,4 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.jeecg.modules.xslmes.mapper.MesXslRawMaterialCardMapper">
<!-- 库区编码已与卡片 warehouse_area 按 TRIM 对齐(见库区/卡片筛选逻辑) -->
<select id="sumRemainingQtyByTrimmedWarehouseArea"
resultType="org.jeecg.modules.xslmes.dto.MesXslAreaRemainQtySumDTO">
SELECT TRIM(t.warehouse_area) AS areaCode,
COALESCE(SUM(COALESCE(t.remaining_quantity, 0)), 0) AS qtySum
FROM mes_xsl_raw_material_card t
WHERE t.warehouse_area IS NOT NULL
AND TRIM(t.warehouse_area) != ''
AND TRIM(t.warehouse_area) IN
<foreach collection="areaCodes" item="c" open="(" separator="," close=")">
#{c}
</foreach>
GROUP BY TRIM(t.warehouse_area)
</select>
</mapper>

View File

@@ -0,0 +1,226 @@
package org.jeecg.modules.xslmes.print.catalog;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.print.catalog.IPrintBizEntityFieldCatalogProvider;
import org.jeecg.modules.print.vo.PrintBizDetailSlotVO;
import org.jeecg.modules.print.vo.PrintBizFieldItemVO;
import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldDetail;
import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldProfile;
import org.jeecg.modules.xslmes.mapper.MesXslBizEntityFieldDetailMapper;
import org.jeecg.modules.xslmes.service.IMesXslBizEntityFieldProfileService;
import org.springframework.stereotype.Component;
/**
* 将 mes_xsl_biz_entity_field_* 中的缓存提供给打印绑定接口SPI 实现)。
*
* <p>bizCode = {@code print_biz_perm_entity.perm_id}。
*
* <p>「新增绑定」下拉组装时对每条业务若单独查库会产生严重 N+1{@link #beginBulkLookup(Collection)} 在同一请求线程内改为单次 IN 查询。
*/
@Slf4j
@Component
public class PrintBizEntityFieldCatalogProviderImpl implements IPrintBizEntityFieldCatalogProvider {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/** null=非批量模式;非 null=批量模式(可能为空 Map */
private static final ThreadLocal<Map<String, MesXslBizEntityFieldProfile>> BULK_PROFILE_BY_CODE =
new ThreadLocal<>();
@Resource
private IMesXslBizEntityFieldProfileService bizEntityFieldProfileService;
@Resource
private MesXslBizEntityFieldDetailMapper detailMapper;
@Override
public void beginBulkLookup(Collection<String> bizCodes) {
endBulkLookup();
if (bizCodes == null || bizCodes.isEmpty()) {
BULK_PROFILE_BY_CODE.set(Collections.emptyMap());
return;
}
List<String> ids =
bizCodes.stream()
.filter(StringUtils::isNotBlank)
.map(String::trim)
.distinct()
.collect(Collectors.toList());
if (ids.isEmpty()) {
BULK_PROFILE_BY_CODE.set(Collections.emptyMap());
return;
}
List<MesXslBizEntityFieldProfile> list =
bizEntityFieldProfileService
.lambdaQuery()
.in(MesXslBizEntityFieldProfile::getBusinessCode, ids)
.list();
Map<String, MesXslBizEntityFieldProfile> map = new HashMap<>(Math.max(16, list.size() * 2));
for (MesXslBizEntityFieldProfile p : list) {
if (p != null && StringUtils.isNotBlank(p.getBusinessCode())) {
map.put(p.getBusinessCode().trim(), p);
}
}
BULK_PROFILE_BY_CODE.set(map);
}
@Override
public void endBulkLookup() {
BULK_PROFILE_BY_CODE.remove();
}
/** 批量模式下读线程 Map否则单次按编码查询 */
private MesXslBizEntityFieldProfile resolveProfile(String bizCode) {
if (StringUtils.isBlank(bizCode)) {
return null;
}
Map<String, MesXslBizEntityFieldProfile> bulk = BULK_PROFILE_BY_CODE.get();
if (bulk != null) {
return bulk.get(bizCode.trim());
}
return bizEntityFieldProfileService.getByBusinessCode(bizCode);
}
@Override
public String getEntityClassFqn(String bizCode) {
MesXslBizEntityFieldProfile p = resolveProfile(bizCode);
return p != null ? StringUtils.trimToNull(p.getEntityClassName()) : null;
}
@Override
public boolean hasCatalogForBiz(String bizCode) {
return resolveProfile(bizCode) != null;
}
@Override
public List<PrintBizFieldItemVO> listMainFields(String bizCode) {
MesXslBizEntityFieldProfile p = resolveProfile(bizCode);
if (p == null) {
return Collections.emptyList();
}
return parseFieldItems(p.getMainFieldsJson());
}
@Override
public List<PrintBizDetailSlotVO> listDetailSlots(String bizCode) {
MesXslBizEntityFieldProfile p = resolveProfile(bizCode);
if (p == null || StringUtils.isBlank(p.getId())) {
return Collections.emptyList();
}
List<MesXslBizEntityFieldDetail> lines =
detailMapper.selectList(
new LambdaQueryWrapper<MesXslBizEntityFieldDetail>()
.eq(MesXslBizEntityFieldDetail::getProfileId, p.getId())
.orderByAsc(MesXslBizEntityFieldDetail::getSortNo)
.orderByAsc(MesXslBizEntityFieldDetail::getId));
List<PrintBizDetailSlotVO> out = new ArrayList<>();
for (MesXslBizEntityFieldDetail line : lines) {
if (StringUtils.isBlank(line.getDetailPropertyName())) {
continue;
}
out.add(
new PrintBizDetailSlotVO(
line.getDetailPropertyName(),
StringUtils.defaultString(line.getDetailEntityClassName()),
StringUtils.defaultIfBlank(line.getDetailSlotKind(), "LIST"),
StringUtils.defaultIfBlank(line.getDetailName(), line.getDetailPropertyName())));
}
return out;
}
@Override
public List<PrintBizFieldItemVO> listPrefixedDetailFields(String bizCode, String detailProperty, String slotKind) {
if (StringUtils.isAnyBlank(bizCode, detailProperty)) {
return Collections.emptyList();
}
MesXslBizEntityFieldProfile p = resolveProfile(bizCode);
if (p == null || StringUtils.isBlank(p.getId())) {
return Collections.emptyList();
}
String prop = detailProperty.trim();
String reqKind = StringUtils.trimToEmpty(slotKind);
List<MesXslBizEntityFieldDetail> lines =
detailMapper.selectList(
new LambdaQueryWrapper<MesXslBizEntityFieldDetail>()
.eq(MesXslBizEntityFieldDetail::getProfileId, p.getId()));
MesXslBizEntityFieldDetail hit = null;
for (MesXslBizEntityFieldDetail line : lines) {
if (!prop.equals(line.getDetailPropertyName())) {
continue;
}
if (!slotKindMatch(reqKind, line.getDetailSlotKind())) {
continue;
}
hit = line;
break;
}
if (hit == null) {
return Collections.emptyList();
}
List<PrintBizFieldItemVO> raw = parseFieldItems(hit.getDetailFieldsJson());
List<PrintBizFieldItemVO> out = new ArrayList<>(raw.size());
for (PrintBizFieldItemVO x : raw) {
String path = prop + "." + x.getFieldKey();
String label = "明细「" + prop + "」→ " + x.getLabel();
out.add(PrintBizFieldItemVO.copyWithPrefixedPath(x, path, label));
}
return out;
}
private static boolean slotKindMatch(String requested, String stored) {
String r = StringUtils.trimToEmpty(requested);
String s = StringUtils.trimToEmpty(stored);
if (StringUtils.isBlank(s)) {
return true;
}
if (StringUtils.isBlank(r)) {
return true;
}
return r.equalsIgnoreCase(s);
}
/** 解析 JSON 数组:支持 VO 对象元素或纯字符串字段名 */
private List<PrintBizFieldItemVO> parseFieldItems(String json) {
if (StringUtils.isBlank(json)) {
return Collections.emptyList();
}
try {
JsonNode root = OBJECT_MAPPER.readTree(json);
if (!root.isArray()) {
return Collections.emptyList();
}
List<PrintBizFieldItemVO> out = new ArrayList<>();
for (JsonNode n : root) {
if (n.isTextual()) {
String k = n.asText();
if (StringUtils.isNotBlank(k)) {
out.add(PrintBizFieldItemVO.plainStringField(k));
}
continue;
}
if (n.isObject()) {
PrintBizFieldItemVO vo = OBJECT_MAPPER.treeToValue(n, PrintBizFieldItemVO.class);
if (vo != null && StringUtils.isNotBlank(vo.getFieldKey())) {
out.add(vo);
}
}
}
return out;
} catch (Exception e) {
log.warn("解析业务实体字段缓存 JSON 失败: {}", e.getMessage());
return Collections.emptyList();
}
}
}

View File

@@ -0,0 +1,40 @@
package org.jeecg.modules.xslmes.service;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldDetail;
import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldProfile;
/** 业务实体字段配置(主子表) */
public interface IMesXslBizEntityFieldProfileService extends IService<MesXslBizEntityFieldProfile> {
/** 按业务编码(菜单 permission id查询主表不含 detailList */
MesXslBizEntityFieldProfile getByBusinessCode(String businessCode);
/**
* 按业务编码 upsert用于启动扫描写入明细全量替换。
*
* @param businessCode 与 print_biz_perm_entity.perm_id、biz_code 一致
*/
void upsertScannedProfile(
String businessCode,
String businessName,
String entityFqn,
String mainFieldsJson,
List<MesXslBizEntityFieldDetail> detailRows);
/** 新增主表并保存明细 */
void saveWithDetails(MesXslBizEntityFieldProfile profile);
/** 更新主表并重写明细 */
void updateWithDetails(MesXslBizEntityFieldProfile profile);
/** 按主键删除主表及明细 */
void removeWithDetails(String id);
/** 批量删除主表及明细 */
void removeBatchWithDetails(java.util.Collection<String> ids);
/** 查询主表并填充 detailList */
MesXslBizEntityFieldProfile getByIdWithDetails(String id);
}

View File

@@ -0,0 +1,18 @@
package org.jeecg.modules.xslmes.service;
import org.jeecg.modules.xslmes.vo.MesXslRawMaterialWarehouseBoardVO;
/**
* 原材料库区看板(库区 + 原材料卡片聚合)
*/
public interface IMesXslRawMaterialWarehouseBoardService {
/**
* 聚合看板数据
*
* @param warehouseId 所属仓库ID可空表示全部启用库区
* @param keyword 物料名称/条码/批次模糊筛选(可空);非空时仅展示仍有匹配卡片的库区
* @param measureType quantity=占用率按剩余数量与 maxCapacity 对齐weight=按剩余重量
*/
MesXslRawMaterialWarehouseBoardVO queryBoard(String warehouseId, String keyword, String measureType);
}

View File

@@ -3,6 +3,8 @@ package org.jeecg.modules.xslmes.service;
import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea;
import java.util.Collection;
/**
* MES 库区管理
*/
@@ -12,4 +14,9 @@ public interface IMesXslWarehouseAreaService extends IService<MesXslWarehouseAre
* 同租户下是否已存在相同库区编码(编辑时传 excludeId 排除自身)
*/
boolean existsSameAreaCode(String areaCode, String excludeId);
/**
* 按配置策略回填列表中的「实际存放量」展示值(不写库)
*/
void enrichDisplayedActualCapacity(Collection<MesXslWarehouseArea> areas);
}

View File

@@ -70,6 +70,11 @@ public class MesXslStompNotifyService {
publish("/topic/sync/mes-warehouse-areas", "MES_WAREHOUSE_AREA_CHANGED", "warehouseAreaId", warehouseAreaId, action);
}
/** 广播打印模板变更事件到 /topic/sync/print-templates */
public void publishPrintTemplateChanged(String action, String templateId) {
publish("/topic/sync/print-templates", "PRINT_TEMPLATE_CHANGED", "templateId", templateId, action);
}
// ─────────────────────────── 私有辅助 ────────────────────────────
private void publish(String topic, String cmd, String idKey, String idValue, String action) {

View File

@@ -0,0 +1,164 @@
package org.jeecg.modules.xslmes.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldDetail;
import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldProfile;
import org.jeecg.modules.xslmes.mapper.MesXslBizEntityFieldDetailMapper;
import org.jeecg.modules.xslmes.mapper.MesXslBizEntityFieldProfileMapper;
import org.jeecg.modules.xslmes.service.IMesXslBizEntityFieldProfileService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class MesXslBizEntityFieldProfileServiceImpl extends ServiceImpl<MesXslBizEntityFieldProfileMapper, MesXslBizEntityFieldProfile>
implements IMesXslBizEntityFieldProfileService {
/** 标记为启动任务根据 print_biz_perm_entity 写入,便于区分手工维护数据 */
private static final String REMARK_PRINT_PERM_SCAN = "print_biz_perm_entity 启动异步扫描";
@Resource
private MesXslBizEntityFieldDetailMapper detailMapper;
@Override
public MesXslBizEntityFieldProfile getByBusinessCode(String businessCode) {
if (StringUtils.isBlank(businessCode)) {
return null;
}
return this.lambdaQuery()
.eq(MesXslBizEntityFieldProfile::getBusinessCode, businessCode.trim())
.last("LIMIT 1")
.one();
}
@Override
@Transactional(rollbackFor = Exception.class)
public void upsertScannedProfile(
String businessCode,
String businessName,
String entityFqn,
String mainFieldsJson,
List<MesXslBizEntityFieldDetail> detailRows) {
if (StringUtils.isBlank(businessCode)) {
return;
}
String code = businessCode.trim();
Date now = new Date();
MesXslBizEntityFieldProfile existing = getByBusinessCode(code);
if (existing == null) {
MesXslBizEntityFieldProfile p = new MesXslBizEntityFieldProfile();
p.setBusinessCode(code);
p.setBusinessName(StringUtils.defaultIfBlank(businessName, code));
p.setEntityClassName(entityFqn);
p.setMainFieldsJson(mainFieldsJson);
p.setRemark(REMARK_PRINT_PERM_SCAN);
p.setCreateTime(now);
p.setUpdateTime(now);
p.setDetailList(detailRows != null ? detailRows : List.of());
saveWithDetails(p);
return;
}
existing.setBusinessName(StringUtils.defaultIfBlank(businessName, existing.getBusinessName()));
existing.setEntityClassName(entityFqn);
existing.setMainFieldsJson(mainFieldsJson);
existing.setRemark(REMARK_PRINT_PERM_SCAN);
existing.setUpdateTime(now);
existing.setDetailList(detailRows != null ? detailRows : List.of());
updateWithDetails(existing);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void saveWithDetails(MesXslBizEntityFieldProfile profile) {
this.save(profile);
insertDetailRows(profile);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateWithDetails(MesXslBizEntityFieldProfile profile) {
this.updateById(profile);
detailMapper.delete(new LambdaQueryWrapper<MesXslBizEntityFieldDetail>().eq(MesXslBizEntityFieldDetail::getProfileId, profile.getId()));
insertDetailRows(profile);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void removeWithDetails(String id) {
if (StringUtils.isBlank(id)) {
return;
}
detailMapper.delete(new LambdaQueryWrapper<MesXslBizEntityFieldDetail>().eq(MesXslBizEntityFieldDetail::getProfileId, id));
this.removeById(id);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void removeBatchWithDetails(Collection<String> ids) {
if (ids == null || ids.isEmpty()) {
return;
}
List<String> trimmed = new ArrayList<>();
for (String id : ids) {
if (StringUtils.isNotBlank(id)) {
String t = id.trim();
trimmed.add(t);
detailMapper.delete(new LambdaQueryWrapper<MesXslBizEntityFieldDetail>().eq(MesXslBizEntityFieldDetail::getProfileId, t));
}
}
if (!trimmed.isEmpty()) {
this.removeByIds(trimmed);
}
}
@Override
public MesXslBizEntityFieldProfile getByIdWithDetails(String id) {
MesXslBizEntityFieldProfile profile = this.getById(id);
if (profile == null) {
return null;
}
List<MesXslBizEntityFieldDetail> lines =
detailMapper.selectList(
new LambdaQueryWrapper<MesXslBizEntityFieldDetail>()
.eq(MesXslBizEntityFieldDetail::getProfileId, id)
.orderByAsc(MesXslBizEntityFieldDetail::getSortNo)
.orderByAsc(MesXslBizEntityFieldDetail::getId));
profile.setDetailList(lines);
return profile;
}
/** 写入子表(编辑时已清空旧数据) */
private void insertDetailRows(MesXslBizEntityFieldProfile profile) {
if (profile.getDetailList() == null || profile.getDetailList().isEmpty()) {
return;
}
Date now = new Date();
int seq = 0;
for (MesXslBizEntityFieldDetail row : profile.getDetailList()) {
row.setId(null);
row.setProfileId(profile.getId());
if (row.getSortNo() == null) {
row.setSortNo(seq++);
}
if (row.getCreateTime() == null) {
row.setCreateTime(now);
}
if (row.getUpdateTime() == null) {
row.setUpdateTime(now);
}
if (StringUtils.isBlank(row.getCreateBy())) {
row.setCreateBy(profile.getCreateBy());
}
if (StringUtils.isBlank(row.getUpdateBy())) {
row.setUpdateBy(profile.getUpdateBy());
}
detailMapper.insert(row);
}
}
}

View File

@@ -0,0 +1,248 @@
package org.jeecg.modules.xslmes.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard;
import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea;
import org.jeecg.modules.xslmes.service.IMesXslRawMaterialCardService;
import org.jeecg.modules.xslmes.service.IMesXslRawMaterialWarehouseBoardService;
import org.jeecg.modules.xslmes.service.IMesXslWarehouseAreaService;
import org.jeecg.modules.xslmes.vo.MesXslRawMaterialWarehouseBoardVO;
import org.jeecg.modules.xslmes.vo.MesXslRawMaterialWarehouseBoardVO.BoardAreaCardVO;
import org.jeecg.modules.xslmes.vo.MesXslRawMaterialWarehouseBoardVO.BoardBandVO;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* 原材料库区看板
*/
@Service
@RequiredArgsConstructor
public class MesXslRawMaterialWarehouseBoardServiceImpl implements IMesXslRawMaterialWarehouseBoardService {
private static final String MEASURE_WEIGHT = "weight";
/** 库区编码首段形如 1F、2P、03A 等,仅作看板分组带标题(与仓库分类层级无「楼层」对应关系) */
private static final Pattern BAND_FIRST_SEGMENT = Pattern.compile("^\\d+[A-Za-z]+$");
private final IMesXslWarehouseAreaService mesXslWarehouseAreaService;
private final IMesXslRawMaterialCardService mesXslRawMaterialCardService;
@Override
public MesXslRawMaterialWarehouseBoardVO queryBoard(String warehouseId, String keyword, String measureType) {
String mt = StringUtils.defaultIfBlank(measureType, "quantity").toLowerCase(Locale.ROOT).trim();
if (!MEASURE_WEIGHT.equals(mt)) {
mt = "quantity";
}
MesXslRawMaterialWarehouseBoardVO vo = new MesXslRawMaterialWarehouseBoardVO();
vo.setMeasureType(mt);
QueryWrapper<MesXslWarehouseArea> areaQw = new QueryWrapper<>();
areaQw.eq("status", "0");
if (StringUtils.isNotBlank(warehouseId)) {
areaQw.eq("warehouse_id", warehouseId.trim());
}
areaQw.orderByAsc("area_code");
List<MesXslWarehouseArea> areas = mesXslWarehouseAreaService.list(areaQw);
if (areas.isEmpty()) {
return vo;
}
mesXslWarehouseAreaService.enrichDisplayedActualCapacity(areas);
List<String> areaCodes = areas.stream().map(MesXslWarehouseArea::getAreaCode).filter(StringUtils::isNotBlank).map(String::trim).distinct().collect(Collectors.toList());
QueryWrapper<MesXslRawMaterialCard> cardQw = new QueryWrapper<>();
cardQw.in("warehouse_area", areaCodes);
cardQw.apply("(COALESCE(remaining_quantity,0) > 0 OR COALESCE(remaining_weight,0) > 0)");
String kw = StringUtils.trimToNull(keyword);
if (kw != null) {
cardQw.and(w ->
w.like("material_name", kw).or().like("barcode", kw).or().like("batch_no", kw));
}
List<MesXslRawMaterialCard> cards = mesXslRawMaterialCardService.list(cardQw);
Map<String, List<MesXslRawMaterialCard>> byArea =
cards.stream().filter(c -> StringUtils.isNotBlank(c.getWarehouseArea())).collect(Collectors.groupingBy(c -> c.getWarehouseArea().trim(), Collectors.toList()));
boolean filterByKeyword = kw != null;
Map<String, BoardBandVO> bandMap = new LinkedHashMap<>();
for (MesXslWarehouseArea area : areas) {
String code = StringUtils.trimToEmpty(area.getAreaCode());
if (code.isEmpty()) {
continue;
}
List<MesXslRawMaterialCard> list = byArea.getOrDefault(code, new ArrayList<>());
if (filterByKeyword && list.isEmpty()) {
continue;
}
BoardAreaCardVO cardVo = aggregateArea(area, list, mt);
BandKey bk = resolveBand(area.getAreaCode());
BoardBandVO band = bandMap.computeIfAbsent(bk.key, k -> {
BoardBandVO b = new BoardBandVO();
b.setBandKey(bk.key);
b.setBandLabel(bk.label);
b.setBandSort(bk.sort);
return b;
});
band.getAreas().add(cardVo);
}
List<BoardBandVO> bands =
bandMap.values().stream().sorted(Comparator.comparing(BoardBandVO::getBandSort, Comparator.nullsLast(Integer::compareTo)).thenComparing(BoardBandVO::getBandKey, Comparator.nullsLast(String::compareTo))).collect(Collectors.toList());
for (BoardBandVO band : bands) {
band.getAreas().sort(Comparator.comparing(BoardAreaCardVO::getAreaCode, Comparator.nullsLast(String::compareTo)));
}
vo.setBands(bands);
return vo;
}
private BoardAreaCardVO aggregateArea(MesXslWarehouseArea area, List<MesXslRawMaterialCard> list, String measureType) {
BoardAreaCardVO vo = new BoardAreaCardVO();
vo.setAreaId(area.getId());
vo.setAreaCode(area.getAreaCode());
vo.setAreaName(area.getAreaName());
vo.setWarehouseId(area.getWarehouseId());
vo.setWarehouseName(area.getWarehouseName());
vo.setMaxCapacity(area.getMaxCapacity());
vo.setActualCapacity(area.getActualCapacity());
vo.setCardCount(list.size());
int sumQty = 0;
BigDecimal sumW = BigDecimal.ZERO;
LinkedHashSet<String> materialNames = new LinkedHashSet<>();
for (MesXslRawMaterialCard c : list) {
if (c.getRemainingQuantity() != null) {
sumQty += c.getRemainingQuantity();
}
if (c.getRemainingWeight() != null) {
sumW = sumW.add(c.getRemainingWeight());
}
if (StringUtils.isNotBlank(c.getMaterialName())) {
materialNames.add(c.getMaterialName().trim());
}
}
vo.setCurrentQuantity(sumQty);
vo.setCurrentWeight(sumW.setScale(3, RoundingMode.HALF_UP));
vo.setMaterialKindCount(materialNames.size());
vo.setTopMaterialNames(materialNames.stream().limit(8).collect(Collectors.toList()));
Double usage = null;
Integer maxCap = area.getMaxCapacity();
if (maxCap != null && maxCap > 0) {
if (MEASURE_WEIGHT.equals(measureType)) {
usage = sumW.multiply(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(maxCap), 1, RoundingMode.HALF_UP).doubleValue();
} else {
usage = BigDecimal.valueOf(sumQty).multiply(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(maxCap), 1, RoundingMode.HALF_UP).doubleValue();
}
if (usage > 100) {
usage = 100d;
}
if (usage < 0) {
usage = 0d;
}
}
vo.setUsagePercent(usage);
vo.setAlertLevel(resolveAlert(usage, list.isEmpty()));
return vo;
}
private static String resolveAlert(Double usagePercent, boolean emptyCards) {
if (emptyCards) {
return "empty";
}
if (usagePercent == null) {
return "unknown";
}
if (usagePercent <= 0) {
return "empty";
}
if (usagePercent < 30) {
return "low";
}
if (usagePercent < 90) {
return "normal";
}
if (usagePercent < 100) {
return "high";
}
return "full";
}
private BandKey resolveBand(String areaCode) {
if (StringUtils.isBlank(areaCode)) {
return new BandKey("zzz_other", "其它", 999_000);
}
String trimmed = areaCode.trim();
String head = trimmed.contains("-") ? trimmed.substring(0, trimmed.indexOf('-')) : trimmed;
if (BAND_FIRST_SEGMENT.matcher(head).matches()) {
String normalized = normalizeBandToken(head);
int sort = bandSort(normalized);
return new BandKey(normalized.toLowerCase(Locale.ROOT), normalized, sort);
}
String label = StringUtils.left(head, 16);
if (label.isEmpty()) {
label = trimmed.length() > 16 ? trimmed.substring(0, 16) : trimmed;
}
return new BandKey("z_" + label.toLowerCase(Locale.ROOT), label, 888_000 + Math.abs(label.hashCode() % 1000));
}
private static String normalizeBandToken(String raw) {
if (raw == null) {
return "其它";
}
String s = raw.toUpperCase(Locale.ROOT);
s = s.replace('', 'F').replace('', 'P');
return s;
}
/**
* 简单排序按前缀中的数字升序1F&lt;2F&lt;10F末尾字母次之
*/
private static int bandSort(String label) {
String digits = "";
String tail = "";
for (int i = 0; i < label.length(); i++) {
char ch = label.charAt(i);
if (Character.isDigit(ch)) {
digits += ch;
} else {
tail = label.substring(i);
break;
}
}
int num = 0;
try {
if (!digits.isEmpty()) {
num = Integer.parseInt(digits);
}
} catch (NumberFormatException ignored) {
num = 0;
}
return num * 100 + Math.min(Math.abs(tail.hashCode() % 99), 99);
}
private static final class BandKey {
final String key;
final String label;
final int sort;
BandKey(String key, String label, int sort) {
this.key = key;
this.label = label;
this.sort = sort;
}
}
}

View File

@@ -1,18 +1,25 @@
package org.jeecg.modules.xslmes.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.xslmes.capacity.WarehouseAreaDisplayedActualCapacityMediator;
import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea;
import org.jeecg.modules.xslmes.mapper.MesXslWarehouseAreaMapper;
import org.jeecg.modules.xslmes.service.IMesXslWarehouseAreaService;
import org.springframework.stereotype.Service;
import java.util.Collection;
/**
* MES 库区管理
*/
@Service
@RequiredArgsConstructor
public class MesXslWarehouseAreaServiceImpl extends ServiceImpl<MesXslWarehouseAreaMapper, MesXslWarehouseArea> implements IMesXslWarehouseAreaService {
private final WarehouseAreaDisplayedActualCapacityMediator displayedActualCapacityMediator;
@Override
public boolean existsSameAreaCode(String areaCode, String excludeId) {
if (StringUtils.isBlank(areaCode)) {
@@ -24,4 +31,9 @@ public class MesXslWarehouseAreaServiceImpl extends ServiceImpl<MesXslWarehouseA
.ne(StringUtils.isNotBlank(excludeId), MesXslWarehouseArea::getId, excludeId)
.count() > 0L;
}
@Override
public void enrichDisplayedActualCapacity(Collection<MesXslWarehouseArea> areas) {
displayedActualCapacityMediator.apply(areas);
}
}

View File

@@ -41,11 +41,11 @@ public class MesXslWarehouseServiceImpl extends ServiceImpl<MesXslWarehouseMappe
return;
}
String code = baseMapper.queryCategoryCodeById(e.getWarehouseCategory());
if (!MesXslWarehouseCategory.CUSTOMER_CATEGORY_CODE.equals(code)) {
if (!MesXslWarehouseCategory.isCustomerWarehouseCategoryCode(code)) {
e.setCustomerId(null);
e.setCustomerShortName(null);
}
if (!MesXslWarehouseCategory.SUPPLIER_CATEGORY_CODE.equals(code)) {
if (!MesXslWarehouseCategory.isSupplierWarehouseCategoryCode(code)) {
e.setSupplierId(null);
e.setSupplierShortName(null);
}
@@ -56,11 +56,11 @@ public class MesXslWarehouseServiceImpl extends ServiceImpl<MesXslWarehouseMappe
return;
}
String code = baseMapper.queryCategoryCodeById(e.getWarehouseCategory());
if (MesXslWarehouseCategory.CUSTOMER_CATEGORY_CODE.equals(code)) {
if (MesXslWarehouseCategory.isCustomerWarehouseCategoryCode(code)) {
if (oConvertUtils.isEmpty(e.getCustomerId())) {
throw new JeecgBootException("仓库分类为客户库时,请选择客户");
}
} else if (MesXslWarehouseCategory.SUPPLIER_CATEGORY_CODE.equals(code)) {
} else if (MesXslWarehouseCategory.isSupplierWarehouseCategoryCode(code)) {
if (oConvertUtils.isEmpty(e.getSupplierId())) {
throw new JeecgBootException("仓库分类为供应商库时,请选择供应商");
}

View File

@@ -0,0 +1,91 @@
package org.jeecg.modules.xslmes.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* 原材料库区看板:按库区编码前缀等规则形成的「分组带」汇总展示(不按业务楼层拆分)
*/
@Data
@Schema(description = "原材料库区看板")
public class MesXslRawMaterialWarehouseBoardVO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "计量口径回显quantity=按剩余数量 weight=按剩余重量")
private String measureType;
@Schema(description = "分组带列表")
private List<BoardBandVO> bands = new ArrayList<>();
@Data
@Schema(description = "看板分组带(如 1F、2F")
public static class BoardBandVO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "分组键(排序用)")
private String bandKey;
@Schema(description = "分组标题")
private String bandLabel;
@Schema(description = "排序号,越小越靠前")
private Integer bandSort;
@Schema(description = "该组下的库区卡片")
private List<BoardAreaCardVO> areas = new ArrayList<>();
}
@Data
@Schema(description = "单个库区卡片数据")
public static class BoardAreaCardVO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "库区主键")
private String areaId;
@Schema(description = "库区编码")
private String areaCode;
@Schema(description = "库区名称")
private String areaName;
@Schema(description = "所属仓库ID")
private String warehouseId;
@Schema(description = "所属仓库名称")
private String warehouseName;
@Schema(description = "最大存放量(库区主数据)")
private Integer maxCapacity;
@Schema(description = "实际存放量(库区主数据快照)")
private Integer actualCapacity;
@Schema(description = "在库卡片张数(有剩余量)")
private Integer cardCount;
@Schema(description = "物料种类数(去重物料名称)")
private Integer materialKindCount;
@Schema(description = "剩余数量合计")
private Integer currentQuantity;
@Schema(description = "剩余重量合计")
private BigDecimal currentWeight;
@Schema(description = "物料名称摘要(前若干种)")
private List<String> topMaterialNames = new ArrayList<>();
@Schema(description = "占用率 0100无上限或上限为0时为 null")
private Double usagePercent;
@Schema(description = "告警级别empty/low/normal/high/full/unknown")
private String alertLevel;
}
}

View File

@@ -0,0 +1,43 @@
package org.jeecg.modules.print.bootstrap;
import java.util.concurrent.CompletableFuture;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.print.service.IPrintBizPermEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 项目启动后异步从数据库 {@code sys_permission} 读取真实 component / component_name预热
* {@code print_biz_perm_entity},不依赖人工白名单操作。关闭:{@code jeecg.print.biz-perm-warmup=false}
*/
@Slf4j
@Component
@Order(2000)
public class PrintBizPermEntityWarmupRunner implements ApplicationRunner {
@Autowired private IPrintBizPermEntityService printBizPermEntityService;
@Value("${jeecg.print.biz-perm-warmup:true}")
private boolean warmupEnabled;
@Override
public void run(ApplicationArguments args) {
if (!warmupEnabled) {
log.info("打印菜单-实体映射预热已关闭jeecg.print.biz-perm-warmup=false");
return;
}
CompletableFuture.runAsync(
() -> {
try {
log.info("打印菜单-实体映射:开始异步预热(来源 sys_permission 表)");
printBizPermEntityService.warmupMappingsFromSysPermissionTable();
} catch (Exception e) {
log.warn("打印菜单-实体映射预热失败(不影响系统启动)", e);
}
});
}
}

Some files were not shown because too many files have changed in this diff Show More