Realizing js from scratch to develop Linux graphical interface program

Realizing js from scratch to develop Linux graphical interface program

Preface

Recently, the company has received development needs at work, and the company wants to sell server hardware running in special scenarios (based on

Linux
Operating system), front-end engineers need to cooperate with development
Linux
The graphical applications under the system are delivered together.

The final application program is written by the hardware engineer by calling

shell
The script directly obtains the current computing data and related parameters of the machine, and then renders the interface for the user to view. The entire process is docked by the front-end and the hardware engineer, without the need for the back-end to participate.

Because of the previous use

Electron
in
windows
Under the experience of developing client software, this time I still choose
Electron
As a technical solution to achieve development goals.

Electron
Is a use
JavaScript
,
HTML
with
CSS
Wait
Web
Technology to create a framework for native programs, which integrates
Chromium
with
Node.js
, Which also makes common browsers have the ability to call operating system related services. In addition, its biggest advantage is that it is cross-platform and can support development
Windows
,
Mac
with
Linux
The client application under the system.

Front-end engineers generally

Linux
The operating system is less exposed, and how to quickly become familiar with the characteristics of the system and complete the development goals with the minimum learning cost is not a small challenge. The entire development process is roughly summarized into the following steps.

  • Build
    Linux
    Operating system and graphical desktop
  • Build
    Electron
    Project structure, according to
    UI
    Design drawing to complete the development of static pages
  • After the static page is completed, write the call
    shell
    The function of the script, by calling the script to get the machine data, and then rendering it on the page
  • The project is developed and packaged into an installation program for delivery

Install Linux development environment

Linux
The environment is very cumbersome to set up, many people will choose to install the virtual machine and operating system locally, and then do some settings for the environment. In order to be able to quickly and easily use it in the early stage
Linux
System, you can consider spending dozens of dollars on Alibaba Cloud to buy a short-term and well-installed server.

First log in to Alibaba Cloud's official website to register an account, and then select the lightweight application server from the drop-down list in the product column (as shown below);

After entering the page, select the configuration and apply the mirror column

Node.js
select
14.15.2
Version (as shown below). If
Node
The version selected is too low, and many software can't run.

Select the column of system mirroring

Ubuntu 16.04
Version (as shown in the figure below). The image of the operating system can be selected according to actual needs.
Linux
The most used operating system is
CentOs
with
Ubuntu
.

The configuration process is very simple, and it is basically over here, and then click the confirm button to pay and get a server.

After the payment is successful, click to enter the management console, and the relevant parameters of the server you purchased are displayed on the page, such as the public network

IP
address,
CPU
Usage and
RAM
Occupy size.

server information
There is one on the right side of that column
reset Password
, Click Set a new password and restart the application.

After restarting, click on the remote connection on the upper right side (as shown in the figure below) and enter in the black window

node -v
Can view
node
Version. This black window is a command line tool, you can enter various commands in it to complete system-related operations.

Continue typing on the command line

sudo apt-get install git
, Install one on our server
git
.In this installation command
sudo
It is to run with administrator privileges.
apt-get
It is a package management tool, we can use it to download, update, uninstall and other operations of the software, similar to the front-end use
npm
.

installation

git
During the process, the command line may pop up
Is this ok [y/N]:
For inquiries, enter
y
Continue the installation. After the installation is complete, enter on the command line
git --version
You can view the installed
git
version.

Install a graphical desktop

Our goal is to

Linux
Next, develop a graphical interface program. A system with only a black window on it cannot meet the needs. We also need to
Linux
The system then installs a graphical desktop, like
Windows
The system is the same, so that the program we developed can be displayed on the graphical desktop.

  • Update the download source, enter at the command line

    sudo apt-get update
    carried out.

  • Install the desktop environment

    xfce
    ,input the command
    sudo apt install xfce4
    carried out.

VNC configuration

Configuration

VNC
Is to make local
windows
The computer can open the remote server in the form of a graphical desktop.

Enter on the Alibaba Cloud server command line

