![]() |
Links and the event loop | ![]() |
A link moves bytes between TeXmacs and an extern program; it knows nothing about trees, formats or sessions. The abstract class is declared in
System/Link/tm_link.hpp
:
struct tm_link_rep: abstract_struct {
bool alive; // link is alive
string secret; // empty string or secret key for encrypted connections
command feed_cmd; // called when async data available
virtual string start () = 0;
virtual void write (string s, int channel) = 0;
virtual string& watch (int channel) = 0;
virtual string read (int channel) = 0;
virtual void listen (int msecs) = 0;
virtual void interrupt () = 0;
virtual void stop () = 0;
void write_packet (string s, int channel);
bool complete_packet (int channel);
string read_packet (int channel, int timeout, bool& success);
void secure_server (string cmd);
void secure_client ();
void set_command (command _cmd) { feed_cmd = _cmd; }
void apply_command () { if (!is_nil (feed_cmd)) feed_cmd->apply (); }
}; |
The smart pointer tm_link is declared with ABSTRACT_NULL. The channels are numbers: LINK_IN and LINK_OUT are both 0 (input to the program and its standard output), LINK_ERR is 1 (its standard error). The contract of the virtual methods, as relied upon by
connection.cpp
, is the following:
Start the extern program and set alive. The returned message is "ok" on success. Other values in use are "busy" (already started), messages starting with "Error:", the startup message of a dynamic library, and the special values "cmdline" and "request", which switch the connection to the corresponding evaluation style.
Send s to the program. Only LINK_IN is meaningful.
string& watch (int channel)
watch returns a reference to the buffer of pending output of the channel without consuming it (it is only used by the packet functions); read returns the pending output and empties the buffer. Neither method is required to wait for data.
Wait at most msecs milliseconds until output is available on one of the channels, and buffer it.
void interrupt ()
Interrupt the current computation, resp. terminate the program and set alive to false.
When new output has been buffered, the link (or the code which polls it) must call apply_command, which runs the command installed by connection_rep::start and so calls connection_rep::listen. When the program has terminated, the link must set alive to false; the connection detects this on its next read and reports the session as dead.
The non-virtual methods write_packet, read_packet and the secure_* methods implement the length-prefixed and optionally encrypted packets of the client/server protocol; plug-in connections do not use them. They are described in transport and message protocol.
pipe_link_rep in
System/Link/pipe_link.cpp
holds the launch command, the process identifier, three pairs of pipe descriptors, the buffers outbuf and errbuf, and two socket notifiers. Its start method forks:
pid= fork ();
if (pid==0) { // the child
setsid();
… // connect the pipes to STDIN, STDOUT and STDERR with dup2
execute_shell (cmd); // execve ("/bin/sh", {"sh", "-c", cmd}, environ)
exit (127);
}
else { // the main process
… // keep in, out and err, close the other ends
alive= true;
snout = socket_notifier (out, &pipe_callback, this, NULL);
snerr = socket_notifier (err, &pipe_callback, this, NULL);
add_notifier (snout);
add_notifier (snerr);
return "ok";
} |
The launch command is thus interpreted by /bin/sh, so that it may contain redirections, pipes, sequences and environment assignments. The child is the leader of a new session and process group (setsid), so that signals can be sent to the whole group with killpg: interrupt sends SIGINT to the group, and stop sends SIGTERM, sleeps two seconds, sends SIGKILL, closes the input pipe and calls wait. Since the start method always returns "ok", a launcher which cannot be executed is only detected later, when the shell exits with status 127 and the output pipe reaches its end. (The code still contains a disabled check for a startup character TERMCHAR.)
The method feed reads at most 1024 bytes from one pipe into the corresponding buffer; at end of file it kills the process group, sets alive to false and removes the notifiers. The call-back pipe_callback is invoked when a notifier fires: it calls feed for both pipes, using select with a zero timeout, until no more data is immediately available, and then applies feed_cmd. The method listen is the blocking counterpart, used by synchronous code.
All pipe links are registered in the global set pipe_link_set. process_all_pipes applies the command of every live pipe link (and of every live command line and request link), and close_all_pipes kills all processes; the latter is called by quit_texmacs_internal in
Texmacs/Server/tm_server.cpp
and by the emergency handler in
Texmacs/Server/tm_debug.cpp
.
On Windows (OS_MINGW) without Qt, all methods of pipe_link_rep are empty and start returns "Error: pipes not implemented".
When QTTEXMACS is defined together with OS_MINGW or QTPIPES,
pipe_link.cpp
compiles to nothing and make_pipe_link is provided by
Plugins/Qt/qt_pipe_link.cpp
instead. The class qt_pipe_link_rep delegates to a QTMPipeLink, a subclass of QProcess declared in
Plugins/Qt/QTMPipeLink.hpp
which holds the command and the two buffers. The differences with the POSIX implementation are significant:
No shell. QTMPipeLink::launchCmd splits the launch command into a program and its arguments and starts the program directly: with wordexp on Unix systems (which performs quoting, variable and tilde expansion, but fails on unquoted shell operators such as ;, |, &, < or >), with CommandLineToArgvW on Windows and with QProcess::splitCommand on Android. A launcher which needs shell syntax must therefore invoke a shell explicitly, as in sh -c "cd /some/dir; exec myprog". If the program cannot be started, start returns "Error: cannot start application".
Polling. The signals readyReadStandardOutput and readyReadStandardError are connected to the slot QTMPipeLink::readErrOut, which only appends the available data to the buffers (feedBuf). The command feed_cmd is not applied from the slot; the connection is notified when tm_server_rep::interpose_handler calls process_all_pipes, which applies the command of every live link, whether it received data or not.
Signals. interrupt sends SIGINT with ::kill to the process only (there is no process group); on Windows it is not implemented and only prints an error. stop calls QTMPipeLink::killProcess (0), which calls terminate and, if the process has not finished immediately, kill.
Reading. qt_pipe_link_rep::read first calls listen (0), which uses waitForReadyRead; therefore reading from a Qt pipe link also pulls new data from the process, which is what makes the synchronous loop of connection_retrieve work without perform_select.
Writing. QTMPipeLink::writeStdin waits until the data has been written (waitForBytesWritten); if writing fails, the link is stopped.
A plug-in configured with (:link lib symbol init) uses a dyn_link_rep (
System/Link/dyn_link.cpp
). The interface between TeXmacs and the library is declared in
src/TeXmacs/include/TeXmacs.h
and documented from the point of view of the library in dynamic libraries and dynamic linking.
The function symbol_install looks up the library in $LD_LIBRARY_PATH (which includes the lib directories of all plug-ins), opens it with the function given by the configuration macro TM_DYNAMIC_LINKING (normally dlopen) and resolves the symbol with dlsym. Libraries and symbols are cached in the static table dyn_linked, so that a library is opened only once. Without TM_DYNAMIC_LINKING, or on Windows, dynamic linking is not available.
dyn_link_rep::start casts the symbol to a package_exports_1 structure and calls its install function with the TeXmacs_exports_1 structure of TeXmacs and the initialization string. The returned string becomes the first output of the link (the banner). dyn_link_rep::write calls the evaluate function of the library with the input and the session name and stores the result as the pending output; if the result is NULL, the error string is used instead. Then it applies feed_cmd immediately: the whole evaluation is synchronous, from within connection_write. The strings returned by the library must follow the same DATA_BEGIN … DATA_END conventions as the output of pipes, since they are parsed by the same texmacs_input. The methods listen, interrupt and stop do nothing; a dynamically linked computation cannot be interrupted, and the library is never unloaded.
Dynamic links are not registered in any global set and are therefore not polled. Their output becomes visible only through the immediate feed_cmd call in write, and, for the banner, through the call to listen in connection_rep::start, which is only made for a plug-in named dynlink (see known issues).
cmdline_link_rep (
System/Link/cmdline_link.cpp
) starts a new process for every request. Its start method only clears the buffers and returns "cmdline". Its write method replaces newlines in the input by spaces, asks Scheme for the command line with (connection-cmdline name "default" input), appends 2> /dev/null, and forks /bin/sh -c like a pipe link, with socket notifiers on the output pipes; write is ignored while the previous command is still running. An end of file on the standard output kills the process group and marks the link as dead, which is how the connection learns that the output is complete. read returns nothing as long as the process is alive. Live command line links are registered in cmdline_link_set and polled by process_all_cmdlines, which is called from process_all_pipes; in addition, connection_rep::listen calls listen (1) on these links, which waits at most one millisecond for data.
request_link_rep (
System/Link/request_link.cpp
) is similar, but the request is a Scheme expression returned by connection-request. The only request which is understood is
(http_post url (tuple header …) json-data) |
which is passed to async_http_post_json (
System/Files/web_files.cpp
). The latter builds a shell command (with to_shell_command) and runs it with async_eval_system, which starts it with popen and reads its output in a detached thread. When the thread has finished, async_eval_pending, called from the interpose handler, copies the output into the buffer of the link and sets its status field to 0; the next poll of the link (by process_all_requests) then marks it as dead. The kill flag which interrupt and stop set is only checked by the reading thread before it starts reading, so a running request cannot really be cancelled; its result is then ignored by the connection.
System/Link/socket_notifier.cpp
maintains a set of socket_notifier objects, each consisting of a file descriptor and a command. add_notifier and remove_notifier manage the set, and perform_select repeatedly calls select with a zero timeout on all registered descriptors and runs the commands of the ready ones, until none is ready. It does not block. On Windows it is not implemented.
Which mechanism delivers the output of a link depends on the build:
| Build | Interpose handler calls | Pipes | Command lines | Requests |
| Qt with QTPIPES (default) | process_all_pipes | QProcess signals fill the buffers, polled | polled, listen (1) | polled |
| Qt without QTPIPES | perform_select, process_all_pipes | socket notifiers, also polled | notifiers, polled | polled |
| Other ports (Vue, SDL, X11, Cocoa) | perform_select | socket notifiers | socket notifiers | not polled |
In all cases async_eval_pending is called by the interpose handler as well. The important point for implementers is that socket notifiers registered with add_notifier are not serviced in the default Qt build, since perform_select is only called when QTPIPES is undefined. A link which wants to be served in all builds should register itself in a set which is polled from process_all_pipes, as the command line and request links do.
The header
tm_link.hpp
declares the functions make_socket_link, make_socket_server, find_socket_link, close_all_sockets and close_all_servers, but none of them is defined anywhere in the sources: they are left over from an older implementation. Likewise, the options (:socket host port) and (:socket variant host port) of plugin-configure produce a launcher description (tuple "socket" host port), but connection_start has no branch for it. Plug-ins can therefore not communicate through sockets at present.
The client/server code of the collaboration tools does have a working socket link: the class socket_link_rep in
Plugins/Qt/QTMSockets.hpp
, which derives from both QObject and tm_link_rep, uses QSocketNotifier objects and applies feed_cmd when data arrives. It is only available in Qt builds and is used through the packet interface (see transport and message protocol).
The following steps are needed to add a new transport, for instance the missing socket connections.
The link class. Derive a class from tm_link_rep and implement the seven virtual methods according to the contract above. In particular, start must set alive and return "ok", read must return and clear the buffered data without blocking, and the link must set alive to false when the peer disappears. Provide a factory function, declared in
tm_link.hpp
.
Delivery of the output. Make sure that apply_command is called when data has been buffered. The simplest portable solution is to keep the live links in a set and to apply their commands from process_all_pipes (as process_all_cmdlines does); calling apply_command when nothing new arrived is harmless. A socket notifier alone is not enough in the default Qt build. Whatever the mechanism, do not call apply_command while connection_retrieve is running for the same connection unless read also pulls data, or synchronous evaluation will not terminate.
Termination. Add the links to close_all_pipes (or to a function called from quit_texmacs_internal) so that they are closed when TeXmacs exits.
The connection. Add a branch to connection_start in
System/Link/connection.cpp
which recognizes the launcher description and creates the link.
The configuration. Add a clause to plugin-configure-cmd in
kernel/texmacs/tm-plugins.scm
which turns the new option into a launcher description with connection-setup, and document the option in the summary of configuration options. If the option takes a variant, pass it as the optional third argument of connection-setup, as is done for :launch.
Remote use. If the new link should be usable for remote plug-ins, extend write-local-plugin-info and the code which reads remote-plugins.scm; currently only pipe launchers are exported.
For the socket case, the description is already produced by plugin-configure, and the dispatch could look as follows (this is a sketch, not existing code; make_plugin_socket_link is a hypothetical factory):
else if (is_tuple (t, "socket", 2)) {
tm_link ln= make_plugin_socket_link (t[1]->label, as_int (t[2]->label));
con= tm_new<connection_rep> (name, session, ln);
} |
The link would connect to the given host and port in start, configure the socket as non-blocking, append the received bytes to its output buffer in a polled feed method, and treat a closed socket as the death of the program. Since a socket has no separate error stream, read (LINK_ERR) would always return the empty string; a server which wants to report errors should use the error# channel inside its DATA_BEGIN … DATA_END blocks, keeping in mind that the error channel of the standard output is only delivered to a handler declared with :handler (see output channels). Interrupts cannot be sent as signals either, so they would have to be part of the protocol, for instance as a special command prefixed with DATA_COMMAND.