/
ExternalTool.vala
110 lines (103 loc) · 2.5 KB
/
ExternalTool.vala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* Copyright 2011-2012 Martijn Koedam <qball@gmpclient.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using GLib;
using Posix;
namespace IfThenElse
{
/**
* Execute an external tool.
*
* This executes an external tool.
*
* =Example=
*
* {{{
* [EAction]
* cmd=mpc play
* }}}
*/
public class ExternalToolAction: BaseAction, Base
{
public string cmd {get; set; default = "";}
/**
* If the property kill_child is set to true, it kills the
* client when the object is deactivated.
*/
public bool kill_child {get; set; default = false;}
private GLib.Pid pid = 0;
private void child_watch_called(GLib.Pid p, int status)
{
GLib.Process.close_pid(p);
GLib.message("Child watch called.\n");
pid = 0;
}
private void start_application()
{
GLib.message("%s: %s", this.name, "start application");
if(kill_child)
{
stop_application();
pid = 0;
}
if(pid == 0)
{
string[] argv;
GLib.message("Start application\n");
try {
GLib.Shell.parse_argv(cmd, out argv);
foreach (var s in argv)
{
GLib.message("argv: %s\n", s);
}
GLib.Process.spawn_async(null, argv, null, SpawnFlags.SEARCH_PATH|SpawnFlags.DO_NOT_REAP_CHILD, null, out pid);
GLib.ChildWatch.add(pid, child_watch_called);
} catch (Error e) {
GLib.warning("Failed to start application: %s", e.message);
}
}
}
private void stop_application()
{
if(pid > 0)
{
GLib.message("%s: Killing pid: %i\n",this.name, (int)pid);
Posix.kill((pid_t)pid, 1);
}
}
public void Activate()
{
start_application();
}
public void Deactivate()
{
GLib.message("%s: Deactivate\n", this.name);
stop_application();
}
/**
* Generate dot output for this node
*
*/
public void output_dot(FileStream fp)
{
fp.printf("\"%s\" [label=\"%s\\n(%s)\", shape=oval]\n",
this.name,
this.get_public_name(),
cmd.escape("")
);
}
}
}