sudo apt-get install vnc4server
installation
VNC
.

VNC
After the server is installed, execute
vncserver :1
Command start
VNC
(If there is an error without permission, add
sudo
Run again). Here, the first time you start, you will enter the connection password, the password must be remembered, and wait for it locally
windows
This password is required to connect to the remote desktop.

After the password is set, start to modify

VNC
Configuration file. Enter first
vncserver -kill :1
Command, this command is to prevent errors when modifying files.

Then type

vi ~/.vnc/xstartup
,turn on
VNC
Start configuration file entry
vi
Editor mode.

Learned here

Linux
Basic students should know,
vi
The editor has its own set of rules for input and exit. When it is turned on by default, the characters you type on the keyboard will not appear on the file, only input first
i
Enter insert mode to make the entered characters take effect.

keyboard input

i
Enter insert mode, and then
x-window-manager &
Enter in front of that line
#
Note, and then paste the following configuration information below (the final result is shown in the figure below).

sesion-manager & xfdesktop & xfce4-panel & xfce4-menu-plugin & xfsettingsd & xfconfd & xfwm4 & Copy code

After configuring the startup file, exit

vi
The editor needs to first press on the upper left corner of the keyboard
ESC
Key to enter
vi
The command mode of the editor, and then type on the keyboard
:wq
Press down
Enter
Key to save and exit.

The above has been the server-side

VNC
The configuration is roughly finished, now enter the Alibaba Cloud console to configure the firewall, and click on the firewall in the security bar on the left side of the console (as shown in the figure below).

There is a button to add a rule in the upper right corner. After clicking it, a pop-up box appears (as shown in the figure below), and the protocol is selected

TCP
, Port number input
5901
, And finally click the OK button.

After the firewall configuration is complete, return to the console to restart the server (here must be restarted), and open the remote connection (as shown below).

Wait until the command line window appears, enter

vncserver :1
start up
VNC
Services. So far, the configuration of the server has been completed.

Remote Connection

The server has been configured and is now locally

windows
Computer installation
VNC
The client software connects to the remote desktop.

Open the official website

https://www.realvnc.com/en/connect/download/viewer/
click to download
windows
Client software installation.

After the software is installed, click Run and click on the menu bar

File
Down
New connection
A pop-up box appears.
VNC Server
Fill in the public network of the purchased Alibaba Cloud host in that column
ip
, Add the port number after
:5901
(As shown below). After configuration, click
OK
.

At this time, an icon appears on the main interface. After clicking it, you will be asked to enter a password.

VNC Server
The set password.

After the password is entered, the remote desktop is opened (as shown below), so far

Linux
The system configuration work is completed.

Sometimes it is found that the remote desktop cannot be connected after the Alibaba Cloud server restarts. At this time, you need to open the command line tool of the Alibaba Cloud console and enter

vncserver :1
will
VNC
The service starts up and then connects remotely.

Electron project development

The graphical interface has been activated, operating habits and

Windows
similar.

Start development now

Electron
Item. currently
githup
There are many excellent
Electron
Scaffolding, of course, you can build it yourself if you have enough time and special requirements.

Scaffolding is unfamiliar with those

Electron
The front-end players are very convenient, eliminating the cumbersome project construction link. The currently popular scaffolding is based on
react
of
electron-react-boilerplate
, The project address is as follows.

https://github.com/electron-react-boilerplate/electron-react-boilerplate

in the case of

vue
Audiophiles, you can also choose
electron-vue
Scaffolding, the project address is as follows.

https://github.com/SimulatedGREG/electron-vue

This article starts with

electron-react-boilerplate
As an example, in
Linux
Right-click on the graphical desktop and select
Open Terminal Here
Open the command line tool.

Since we have installed it before

git
, You can use it directly
git
Project
clone
Down.

Run command

git clone https://github.com/electron-react-boilerplate/electron-react-boilerplate
Download the project to the desktop.

If found

githup
Can't open, you can change to this command to download
git clone git://github.com/electron-react-boilerplate/electron-react-boilerplate --depth 1
.

