├── .gitignore
├── LICENSE
├── README.md
├── doc
├── ros2_launch_gui_example.png
└── ros2_launch_gui_nav2_example.png
├── package.xml
├── resource
└── ros2launch_gui
├── ros2launch_gui
├── __init__.py
├── actions
│ ├── __init__.py
│ └── display_user_interface.py
├── api
│ ├── __init__.py
│ ├── create_default_user_interface.py
│ ├── describe.py
│ └── user_interface.py
├── event_handlers
│ ├── __init__.py
│ └── on_user_interface_event.py
├── events
│ ├── __init__.py
│ └── query_user_interface.py
├── option
│ ├── __init__.py
│ └── gui.py
├── qt
│ ├── __init__.py
│ ├── details_widget.py
│ ├── launch_description_widget.py
│ ├── main.py
│ └── process_output_widget.py
└── tk
│ ├── __init__.py
│ ├── event_viewer.py
│ ├── launch_description_treeview.py
│ ├── process_manager.py
│ └── user_interface.py
├── setup.cfg
├── setup.py
└── test
├── test_ansi_to_html.py
├── test_copyright.py
├── test_flake8.py
└── test_pep257.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ROS 2 Launch GUI
2 |
3 | This package provides a Graphical User Interface for the ROS 2 Launch System.
4 |
5 | 
6 |
7 | The above screenshot is from running:
8 |
9 | ros2 launch -g turtlesim multisim.launch.py
10 |
11 | On the left is a tree representation of the launch description while on the right, the output of each process is separated into tabs.
12 |
13 | For a more complex example, here is a screenshot from the nav2 tutorial.
14 |
15 | 
16 |
17 | ## Usage
18 |
19 | So far, testing has been as a ros2 launch option. The design should allow for a DisplayUserInterface action to be manually added to a launch description, but this has not yet been tested.
20 |
21 | ### Command line option
22 |
23 | An option is add to the `ros2 launch command for enabling a gui.
24 |
25 | ros2 launch --gui my_package my_launch.py
26 |
27 | or
28 |
29 | ros2 launch -g my_package my_launch.xml
30 |
31 | ### DisplayUserInterface action
32 |
33 | This is a work in progress...
34 |
35 | ## Design
36 |
37 | The system interfaces with the launch system using the DisplayUserInterface action. This action will create a user interface and return actions from it. It also contains the LaunchDescription to display.
38 | The default user interface supplies an event handler so the ui can react to launch events. The OnUserInterfaceEvent handler will forward events to the ui and respond to QueryUserInterface events to send pending events from the ui to the launch system.
39 | In order for the ui to be able to send events to the launch system, TimerActions are used to periodically send QueryUserInterface events allowing the launch system to regularly check for new ui actions.
40 |
--------------------------------------------------------------------------------
/doc/ros2_launch_gui_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rolker/ros2launch_gui/36729b3d413ed90711a1f46c1075522de9d80f75/doc/ros2_launch_gui_example.png
--------------------------------------------------------------------------------
/doc/ros2_launch_gui_nav2_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rolker/ros2launch_gui/36729b3d413ed90711a1f46c1075522de9d80f75/doc/ros2_launch_gui_nav2_example.png
--------------------------------------------------------------------------------
/package.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ros2launch_gui
5 | 0.0.0
6 | Provides a gui option to the ros2 launch command
7 | Roland Arsenault
8 | Apache-2.0
9 |
10 | python_qt_binding
11 | ros2launch
12 |
13 | ament_copyright
14 | ament_flake8
15 | ament_pep257
16 | python3-pytest
17 |
18 |
19 | ament_python
20 |
21 |
22 |
--------------------------------------------------------------------------------
/resource/ros2launch_gui:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rolker/ros2launch_gui/36729b3d413ed90711a1f46c1075522de9d80f75/resource/ros2launch_gui
--------------------------------------------------------------------------------
/ros2launch_gui/__init__.py:
--------------------------------------------------------------------------------
1 | from . import actions
2 | from . import option
3 |
4 | __all__ = [
5 | 'actions',
6 | 'option'
7 | ]
8 |
--------------------------------------------------------------------------------
/ros2launch_gui/actions/__init__.py:
--------------------------------------------------------------------------------
1 | from .display_user_interface import DisplayUserInterface
2 |
3 | __all__ = [
4 | 'DisplayUserInterface',
5 | ]
6 |
--------------------------------------------------------------------------------
/ros2launch_gui/actions/display_user_interface.py:
--------------------------------------------------------------------------------
1 |
2 | from typing import Callable
3 | from typing import List
4 | from typing import Optional
5 |
6 | from launch import Action
7 | from launch import LaunchContext
8 | from launch import LaunchDescription
9 | from launch import LaunchDescriptionEntity
10 |
11 | from ..api.create_default_user_interface import create_default_user_interface
12 | from ..api import UserInterface
13 |
14 | class DisplayUserInterface(Action):
15 | """Action to display a user interface for the launch system."""
16 | def __init__(
17 | self,
18 | *,
19 | launch_description: LaunchDescription,
20 | ui_launcher: Callable[[LaunchDescription, LaunchContext, bool], UserInterface] = create_default_user_interface,
21 | debug: bool = False
22 | ):
23 | """
24 | Create a DisplayUserInterface action.
25 |
26 |
27 |
28 | :param launch_description: The launch description to display the user interface for.
29 | :param ui_launcher: The function to use to create the user interface.
30 | :param debug: Whether to run the user interface in debug mode.
31 | """
32 | super().__init__()
33 | self._launch_description = launch_description
34 | self._ui_launcher = ui_launcher
35 | self._debug = debug
36 | self._ui = None
37 |
38 | def execute(self, context) -> Optional[List[LaunchDescriptionEntity]]:
39 | self._ui = self._ui_launcher(self._launch_description, context, self._debug)
40 | return self._ui.get_pending_actions()
41 |
--------------------------------------------------------------------------------
/ros2launch_gui/api/__init__.py:
--------------------------------------------------------------------------------
1 | from .describe import DescribedLaunchEntity
2 | from .user_interface import UserInterface
3 |
4 |
5 | __all__ = [
6 | 'DescribedLaunchEntity',
7 | 'UserInterface',
8 | ]
9 |
--------------------------------------------------------------------------------
/ros2launch_gui/api/create_default_user_interface.py:
--------------------------------------------------------------------------------
1 |
2 | from launch import LaunchContext
3 | from launch import LaunchDescription
4 |
5 | from ros2launch_gui.api import UserInterface
6 |
7 | def create_default_user_interface(
8 | launch_description: LaunchDescription,
9 | context: LaunchContext,
10 | debug: bool = False
11 | ) -> UserInterface:
12 | """Create a ui for monitoring launch events."""
13 |
14 | from ros2launch_gui.qt import UserInterface
15 |
16 | return UserInterface(launch_description, debug=debug)
17 |
18 |
--------------------------------------------------------------------------------
/ros2launch_gui/api/describe.py:
--------------------------------------------------------------------------------
1 |
2 | from launch import Action
3 | from launch import Condition
4 | from launch import LaunchContext
5 | from launch import LaunchDescription
6 | from launch import LaunchDescriptionEntity
7 | from launch.launch_introspector import format_action
8 | from launch.launch_introspector import format_substitutions
9 | from launch.actions import DeclareLaunchArgument
10 | from launch.actions import IncludeLaunchDescription
11 | from launch.utilities import normalize_to_list_of_substitutions
12 | from launch.utilities import perform_substitutions
13 |
14 | from launch_ros.actions import Node
15 | from launch_ros.actions import PushRosNamespace
16 | from launch_ros.actions import SetParameter
17 | from launch_ros.actions import SetParametersFromFile
18 |
19 |
20 | class DescribedLaunchEntity:
21 | """A human readable description of launch entity and its children.
22 | This is used to decouple the launch context from the description to be used
23 | in a GUI which may be running in a different thread.
24 | """
25 |
26 | def __init__(
27 | self,
28 | launch_entity: LaunchDescriptionEntity,
29 | context: LaunchContext = None
30 | ):
31 | if launch_entity is None:
32 | self.type_name = 'None'
33 | self.label = ''
34 | self.description = ''
35 | self.id = 0
36 |
37 | self.id = id(launch_entity)
38 |
39 | self.type_name = type(launch_entity).__name__
40 | self.label = ''
41 | if isinstance(launch_entity, Action):
42 | try:
43 | self.description = format_action(launch_entity)
44 | except Exception as e:
45 | self.description = str(e)
46 | else:
47 | try:
48 | self.description = launch_entity.describe()
49 | except NotImplementedError:
50 | self.description = ''
51 |
52 | self.conditional_children = []
53 |
54 | # IncludeLaunchDescription's describe_sub_entities() method returns temporary entities with different ids than the entities actually run, so try to get the real ones.
55 | if isinstance(launch_entity, IncludeLaunchDescription):
56 | try:
57 | self.children = [DescribedLaunchEntity(launch_entity.launch_description_source.get_launch_description(context)),]
58 | except Exception as e:
59 | self.children = []
60 | else:
61 | self.children = [DescribedLaunchEntity(child) for child in launch_entity.describe_sub_entities()]
62 | for condition, sub_entities in launch_entity.describe_conditional_sub_entities():
63 | self.conditional_children.append((condition, [DescribedLaunchEntity(child) for child in sub_entities]))
64 |
65 | self.condition = None
66 | if isinstance(launch_entity, Action):
67 | if launch_entity.condition is not None:
68 | self.condition = describe_condition(launch_entity.condition, context)
69 |
70 | if isinstance(launch_entity, IncludeLaunchDescription):
71 | self.description = launch_entity.launch_description_source.location
72 | self.launch_arguments = []
73 | for la in launch_entity.launch_arguments:
74 | self.launch_arguments.append((describe_substitution(la[0], context), describe_substitution(la[1], context)))
75 |
76 | elif isinstance(launch_entity, DeclareLaunchArgument):
77 | self.label = str(launch_entity.name)
78 | if context is not None and launch_entity.name in context.launch_configurations:
79 | self.description = context.launch_configurations[launch_entity.name]
80 | else:
81 | self.description = describe_substitution(launch_entity.default_value, context)
82 |
83 | elif isinstance(launch_entity, SetParameter):
84 | self.label = describe_substitution(launch_entity.name, context)
85 | self.description = describe_substitution(launch_entity.value, context)
86 |
87 | elif isinstance(launch_entity, SetParametersFromFile):
88 | self.description = describe_substitution(launch_entity._input_file, context)
89 |
90 | elif isinstance(launch_entity, Node):
91 | try:
92 | self.label = launch_entity.node_name
93 | except RuntimeError:
94 | pass
95 | self.description = "package: {}, executable: {}".format(launch_entity.node_package, launch_entity.node_executable)
96 |
97 | elif isinstance(launch_entity, PushRosNamespace):
98 | self.label = describe_substitution(launch_entity.namespace, context)
99 | self.description = describe_substitution(launch_entity.namespace, None)
100 |
101 |
102 |
103 |
104 | def __repr__(self):
105 | return 'id: {} ({}) name: {} desc: {}'.format(self.id, self.type_name, self.label, self.description)
106 |
107 | def describe_condition(condition: Condition, context: LaunchContext) -> str:
108 | if condition is not None:
109 | value = '?'
110 | if context is not None:
111 | value = condition.evaluate(context)
112 | return '{}: {}'.format(type(condition).__name__, value)
113 | return ''
114 |
115 | def describe_substitution(substitution, context: LaunchContext) -> str:
116 | if substitution is None:
117 | return ''
118 | if context is not None:
119 | return perform_substitutions(context, normalize_to_list_of_substitutions(substitution))
120 | return format_substitutions(substitution)
121 |
122 |
--------------------------------------------------------------------------------
/ros2launch_gui/api/user_interface.py:
--------------------------------------------------------------------------------
1 |
2 | from typing import List
3 | from typing import Optional
4 |
5 | from launch import Event
6 | from launch import LaunchContext
7 | from launch import LaunchDescription
8 | from launch import LaunchDescriptionEntity
9 |
10 | from launch.actions import EmitEvent
11 | from launch.actions import RegisterEventHandler
12 | from launch.actions import Shutdown
13 |
14 | from launch.events import ExecutionComplete
15 | from launch.events import IncludeLaunchDescription
16 |
17 | from launch.events.process import ProcessStarted
18 | from launch.events.process import ProcessExited
19 | from launch.events.process import ProcessIO
20 | from launch.events.process import RunningProcessEvent
21 |
22 | import os
23 |
24 | # Get ROS distro
25 | __installed_distro = os.environ.get("ROS_DISTRO", "").lower()
26 |
27 | if __installed_distro in ["humble", "galactic", "foxy"]:
28 | # Get some_action_type for older distributions
29 | from launch.some_actions_type import SomeActionsType as SomeEntitiesType
30 | else:
31 | from launch.some_entities_type import SomeEntitiesType
32 |
33 | from launch_ros.events.lifecycle import ChangeState
34 | from launch_ros.events.lifecycle import StateTransition
35 |
36 | from .describe import DescribedLaunchEntity
37 |
38 | from ..event_handlers import OnUserInterfaceEvent
39 | from ..events import QueryUserInterface
40 |
41 | class UserInterface:
42 | """Base class for a launch system user interface"""
43 |
44 | def __init__(
45 | self,
46 | launch_description: LaunchDescription,
47 | debug: bool = False
48 | ):
49 | self._pending_actions = [
50 | RegisterEventHandler(OnUserInterfaceEvent(self, debug)),
51 | EmitEvent(event=QueryUserInterface()),
52 | EmitEvent(event=IncludeLaunchDescription(launch_description))
53 | ]
54 | self._close_requested = False
55 |
56 | def close(self) -> None:
57 | """Request the GUI to close."""
58 | self._close_requested = True
59 |
60 | @property
61 | def close_requested(self) -> bool:
62 | """Check if the GUI has been requested to close."""
63 | return self._close_requested
64 |
65 | def get_pending_actions(self) -> List[LaunchDescriptionEntity]:
66 | actions = self._pending_actions
67 | self._pending_actions = []
68 | return actions
69 |
70 | def add_pending_action(self, action: LaunchDescriptionEntity) -> None:
71 | self._pending_actions.append(action)
72 |
73 | def on_process_started(self, process_name: str, pid: int, action: DescribedLaunchEntity) -> None:
74 | """Display a process start event in the GUI."""
75 | pass
76 |
77 | def on_process_exited(self, process_name: str, pid: int, action: DescribedLaunchEntity, return_code) -> None:
78 | """Display a process exit event in the GUI."""
79 | pass
80 |
81 | def on_process_io(self, process_name: str, text: str) -> None:
82 | """Display process output in the GUI."""
83 | pass
84 |
85 | def on_describe_launch_entity(self, entity: DescribedLaunchEntity) -> None:
86 | """Display a description of a launch entity in the GUI."""
87 | pass
88 |
89 | def on_execution_complete(self, entity: DescribedLaunchEntity) -> None:
90 | """Display a completion event in the GUI."""
91 | pass
92 |
93 | def on_state_transition(self, entity: DescribedLaunchEntity, start_state: str, goal_state: str) -> None:
94 | """Display a state transition in the GUI."""
95 | pass
96 |
97 | def on_close(self):
98 | """Called when the GUI is closed."""
99 | # only shutdown the launch if close was requested from the gui
100 | if not self.close_requested:
101 | self.add_pending_action(Shutdown())
102 |
103 | def handle(self, event: Event, context: LaunchContext) -> Optional[SomeEntitiesType]:
104 | """Handle a launch event."""
105 | if isinstance(event, RunningProcessEvent):
106 | if isinstance(event, ProcessStarted):
107 | self.on_process_started(event.process_name, event.pid, DescribedLaunchEntity(event.action, context))
108 | elif isinstance(event, ProcessExited):
109 | self.on_process_exited(event.process_name, event.pid, DescribedLaunchEntity(event.action, context), event.returncode)
110 | elif isinstance(event, ProcessIO):
111 | self.on_process_io(event.process_name, event.text)
112 | elif isinstance(event, ExecutionComplete):
113 | self.on_execution_complete(DescribedLaunchEntity(event.action, context))
114 | elif isinstance(event, IncludeLaunchDescription):
115 | self.on_describe_launch_entity(DescribedLaunchEntity(event.launch_description, context))
116 | elif isinstance(event, StateTransition):
117 | self.on_state_transition(
118 | DescribedLaunchEntity(event.action, context),
119 | event.start_state,
120 | event.goal_state
121 | )
122 | return None
123 |
--------------------------------------------------------------------------------
/ros2launch_gui/event_handlers/__init__.py:
--------------------------------------------------------------------------------
1 | from .on_user_interface_event import OnUserInterfaceEvent
2 |
3 | __all__ = [
4 | 'OnUserInterfaceEvent',
5 | ]
6 |
--------------------------------------------------------------------------------
/ros2launch_gui/event_handlers/on_user_interface_event.py:
--------------------------------------------------------------------------------
1 | from launch.actions import TimerAction
2 | from launch.actions import EmitEvent
3 | from launch.actions import LogInfo
4 | from launch.event_handler import BaseEventHandler
5 | from launch.events import Shutdown
6 | from ros2launch_gui.events import QueryUserInterface
7 |
8 | class OnUserInterfaceEvent(BaseEventHandler):
9 | def __init__(self, ui, debug: bool = False):
10 | super().__init__(matcher=lambda event: True)
11 | self._ui = ui
12 | self._debug = debug
13 |
14 | def handle(self, event, context):
15 | super().handle(event, context)
16 | if self._ui is None:
17 | return None
18 | if isinstance(event, Shutdown):
19 | self._ui.close()
20 | self._ui = None
21 | return None
22 | if isinstance(event, QueryUserInterface):
23 | return [TimerAction(
24 | period=0.5,
25 | actions=[EmitEvent(event=QueryUserInterface())])
26 | ] + self._ui.get_pending_actions()
27 | try:
28 | return self._ui.handle(event, context)
29 | except Exception as e:
30 | if self._debug:
31 | self._ui.close()
32 | self._ui = None
33 | raise
34 | return [LogInfo(msg=f'Exception while ui was handling event: {event.name}, exception: {e}')]
35 |
--------------------------------------------------------------------------------
/ros2launch_gui/events/__init__.py:
--------------------------------------------------------------------------------
1 | from .query_user_interface import QueryUserInterface
2 |
3 | __all__ = [
4 | 'QueryUserInterface',
5 | ]
6 |
--------------------------------------------------------------------------------
/ros2launch_gui/events/query_user_interface.py:
--------------------------------------------------------------------------------
1 |
2 | from launch import Event
3 |
4 | class QueryUserInterface(Event):
5 | """Event sent at regular interval to collect Actions from a user interface"""
6 |
7 | name = 'ros2launch_gui.events.QueryUserInterface'
8 |
9 | def __init__(self):
10 | super().__init__()
11 |
--------------------------------------------------------------------------------
/ros2launch_gui/option/__init__.py:
--------------------------------------------------------------------------------
1 | from . import gui
2 |
3 | __all__ = [
4 | 'gui'
5 | ]
6 |
--------------------------------------------------------------------------------
/ros2launch_gui/option/gui.py:
--------------------------------------------------------------------------------
1 |
2 | from launch import LaunchDescription
3 |
4 | from ros2launch_gui.actions import DisplayUserInterface
5 | from ros2launch.option import OptionExtension
6 |
7 | from typing import Tuple
8 |
9 |
10 | class GuiOption(OptionExtension):
11 |
12 | def add_arguments(self, parser, cli_name, *, argv=None):
13 | parser.add_argument(
14 | '-g', '--gui',
15 | action='store_true',
16 | help='Display launch status in a GUI'
17 | )
18 |
19 | def prelaunch(
20 | self,
21 | launch_description: LaunchDescription,
22 | args
23 | ) -> Tuple[LaunchDescription,]:
24 | if(args.gui):
25 | return LaunchDescription(
26 | [
27 | DisplayUserInterface(launch_description=launch_description, debug=args.debug),
28 | ]
29 | ),
30 |
31 | return launch_description,
32 |
33 |
34 |
--------------------------------------------------------------------------------
/ros2launch_gui/qt/__init__.py:
--------------------------------------------------------------------------------
1 | from .main import UserInterface
2 |
3 | __all__ = [
4 | 'UserInterface',
5 | ]
6 |
--------------------------------------------------------------------------------
/ros2launch_gui/qt/details_widget.py:
--------------------------------------------------------------------------------
1 | from python_qt_binding.QtWidgets import QPushButton
2 | from python_qt_binding.QtWidgets import QWidget
3 | from python_qt_binding.QtWidgets import QVBoxLayout
4 |
5 | from .process_output_widget import ProcessOutputWidget
6 |
7 | class DetailsWidget(QWidget):
8 | """A widget to manage and display detail widgets."""
9 |
10 | def __init__(self, parent=None):
11 | """Create a DetailsWidget."""
12 | super().__init__(parent)
13 |
14 | self.all_process_output_widget = ProcessOutputWidget(self)
15 | self.process_output_widgets = {}
16 |
17 | self.layout = QVBoxLayout()
18 |
19 | show_all_button = QPushButton('Show All Processes')
20 | show_all_button.clicked.connect(self.show_all_processes_output)
21 | self.layout.addWidget(show_all_button)
22 |
23 | self.layout.addWidget(self.all_process_output_widget)
24 | self.current_widget = self.all_process_output_widget
25 |
26 | self.setLayout(self.layout)
27 |
28 | def on_process_started(self, process_name, pid):
29 | if process_name in self.process_output_widgets:
30 | process_output_widget = self.process_output_widgets[process_name]
31 | else:
32 | process_output_widget = ProcessOutputWidget(self, show_process_name=False)
33 | self.process_output_widgets[process_name] = process_output_widget
34 | process_output_widget.hide()
35 | self.layout.addWidget(process_output_widget)
36 |
37 | process_output_widget.on_process_io(process_name, f'Process {pid} started for {process_name}')
38 |
39 | def on_process_io(self, process_name, text):
40 | self.all_process_output_widget.on_process_io(process_name, text)
41 | if process_name in self.process_output_widgets:
42 | self.process_output_widgets[process_name].on_process_io(process_name, text)
43 |
44 | def on_process_exited(self, process_name, return_code):
45 | if process_name in self.process_output_widgets:
46 | self.process_output_widgets[process_name].on_process_io(process_name, f'Process exited with return code {return_code}')
47 |
48 | def show_all_processes_output(self):
49 | self.current_widget.hide()
50 | self.current_widget = self.all_process_output_widget
51 | self.current_widget.show()
52 |
53 | def show_process_output(self, process_name):
54 | if process_name in self.process_output_widgets:
55 | self.current_widget.hide()
56 | self.current_widget = self.process_output_widgets[process_name]
57 | self.current_widget.show()
58 |
--------------------------------------------------------------------------------
/ros2launch_gui/qt/launch_description_widget.py:
--------------------------------------------------------------------------------
1 | import signal
2 |
3 | from typing import Callable
4 |
5 | from python_qt_binding.QtCore import Qt
6 | from python_qt_binding.QtGui import QBrush
7 | from python_qt_binding.QtGui import QColor
8 | from python_qt_binding.QtWidgets import QMenu
9 | from python_qt_binding.QtWidgets import QTreeWidgetItem
10 | from python_qt_binding.QtWidgets import QTreeWidget
11 | from python_qt_binding.QtWidgets import QVBoxLayout
12 | from python_qt_binding.QtWidgets import QWidget
13 |
14 | from launch.actions import EmitEvent
15 | from launch.events.process import SignalProcess
16 | from launch.events.process.process_matchers import matches_pid
17 | from launch_ros.events.lifecycle import ChangeState
18 | from launch_ros.events import matches_node_name
19 | from ros2launch_gui.api.describe import DescribedLaunchEntity
20 |
21 | from lifecycle_msgs.msg import Transition
22 |
23 |
24 | class LaunchDescriptionWidget(QWidget):
25 | """
26 | A widget that displays a launch description as a tree.
27 |
28 | The tree is updated when the launch is executed showing the status of processes.
29 | """
30 |
31 | DetailsCallbackRole = Qt.UserRole
32 | ContextMenuRole = Qt.UserRole + 1
33 |
34 |
35 | lifecycle_transitions = {
36 | 'unconfigured': (
37 | ('Configure', Transition.TRANSITION_CONFIGURE),
38 | ('Shutdown', Transition.TRANSITION_UNCONFIGURED_SHUTDOWN)
39 | ),
40 | 'inactive': (
41 | ('Activate', Transition.TRANSITION_ACTIVATE),
42 | ('Shutdown', Transition.TRANSITION_INACTIVE_SHUTDOWN),
43 | ('Cleanup', Transition.TRANSITION_CLEANUP)
44 | ),
45 | 'active': (
46 | ('Deactivate', Transition.TRANSITION_DEACTIVATE),
47 | ('Shutdown', Transition.TRANSITION_ACTIVE_SHUTDOWN)
48 | ),
49 | }
50 |
51 |
52 | def __init__(self, ui, parent=None):
53 | super().__init__(parent)
54 |
55 | self._ui = ui
56 | self.tree = QTreeWidget(self)
57 | self.tree.setHeaderLabels(['Launch Entity', 'Status', 'Name', 'Description'])
58 | self.tree.header().resizeSection(0, 350)
59 | self.tree.header().resizeSection(1, 75)
60 | self.tree.header().resizeSection(2, 200)
61 |
62 | self.tree.itemActivated.connect(self.on_item_selected)
63 | self.tree.itemClicked.connect(self.on_item_selected)
64 | self.tree.currentItemChanged.connect(self.on_item_selected)
65 |
66 | self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
67 | self.tree.customContextMenuRequested.connect(self.show_context_menu)
68 |
69 | layout = QVBoxLayout()
70 | layout.addWidget(self.tree)
71 | self.setLayout(layout)
72 |
73 | self.entity_items = {}
74 | self.process_items = {}
75 | self.launch_arguments_items = {}
76 | self.entity_condition_items = {}
77 |
78 |
79 | def on_item_selected(self, item, column):
80 | if item is not None:
81 | selected_callback = item.data(0, self.DetailsCallbackRole)
82 | if selected_callback is not None:
83 | selected_callback()
84 |
85 | def on_describe_launch_entity(self, entity: DescribedLaunchEntity) -> None:
86 | self.add_launch_entity_to_tree(entity)
87 | self.tree.expandAll()
88 |
89 | def on_execution_complete(self, entity: DescribedLaunchEntity) -> None:
90 | self.updated_launch_entity(entity, status='done')
91 |
92 | def on_entity_process_started(
93 | self,
94 | entity: DescribedLaunchEntity,
95 | process_name: str,
96 | pid: int,
97 | selected_callback=None
98 | ) -> None:
99 | if process_name in self.process_items:
100 | process_item = self.process_items[process_name]
101 | else:
102 | process_item = QTreeWidgetItem(['Process', 'running', process_name, f'PID: {pid}'])
103 | self.process_items[process_name] = process_item
104 | if entity.id in self.entity_items:
105 | item = self.entity_items[entity.id]
106 | item.addChild(process_item)
107 | item.setExpanded(True)
108 | if entity.type_name == "LifecycleNode":
109 | self.on_state_transition(entity, 'unknown', 'unconfigured')
110 | else:
111 | self.tree.addTopLevelItem(process_item)
112 |
113 | process_item.setText(1, 'running')
114 | process_item.setText(3, f'PID: {pid}')
115 | process_item.setData(0, self.DetailsCallbackRole, selected_callback)
116 | process_item.setData(1, Qt.BackgroundRole, QBrush(QColor(100, 255, 100)))
117 | process_item.setData(
118 | 0,
119 | self.ContextMenuRole,
120 | lambda menu: menu.addAction(
121 | f'Stop {process_name}',
122 | lambda: self._ui.add_pending_action(
123 | EmitEvent(
124 | event=SignalProcess(
125 | signal_number= signal.SIGINT,
126 | process_matcher=matches_pid(pid)
127 | )
128 | )
129 | )
130 | )
131 | )
132 |
133 | def get_lifecycle_menu_items(self, menu: QMenu, node_name: str, current_state: str) -> None:
134 | for label, transition_id in self.lifecycle_transitions[current_state]:
135 | menu.addAction(
136 | f'{label} {node_name}',
137 | lambda id=transition_id: self._ui.add_pending_action(
138 | EmitEvent(
139 | event=ChangeState(
140 | lifecycle_node_matcher=matches_node_name(node_name),
141 | transition_id=id
142 | )
143 | )
144 | )
145 | )
146 |
147 |
148 | def on_entity_process_exited(self, entity: DescribedLaunchEntity, process_name: str, pid: int, return_code) -> None:
149 | if process_name in self.process_items:
150 | item = self.process_items[process_name]
151 | item.setText(1, f'exit: {return_code}')
152 | if return_code == 0:
153 | item.setData(1, Qt.BackgroundRole, QBrush(QColor(200, 255, 200)))
154 | else:
155 | item.setData(1, Qt.BackgroundRole, QBrush(QColor(255, 128, 128)))
156 | item.setData(0, self.ContextMenuRole, None)
157 |
158 | def updated_launch_entity(self, launch_entity: DescribedLaunchEntity, status=None):
159 | if launch_entity.condition is not None:
160 | if launch_entity.id in self.entity_condition_items:
161 | item = self.entity_condition_items[launch_entity.id]
162 | item.setText(2, launch_entity.condition)
163 | if launch_entity.id in self.entity_items:
164 | item = self.entity_items[launch_entity.id]
165 | item.setText(2, launch_entity.label)
166 | item.setText(3, str(launch_entity.description))
167 | if status is not None:
168 | item.setText(1, status)
169 | if launch_entity.type_name == "IncludeLaunchDescription":
170 | for child in launch_entity.children:
171 | if child.id not in self.entity_items:
172 | self.add_launch_entity_to_tree(child, launch_entity)
173 | for child in launch_entity.children:
174 | self.updated_launch_entity(child)
175 |
176 | def on_state_transition(self, entity: DescribedLaunchEntity, start_state: str, goal_state: str) -> None:
177 | if entity.id in self.entity_items:
178 | item = self.entity_items[entity.id]
179 | item.setText(1, f'{goal_state}')
180 | if goal_state == 'active':
181 | item.setData(1, Qt.BackgroundRole, QBrush(QColor(100, 255, 100)))
182 | else:
183 | item.setData(1, Qt.BackgroundRole, QBrush(QColor(255, 255, 100)))
184 | if goal_state in self.lifecycle_transitions:
185 | item.setData(0, self.ContextMenuRole, lambda menu: self.get_lifecycle_menu_items(menu, entity.label, goal_state))
186 | else:
187 | item.setData(0, self.ContextMenuRole, None)
188 |
189 | def add_launch_entity_to_tree(
190 | self,
191 | launch_entity: DescribedLaunchEntity,
192 | parent: DescribedLaunchEntity=None,
193 | status=None
194 | ):
195 | if launch_entity.id in self.entity_items:
196 | item = self.entity_items[launch_entity.id]
197 | if status is not None:
198 | item.setText(1, status)
199 | else:
200 | status_text = status if status is not None else ''
201 | item = QTreeWidgetItem([launch_entity.type_name, status_text, launch_entity.label, str(launch_entity.description), status])
202 | parent_item = None
203 | expand_parent = True
204 | if parent is not None:
205 | if parent.id in self.entity_items:
206 | parent_item = self.entity_items[parent.id]
207 | if launch_entity.type_name == "DeclareLaunchArgument":
208 | if not parent.id in self.launch_arguments_items:
209 | self.launch_arguments_items[parent.id] = QTreeWidgetItem(['Launch Arguments', '', '', ''])
210 | parent_item.addChild(self.launch_arguments_items[parent.id])
211 | parent_item = self.launch_arguments_items[parent.id]
212 | expand_parent = False
213 | if launch_entity.condition is not None:
214 | if launch_entity.id in self.entity_condition_items:
215 | condition_item = self.entity_condition_items[launch_entity.id]
216 | else:
217 | condition_item = QTreeWidgetItem(['Condition', '', launch_entity.condition, ''])
218 | self.entity_condition_items[launch_entity.id] = condition_item
219 | if parent_item is not None:
220 | parent_item.addChild(condition_item)
221 | parent_item.setExpanded(True)
222 | else:
223 | self.tree.addTopLevelItem(condition_item)
224 | parent_item = condition_item
225 | if parent_item is not None:
226 | parent_item.addChild(item)
227 | if expand_parent:
228 | parent_item.setExpanded(True)
229 | else:
230 | self.tree.addTopLevelItem(item)
231 | item.setExpanded(True)
232 | self.entity_items[launch_entity.id] = item
233 | if launch_entity.type_name == "LifecycleNode":
234 | item.setData(1, Qt.BackgroundRole, QBrush(QColor(255, 255, 100)))
235 | if status is None:
236 | # assuming lifecycle node is unconfigured until we know otherwise
237 | status = 'unconfigured'
238 | if status in self.lifecycle_transitions:
239 | item.setData(0, self.ContextMenuRole, lambda menu: self.get_lifecycle_menu_items(menu, launch_entity.label, status))
240 |
241 |
242 | for child in launch_entity.children:
243 | self.add_launch_entity_to_tree(child, launch_entity)
244 | for condition, sub_entities in launch_entity.conditional_children:
245 | for sub_entity in sub_entities:
246 | self.add_launch_entity_to_tree(sub_entity, launch_entity)
247 |
248 | def show_context_menu(self, pos):
249 | item = self.tree.itemAt(pos)
250 | if item is not None:
251 | context_menu_callback = item.data(0, self.ContextMenuRole)
252 | if context_menu_callback is not None:
253 | menu = QMenu(self)
254 | context_menu_callback(menu)
255 | menu.exec_(self.tree.mapToGlobal(pos))
256 |
257 |
--------------------------------------------------------------------------------
/ros2launch_gui/qt/main.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 |
3 | from python_qt_binding.QtWidgets import QApplication
4 | from python_qt_binding.QtWidgets import QMainWindow
5 | from python_qt_binding.QtWidgets import QSplitter
6 |
7 |
8 | from ..api import UserInterface as UserInterfaceBase
9 |
10 | from launch import LaunchDescription
11 | from launch.actions import OpaqueCoroutine
12 |
13 | from .details_widget import DetailsWidget
14 | from .launch_description_widget import LaunchDescriptionWidget
15 |
16 |
17 | class MainWindow(QMainWindow):
18 | def __init__(self, ui: 'UserInterface'=None):
19 | super().__init__()
20 |
21 | self._ui = ui
22 | self.setWindowTitle("ROS 2 Launch GUI")
23 | self.launch_description_widget = LaunchDescriptionWidget(ui, self)
24 | self.details_widget = DetailsWidget(self)
25 |
26 | splitter = QSplitter()
27 | splitter.addWidget(self.launch_description_widget)
28 | splitter.addWidget(self.details_widget)
29 |
30 |
31 | self.setCentralWidget(splitter)
32 | self.show()
33 |
34 | def on_process_started(self, action, process_name, pid):
35 | self.details_widget.on_process_started(process_name, pid)
36 | self.launch_description_widget.on_entity_process_started(action, process_name, pid, lambda: self.details_widget.show_process_output(process_name))
37 |
38 | def on_process_exited(self, action, process_name, pid, return_code):
39 | self.details_widget.on_process_exited(process_name, return_code)
40 | self.launch_description_widget.on_entity_process_exited(action, process_name, pid, return_code)
41 |
42 | def on_process_io(self, process_name, text):
43 | self.details_widget.on_process_io(process_name, text)
44 |
45 | def on_describe_launch_entity(self, entity):
46 | self.launch_description_widget.on_describe_launch_entity(entity)
47 |
48 | def on_execution_complete(self, entity):
49 | self.launch_description_widget.on_execution_complete(entity)
50 |
51 | def on_state_transition(self, entity, start_state, goal_state):
52 | self.launch_description_widget.on_state_transition(entity, start_state, goal_state)
53 |
54 | def closeEvent(self, event):
55 | if self._ui is not None:
56 | self._ui.on_close()
57 | event.accept()
58 |
59 | class UserInterface(UserInterfaceBase):
60 | def __init__(
61 | self,
62 | launch_description: LaunchDescription,
63 | debug: bool = False,
64 |
65 | ):
66 | super().__init__(launch_description, debug)
67 |
68 | self.closing = False
69 |
70 | self.app = QApplication([])
71 | self.main_window = MainWindow(self)
72 | self.main_window.resize(1280, 720)
73 | self.main_window.show()
74 |
75 | self.add_pending_action(OpaqueCoroutine(coroutine=self.run_qt))
76 |
77 | async def run_qt(self, *args, **kwargs):
78 | while not self.closing:
79 | if self.close_requested:
80 | self.main_window.close()
81 | self.app.processEvents()
82 | await asyncio.sleep(0.05)
83 |
84 | def on_process_started(self, process_name, pid, action):
85 | self.main_window.on_process_started(action, process_name, pid)
86 |
87 | def on_process_exited(self, process_name, pid, action, return_code):
88 | self.main_window.on_process_exited(action, process_name, pid, return_code)
89 |
90 | def on_process_io(self, process_name, text):
91 | self.main_window.on_process_io(process_name, text.decode())
92 |
93 | def on_describe_launch_entity(self, entity):
94 | self.main_window.on_describe_launch_entity(entity)
95 |
96 | def on_execution_complete(self, entity):
97 | self.main_window.on_execution_complete(entity)
98 |
99 | def on_state_transition(self, entity, start_state, goal_state):
100 | self.main_window.on_state_transition(entity, start_state, goal_state)
101 |
102 | def on_close(self):
103 | self.closing = True
104 | super().on_close()
105 |
106 |
--------------------------------------------------------------------------------
/ros2launch_gui/qt/process_output_widget.py:
--------------------------------------------------------------------------------
1 | import re
2 | from python_qt_binding.QtWidgets import QPlainTextEdit
3 | from python_qt_binding.QtWidgets import QVBoxLayout
4 | from python_qt_binding.QtWidgets import QWidget
5 |
6 | # ANSI color code mapping to HTML colors
7 | ANSI_COLOR_MAP = {
8 | '30': '#FFFFFF', # Black
9 | '31': '#FF0000', # Red
10 | '32': '#00FF00', # Green
11 | '33': '#FF7F00', # Yellow (actually Orange for better readability)
12 | '34': '#0000FF', # Blue
13 | '35': '#FF00FF', # Magenta
14 | '36': '#00FFFF', # Cyan
15 | '37': '#FFFFFF', # White (actually Black to see it on white background)
16 | }
17 |
18 | # Regular expression to match ANSI escape codes
19 | ansi_color_re = re.compile(r'\033\[([0-9;]*)m')
20 |
21 | def ansi_to_html(text):
22 | matches = ansi_color_re.match(text)
23 | if not matches:
24 | return text
25 | codes = matches.group(1).split(';')
26 | # remove the ANSI escape codes from the text
27 | text = ansi_color_re.sub('', text)
28 | if not codes:
29 | return text
30 |
31 | modifier = None
32 | color_code = None
33 | # reset case
34 | if codes[0] == '0':
35 | return text
36 | # color + modifier
37 | if len(codes) > 1:
38 | modifier = codes[0]
39 | color_code = ANSI_COLOR_MAP.get(codes[1])
40 | # only color code present
41 | else:
42 | color_code = ANSI_COLOR_MAP.get(codes[0])
43 |
44 | html_start = f''
45 | html_end = ''
46 | if modifier == '1':
47 | html_text = f'{html_start}{text}{html_end}'
48 | elif modifier == '3':
49 | html_text = f'{html_start}{text}{html_end}'
50 | elif modifier == '4':
51 | html_text = f'{html_start}{text}{html_end}'
52 | else:
53 | html_text = f'{html_start}{text}{html_end}'
54 | return html_text
55 |
56 | class ProcessOutputWidget(QWidget):
57 | """Widget to display output from launch processes."""
58 |
59 | def __init__(self, parent, show_process_name = True):
60 | """Create a ProcessOutputWidget."""
61 | super().__init__(parent)
62 |
63 | self.show_process_name = show_process_name
64 |
65 | self.text_edit = QPlainTextEdit(self)
66 | self.text_edit.setReadOnly(True)
67 |
68 | layout = QVBoxLayout()
69 | layout.addWidget(self.text_edit)
70 | self.setLayout(layout)
71 | self.text_edit.show()
72 |
73 |
74 | def on_process_io(self, process_name, text):
75 | for line in text.split('\n'):
76 | line = line.rstrip()
77 | if line:
78 | line = ansi_to_html(line)
79 | if self.show_process_name:
80 | self.text_edit.appendHtml(f'[{process_name}] {line}')
81 | else:
82 | self.text_edit.appendHtml(line)
83 |
--------------------------------------------------------------------------------
/ros2launch_gui/tk/__init__.py:
--------------------------------------------------------------------------------
1 | from .user_interface import UserInterface
2 |
3 | __all__ = [
4 | 'UserInterface',
5 | ]
6 |
--------------------------------------------------------------------------------
/ros2launch_gui/tk/event_viewer.py:
--------------------------------------------------------------------------------
1 | from tkinter import ttk
2 | from tkinter.scrolledtext import ScrolledText
3 |
4 | from ros2launch_gui.api import DescribedEvent
5 |
6 | class EventViewer(ttk.Frame):
7 | """A widget that shows launch events."""
8 |
9 | def __init__(self, parent=None):
10 | super().__init__(parent)
11 |
12 | self.text = ScrolledText(self, state='disabled')
13 | self.text.grid(column=0, row=0, sticky=('N', 'W', 'E', 'S'))
14 | self.rowconfigure(0, weight=1)
15 | self.columnconfigure(0, weight=1)
16 |
17 | def on_event(self, event: DescribedEvent) -> None:
18 | self.text.config(state='normal')
19 | self.text.insert('end', '{}\n'.format(event))
20 | #self.text.see('end')
21 | self.text.config(state='disabled')
22 |
23 |
24 |
--------------------------------------------------------------------------------
/ros2launch_gui/tk/launch_description_treeview.py:
--------------------------------------------------------------------------------
1 | from tkinter import ttk
2 |
3 | from ros2launch_gui.api.describe import DescribedLaunchEntity
4 |
5 | class LaunchDescriptionTreeview(ttk.Frame):
6 | """A widget that displays a launch description as a tree."""
7 |
8 | def __init__(self, parent=None):
9 | super().__init__(parent)
10 |
11 | self.tree = ttk.Treeview(self, columns=('name', 'description', 'status'))
12 | self.tree.heading('#0', text='Launch Entity')
13 | self.tree.column('#0', width=350, stretch=False)
14 | self.tree.heading('name', text='Name')
15 | self.tree.column('name', width=200, stretch=False)
16 | self.tree.heading('description', text='Description')
17 | self.tree.heading('status', text='Status')
18 | self.tree.column('status', width=80, stretch=False)
19 | self.tree.grid(column=0, row=0, sticky=('N', 'W', 'E', 'S'))
20 | self.columnconfigure(0, weight=1)
21 | self.rowconfigure(0, weight=1)
22 |
23 | self.tree_ids = {}
24 | self.process_ids = {}
25 |
26 | self.process_selected_callbacks = []
27 |
28 | self.tree.bind("<>", self.on_tree_item_selected)
29 |
30 |
31 |
32 | def add_process_selected_callback(self, callback):
33 | self.process_selected_callbacks.append(callback)
34 |
35 | def on_describe_launch_entity(self, entity: DescribedLaunchEntity) -> None:
36 | self.add_launch_entity_to_tree(entity)
37 |
38 | def on_execution_complete(self, entity: DescribedLaunchEntity) -> None:
39 | self.updated_launch_entity(entity, status='done')
40 |
41 | def on_entity_process_started(self, entity: DescribedLaunchEntity, process_name: str, pid: int) -> None:
42 | if entity.id in self.tree_ids:
43 | item_id = self.tree_ids[entity.id]
44 | self.tree.item(item_id, open=True)
45 | self.process_ids[process_name] = self.tree.insert(item_id, 'end', text="Process", values=(process_name, 'PID: {}'.format(pid), 'running'))
46 |
47 | def on_entity_process_exited(self, entity: DescribedLaunchEntity, process_name: str, pid: int, return_code) -> None:
48 | if process_name in self.process_ids:
49 | item_id = self.process_ids[process_name]
50 | self.tree.item(item_id, values=(process_name, 'PID: {}'.format(pid), 'exit: {}'.format(return_code)))
51 |
52 | def updated_launch_entity(self, launch_entity: DescribedLaunchEntity, status=None):
53 | if launch_entity.id in self.tree_ids:
54 | item_id = self.tree_ids[launch_entity.id]
55 | status_text = status if status is not None else ''
56 | self.tree.item(item_id, values=(launch_entity.label, launch_entity.description, status_text))
57 | if launch_entity.type_name == "IncludeLaunchDescription":
58 | for child in launch_entity.children:
59 | if child.id not in self.tree_ids:
60 | self.add_launch_entity_to_tree(child, item_id)
61 | for child in launch_entity.children:
62 | self.updated_launch_entity(child)
63 |
64 | def add_launch_entity_to_tree(
65 | self,
66 | launch_entity: DescribedLaunchEntity,
67 | parent='',
68 | status=None
69 | ):
70 | if launch_entity.id in self.tree_ids:
71 | item_id = self.tree_ids[launch_entity.id]
72 | else:
73 | item_id = self.tree.insert(parent, 'end', text=launch_entity.type_name, open=True)
74 | self.tree_ids[launch_entity.id] = item_id
75 | status_text = status if status is not None else ''
76 | self.tree.item(item_id, values=(launch_entity.label, launch_entity.description, status_text))
77 | for child in launch_entity.children:
78 | self.add_launch_entity_to_tree(child, item_id)
79 |
80 | def on_tree_item_selected(self, event):
81 | selected_id = self.tree.selection()[0]
82 | for name in self.process_ids:
83 | if selected_id == self.process_ids[name]:
84 | for callback in self.process_selected_callbacks:
85 | callback(name)
86 | return
87 |
--------------------------------------------------------------------------------
/ros2launch_gui/tk/process_manager.py:
--------------------------------------------------------------------------------
1 | from tkinter import ttk
2 | from tkinter.scrolledtext import ScrolledText
3 |
4 | from ros2launch_gui.api.describe import DescribedLaunchEntity
5 |
6 | class ProcessList(ttk.Frame):
7 | """A widget that displays a list of launch processes and their status."""
8 |
9 | def __init__(self, parent=None):
10 | super().__init__(parent)
11 |
12 | self.tree = ttk.Treeview(self, columns=('pid', 'status'))
13 | self.tree.heading('#0', text='Name')
14 | self.tree.heading('pid', text='PID')
15 | self.tree.heading('status', text='Status')
16 | self.tree.grid(column=0, row=0, sticky=('N', 'W', 'E', 'S'))
17 | self.columnconfigure(0, weight=1)
18 | self.rowconfigure(0, weight=1)
19 |
20 | self.tree.column('pid', width=100)
21 | self.tree.column('status', width=100)
22 |
23 | self.tree_ids = {}
24 |
25 |
26 | def get_item_id(self, process_name: str) -> str:
27 | if not process_name in self.tree_ids:
28 | self.tree_ids[process_name] = self.tree.insert('', 'end', text=process_name, values=(0, 'unknown'))
29 | return self.tree_ids[process_name]
30 |
31 |
32 | def on_process_started(
33 | self,
34 | process_name: str,
35 | pid: int,
36 | action: DescribedLaunchEntity
37 | ) -> None:
38 | item_id = self.get_item_id(process_name)
39 | self.tree.item(item_id, values=(pid, 'active'))
40 |
41 | def on_process_exited(
42 | self,
43 | process_name: str,
44 | pid: int,
45 | action: DescribedLaunchEntity,
46 | return_code
47 | ) -> None:
48 | item_id = self.get_item_id(process_name)
49 | self.tree.item(item_id, values=(pid, 'exit: {}'.format(return_code)))
50 |
51 | class ProcessIOView(ttk.Frame):
52 | def __init__(self, parent=None, show_process_name: bool = False):
53 | super().__init__(parent)
54 |
55 | self.text = ScrolledText(self, state='disabled')
56 | self.text.grid(column=0, row=0, sticky=('N', 'W', 'E', 'S'))
57 | self.rowconfigure(0, weight=1)
58 | self.columnconfigure(0, weight=1)
59 |
60 | self.show_process_name = show_process_name
61 |
62 |
63 | def on_process_io(self, process_name: str, data: str) -> None:
64 | self.text.config(state='normal')
65 | if self.show_process_name:
66 | for line in data.splitlines():
67 | self.text.insert('end', '[{}] {}\n'.format(process_name, line.decode()))
68 | else:
69 | self.text.insert('end', data)
70 | #self.text.see('end')
71 | self.text.config(state='disabled')
72 |
73 | class ProcessIONotebook(ttk.Frame):
74 | def __init__(self, parent=None):
75 | super().__init__(parent)
76 |
77 | self.notebook = ttk.Notebook(self)
78 | self.notebook.grid(column=0, row=0, sticky=('N', 'W', 'E', 'S'))
79 | self.columnconfigure(0, weight=1)
80 | self.rowconfigure(0, weight=1)
81 |
82 | self.io_widgets = {}
83 | self.all = ProcessIOView(self, show_process_name=True)
84 | self.notebook.add(self.all, text='All')
85 |
86 | def on_select_process(self, process_name: str) -> None:
87 | if process_name in self.io_widgets:
88 | self.notebook.select(self.io_widgets[process_name])
89 |
90 | def on_process_io(
91 | self,
92 | process_name: str,
93 | data: str
94 | ) -> None:
95 | if process_name in self.io_widgets:
96 | io_widget = self.io_widgets[process_name]
97 | else:
98 | io_widget = ProcessIOView(self)
99 | self.io_widgets[process_name] = io_widget
100 | self.notebook.add(io_widget, text=process_name)
101 |
102 | io_widget.on_process_io(process_name, data)
103 | self.all.on_process_io(process_name, data)
104 |
105 | def on_process_started(
106 | self,
107 | process_name: str,
108 | pid: int,
109 | action: DescribedLaunchEntity
110 | ) -> None:
111 | if process_name in self.io_widgets:
112 | io_widget = self.io_widgets[process_name]
113 | else:
114 | io_widget = ProcessIOView(self)
115 | self.io_widgets[process_name] = io_widget
116 | self.notebook.add(io_widget, text=process_name)
117 | io_widget.on_process_io(process_name, 'Process {} started for action: {}\n'.format(pid, action))
118 |
119 | def on_process_exited(
120 | self,
121 | process_name: str,
122 | pid: int,
123 | action: DescribedLaunchEntity,
124 | return_code
125 | ) -> None:
126 | if process_name in self.io_widgets:
127 | io_widget = self.io_widgets[process_name]
128 | io_widget.on_process_io(process_name, 'Process {} exited with return code: {}\n'.format(pid, return_code))
129 |
130 | class ProcessManager(ttk.Frame):
131 | """A widget that displays a list of launch processes as well as their output in a tabbed display."""
132 |
133 | def __init__(self, parent=None):
134 | super().__init__(parent)
135 |
136 | self.io_notebook = ProcessIONotebook(self)
137 | self.io_notebook.grid(column=0, row=0, sticky=('N', 'W', 'E', 'S'))
138 | self.columnconfigure(0, weight=1)
139 | self.rowconfigure(0, weight=1)
140 |
141 | def on_select_process(self, process_name: str) -> None:
142 | self.io_notebook.on_select_process(process_name)
143 |
144 | def on_process_io(
145 | self,
146 | process_name: str,
147 | data: str
148 | ) -> None:
149 | self.io_notebook.on_process_io(process_name, data)
150 |
151 | def on_process_started(
152 | self,
153 | process_name: str,
154 | pid: int,
155 | action: DescribedLaunchEntity
156 | ) -> None:
157 | self.io_notebook.on_process_started(process_name, pid, action)
158 |
159 | def on_process_exited(
160 | self,
161 | process_name: str,
162 | pid: int,
163 | action: DescribedLaunchEntity,
164 | return_code
165 | ) -> None:
166 | self.io_notebook.on_process_exited(process_name, pid, action, return_code)
167 |
--------------------------------------------------------------------------------
/ros2launch_gui/tk/user_interface.py:
--------------------------------------------------------------------------------
1 |
2 | import asyncio
3 |
4 | from tkinter import Tk
5 | from tkinter import ttk
6 |
7 | from launch import LaunchDescription
8 | from launch.actions import OpaqueCoroutine
9 |
10 | from ..api import DescribedLaunchEntity
11 | from ..api import UserInterface as UserInterfaceBase
12 | from .launch_description_treeview import LaunchDescriptionTreeview
13 | from .process_manager import ProcessManager
14 |
15 | class UserInterface(UserInterfaceBase):
16 | def __init__(
17 | self,
18 | launch_description: LaunchDescription,
19 | debug: bool = False
20 | ):
21 | super().__init__(launch_description, debug)
22 | self.root = Tk()
23 | self.root.title("ROS 2 Launch GUI")
24 | self.root.grid_rowconfigure(0, weight=1)
25 | self.root.grid_columnconfigure(0, weight=1)
26 |
27 | self.closing = False
28 | self.root.protocol("WM_DELETE_WINDOW", self.on_close)
29 |
30 | main_window = ttk.PanedWindow(self.root, orient='horizontal')
31 | main_window.grid(column=0, row=0, sticky=('N', 'W', 'E', 'S'))
32 | self.root.columnconfigure(0, weight=1)
33 | self.root.rowconfigure(0, weight=1)
34 |
35 | self.launch_description_viewer = LaunchDescriptionTreeview(main_window)
36 | main_window.add(self.launch_description_viewer, weight=1)
37 |
38 | self.process_manager = ProcessManager(main_window)
39 | main_window.add(self.process_manager, weight=1)
40 |
41 | self.launch_description_viewer.add_process_selected_callback(self.process_manager.on_select_process)
42 |
43 | self.add_pending_action(OpaqueCoroutine(coroutine=self.run_tk))
44 |
45 | async def run_tk(self, *args, **kwargs):
46 | while not self.closing:
47 | self.root.update()
48 | await asyncio.sleep(0.05)
49 | self.root.destroy()
50 |
51 | def on_process_started(self, process_name, pid, action: DescribedLaunchEntity):
52 | if not self.closing:
53 | self.process_manager.on_process_started(process_name, pid, action)
54 | self.launch_description_viewer.on_entity_process_started(action, process_name, pid)
55 |
56 | def on_process_exited(self, process_name, pid, action, return_code):
57 | if not self.closing:
58 | self.process_manager.on_process_exited(process_name, pid, action, return_code)
59 | self.launch_description_viewer.on_entity_process_exited(action, process_name, pid, return_code)
60 |
61 | def on_process_io(self, process_name, text):
62 | if not self.closing:
63 | self.process_manager.on_process_io(process_name, text)
64 |
65 | def on_describe_launch_entity(self, entity):
66 | if not self.closing:
67 | self.launch_description_viewer.on_describe_launch_entity(entity)
68 |
69 | def on_execution_complete(self, entity):
70 | if not self.closing:
71 | self.launch_description_viewer.on_execution_complete(entity)
72 |
73 | def on_close(self):
74 | self.closing = True
75 | super().on_close()
76 |
77 |
78 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [develop]
2 | script_dir=$base/lib/ros2launch_gui
3 | [install]
4 | install_scripts=$base/lib/ros2launch_gui
5 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import find_packages, setup
2 |
3 | package_name = 'ros2launch_gui'
4 |
5 | setup(
6 | name=package_name,
7 | version='0.0.0',
8 | packages=find_packages(exclude=['test']),
9 | data_files=[
10 | ('share/ament_index/resource_index/packages',
11 | ['resource/' + package_name]),
12 | ('share/' + package_name, ['package.xml']),
13 | ],
14 | install_requires=['setuptools'],
15 | zip_safe=True,
16 | maintainer='Roland Arsenault',
17 | maintainer_email='roland@ccom.unh.edu',
18 | description='Provides a gui option to the ros2 launch command',
19 | license='Apache-2.0',
20 | tests_require=['pytest'],
21 | entry_points={
22 | 'ros2launch.option': [
23 | 'gui = ros2launch_gui.option.gui:GuiOption',
24 | ],
25 | },
26 | )
27 |
--------------------------------------------------------------------------------
/test/test_ansi_to_html.py:
--------------------------------------------------------------------------------
1 | #import pytest
2 | from ros2launch_gui.qt.process_output_widget import ansi_to_html
3 |
4 | def test_plain_text_to_html():
5 | input = "my text"
6 | assert ansi_to_html(input) == input
7 |
8 | def test_info_text_to_html():
9 | input = "\033[0m[INFO] my text\033[0m"
10 | expected = '[INFO] my text'
11 | assert ansi_to_html(input) == expected
12 |
13 | def test_colored_text_to_html():
14 | input = "\033[31mmy text\033[0m"
15 | expected = 'my text'
16 | assert ansi_to_html(input) == expected
17 |
18 | def test_bold_colored_text_to_html():
19 | input = "\033[1;32mmy text\033[0m"
20 | expected = 'my text'
21 | assert ansi_to_html(input) == expected
22 |
23 | def test_underlined_colored_text_to_html():
24 | input = "\033[4;34mmy text\033[0m"
25 | expected = 'my text'
26 | assert ansi_to_html(input) == expected
27 |
28 | def test_italic_colored_text_to_html():
29 | input = "\033[3;34mmy text\033[0m"
30 | expected = 'my text'
31 | assert ansi_to_html(input) == expected
32 |
--------------------------------------------------------------------------------
/test/test_copyright.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015 Open Source Robotics Foundation, Inc.
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from ament_copyright.main import main
16 | import pytest
17 |
18 |
19 | # Remove the `skip` decorator once the source file(s) have a copyright header
20 | @pytest.mark.skip(reason='No copyright header has been placed in the generated source file.')
21 | @pytest.mark.copyright
22 | @pytest.mark.linter
23 | def test_copyright():
24 | rc = main(argv=['.', 'test'])
25 | assert rc == 0, 'Found errors'
26 |
--------------------------------------------------------------------------------
/test/test_flake8.py:
--------------------------------------------------------------------------------
1 | # Copyright 2017 Open Source Robotics Foundation, Inc.
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from ament_flake8.main import main_with_errors
16 | import pytest
17 |
18 |
19 | @pytest.mark.flake8
20 | @pytest.mark.linter
21 | def test_flake8():
22 | rc, errors = main_with_errors(argv=[])
23 | assert rc == 0, \
24 | 'Found %d code style errors / warnings:\n' % len(errors) + \
25 | '\n'.join(errors)
26 |
--------------------------------------------------------------------------------
/test/test_pep257.py:
--------------------------------------------------------------------------------
1 | # Copyright 2015 Open Source Robotics Foundation, Inc.
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from ament_pep257.main import main
16 | import pytest
17 |
18 |
19 | @pytest.mark.linter
20 | @pytest.mark.pep257
21 | def test_pep257():
22 | rc = main(argv=['.', 'test'])
23 | assert rc == 0, 'Found code style errors / warnings'
24 |
--------------------------------------------------------------------------------