After the download is complete, click the project folder to enter the project directory. For the smooth execution of the following installation work, open the permissions of the current project folder and execute the command

sudo chmod -R 777/home/admin/Desktop/electron-react-boilerplate
.The project name here is by default
electron-react-boilerplate
, If you change other names, you must modify them accordingly.

After the permissions are modified, enter the project folder, click the right mouse button to open the command line in this directory, and enter

sudo npm install -g cnpm
,reuse
sudo cnpm install
Installation dependencies (
npm
The installation may fail). After the dependencies are installed, open the project file
package.json
And found that the project startup command is
npm run start
.

So enter

npm run start
Start the project, the command line tool is found to be stuck during the startup process (as shown in the figure below), this is because the installation
react
Browser debugging tools need to access
Chrome
The app store, the command line is stagnant because it cannot be accessed.

In order to solve the above problem, you can open the project directory

src/main.dev.ts
,will
await installExtensions()
Comment out that line of code (as shown below). This line of comment is just to cancel the installation
react
Debugging tools,
Electron
The debug window will still be retained.

The project is finally started, open the project directory

src/App.tsx
, Modify the code of the root component to
Hello world
, The code and renderings are as follows.

const Hello = () => { return ( <div> Hello world </div> ); }; export default function App() { return ( <Router> <Switch> <Route path="/" component={Hello}/> </Switch> </Router> ); } Copy code

It is recommended not to use

Linux
Write the code under, because the graphical desktop is not stable and often freezes affect development efficiency. The best solution is in
windows
Write code under and submit after development
git
.and
Linux
Server directly from
git
Pull up the final code to run and observe the effect, and if all the effects are in line with expectations, then package it into an installation package.

Run shell script

electron-react-boilerplate
Scaffolding is based on
react
The framework and the process of developing pages are no different from our usual development of web pages.

If you just develop web-related content, the page can be packaged and delivered directly after the page is developed. But our development goal is to be able to call

shell
Script to get the data. The source of the data is no longer obtained from the backend as before, but directly calls the script to get the data to be rendered.

shell
Is a command line interpreter, it provides users with a guide
Linux
The kernel sends a request to run the program's interface system-level program, and the user can use
shell
To start, suspend, stop and even write some programs.

For example, a simple

shell
Script file
getSystem.sh
To get the status information of the system.

#!/bin/bash echo -e "hostname:\t `hostname`" echo -e "OScore:\t\t `uname -a`" echo -e "CPUInfo:\t `grep "model name"/proc/cpuinfo | awk -F:'{print $2}' `" echo -e "CPUMHz:\t\t `grep "MHz"/proc/cpuinfo | awk -F:'{print $2}' `" echo -e "MemTotal:\t `free -m | awk'$1=="Mem:" {print $2}' `" Copy code

echo
Representative output,
5
The output sentences correspond to the following
5
Article data.

  • Get the host name of the machine
  • Get the version number of this system
  • Get the type of CPU
  • Get the operating frequency of the CPU
  • Get memory usage

How to execute

shell
What about script files? Generally use system commands
/bin/bash getSystem.sh
You can execute the script file and return the output result after execution (as shown in the figure below).

At present, only the data is output on the command line, and then the data will be displayed on the page.

Now in the project root directory

src
Create a new folder in the folder
scripts
Store all
shell
Script, create a new file in it
getSystem.sh
As a test
demo
And assign the above script code to
getSystem.sh
inside.

shell
The script is ready, we also need to configure the project root directory
pacakge.json
in
build
Under the field
files
, Will be loaded with
shell
Script folder
scripts
Configure it (as shown below).

These ones

files
The configuration below is static resources, which is equivalent to
web
Under development
public
folder,
webpack
After the final packaging, they will be copied intact to the packaged directory.

shell
The configuration of the script is completed, how to find the path of the script on the page and execute it?

due to

Electron
Integrated
nodejs
, We can directly use
node
Subprocess module
child_process
Used to execute commands (code is as follows).

const path = require("path"); const exec = require("child_process").exec; const Hello = () => { const getSystem = ()=>{//Get system parameters //Through the above configuration, the scripts folder will be directly copied to the packaged folder as a static resource, and the files inside can be accessed through the following methods const script_path = path.join(__dirname, "scripts",'getSystem.sh'); console.log(script_path);//The path of the shell script exec(`/bin/bash ${script_path}`, (error,stdout) => {//Execute script if(!error){ console.log("Script output result:"+stdout); } } } return ( <div> <button onClick={getSystem}>Click</button> </div> ); }; Copy code

As expected, clicking the button will eventually return the output result of the script execution. But after packaging the test, the path of the script output by the console after the above code is run is like this (as shown below).

We will find this

getSyetem.sh
The script file is in
app.asar
inside,
app.asar
Yes
Electron
The compressed format file of the program, which is equivalent to the shell of the program, encapsulates all the source code in its own internal, forming an isolated sandbox environment.

Therefore, it is not available outside the system

app.asar
The files inside, if you use
/bin/bash
Forced to execute the package in
app.asar
inside
shell
The script will report errors.

Since direct execution fails, we need to change our thinking. When executing the script file, copy the script to a temporary folder in the system, and then use it.

/bin/bash
Going to execute the script in the temporary folder can be implemented smoothly.

Let's create a new tool method

call
(code show as below).

/tmp
Just
Linux
The temporary folder of the system, we can first determine whether there is a name under the temporary folder
myScripts
If there is no folder, create a new one.

myScripts
After the folder is created, add
electron
Copy the static scripts stored in it to
myScripts
Below the folder, call
/bin/bash
Execute the script and return the result.

const path = require("path"); const exec = require("child_process").exec; const fs = require('fs-extra'); //name is the file name of the shell script export const call = (name)=>{ const script_path = path.join(__dirname, "scripts", `${name}.sh`);//The real path of the script in the electron application return new Promise(async (resolve,reject)=>{ await fs.ensureDir('/tmp/myScripts');//Judging whether there is a myScripts folder under/tmp, create one if not const dist_path = `/tmp/myScripts/${name}.sh`; const isExit = await fs.pathExists(dist_path);//Does the script already exist? !isExit && await fs.copy(script_path, dist_path);//If it does not exist, just copy the past //Execute script exec(`/bin/bash ${dist_path}`, (error, stdout) => { if(error){ console.log(error); reject(error); }else{ resolve(stdout);//Return the data result of the script } }); }) } } Copy code

Call directly on the page

call
Function, if you want to call that script, just pass in the file name of the script.

const Hello = () => { const getSystem = async ()=>{ const data = await call("getSystem");//call the getSystem.sh script console.log(data);//Data returned after the script is executed } return ( <div> <button onClick={getSystem}>Click</button> </div> ); }; Copy code

Finally click the button on the page, you can make

Linux
System execution
getSystem.sh
Script and return the execution result.

The data acquisition method has been unblocked, and the next work is to develop the page rendering data.This part of the work is no different from the usual development of front-end web pages.

Bale

After the code is developed, enter the packaging process. First open the project root directory

package.json
,in
scripts
Look for the packaging command and find that the command is
package
.

Enter directly on the command line

sudo npm run package
Command, the packaging process is started. The scaffolding is smarter, it will determine the platform on which the current code is running, and generate the corresponding installation package.

After the command is executed successfully, the project root directory

release
A tape will be generated under the file
.AppImage
Suffix file, this file is
Linux
The final application generated under the platform.

.AppImage
with
.rpm
with
.deb
When the installation format is different, it uses a common software format, which can be used in almost all
Linux
Used in the release version, one package can contain all the features.

It is equivalent to

Windows
Those in the system that are free of installation
exe
Files, which can be transferred through software,
U
Disk copy to transfer programs to each other. Others
Linux
As long as the machine receives the program, it only needs to use the mouse to double-click to start the application, which is simple and convenient to use.

The final effect is as follows.

Source code

Download code