FreeCAD

Форк
0
/
install_to_toolbar.py 
293 строки · 12.4 Кб
1
# SPDX-License-Identifier: LGPL-2.1-or-later
2
# ***************************************************************************
3
# *                                                                         *
4
# *   Copyright (c) 2022-2024 The FreeCAD Project Association AISBL         *
5
# *                                                                         *
6
# *   This file is part of FreeCAD.                                         *
7
# *                                                                         *
8
# *   FreeCAD is free software: you can redistribute it and/or modify it    *
9
# *   under the terms of the GNU Lesser General Public License as           *
10
# *   published by the Free Software Foundation, either version 2.1 of the  *
11
# *   License, or (at your option) any later version.                       *
12
# *                                                                         *
13
# *   FreeCAD is distributed in the hope that it will be useful, but        *
14
# *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
15
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      *
16
# *   Lesser General Public License for more details.                       *
17
# *                                                                         *
18
# *   You should have received a copy of the GNU Lesser General Public      *
19
# *   License along with FreeCAD. If not, see                               *
20
# *   <https://www.gnu.org/licenses/>.                                      *
21
# *                                                                         *
22
# ***************************************************************************
23

24
""" A collection of functions to handle installing a macro icon to the toolbar. """
25

26
import os
27

28
import FreeCAD
29
import FreeCADGui
30
from PySide import QtCore, QtWidgets
31
import Addon
32

33
translate = FreeCAD.Qt.translate
34

35

36
def ask_to_install_toolbar_button(repo: Addon) -> None:
37
    """Presents a dialog to the user asking if they want to install a toolbar button for
38
    a particular macro, and walks through that process if they agree to do so."""
39
    pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons")
40
    do_not_show_dialog = pref.GetBool("dontShowAddMacroButtonDialog", False)
41
    button_exists = check_for_button(repo)
42
    if not do_not_show_dialog and not button_exists:
43
        add_toolbar_button_dialog = FreeCADGui.PySideUic.loadUi(
44
            os.path.join(os.path.dirname(__file__), "add_toolbar_button_dialog.ui")
45
        )
46
        add_toolbar_button_dialog.buttonYes.clicked.connect(lambda: install_toolbar_button(repo))
47
        add_toolbar_button_dialog.buttonNever.clicked.connect(
48
            lambda: pref.SetBool("dontShowAddMacroButtonDialog", True)
49
        )
50
        add_toolbar_button_dialog.exec()
51

52

53
def check_for_button(repo: Addon) -> bool:
54
    """Returns True if a button already exists for this macro, or False if not."""
55
    command = FreeCADGui.Command.findCustomCommand(repo.macro.filename)
56
    if not command:
57
        return False
58
    custom_toolbars = FreeCAD.ParamGet("User parameter:BaseApp/Workbench/Global/Toolbar")
59
    toolbar_groups = custom_toolbars.GetGroups()
60
    for group in toolbar_groups:
61
        toolbar = custom_toolbars.GetGroup(group)
62
        if toolbar.GetString(command, "*") != "*":
63
            return True
64
    return False
65

66

67
def ask_for_toolbar(repo: Addon, custom_toolbars) -> object:
68
    """Determine what toolbar to add the icon to. The first time it is called it prompts the
69
    user to select or create a toolbar. After that, the prompt is optional and can be configured
70
    via a preference. Returns the pref group for the new toolbar."""
71
    pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons")
72

73
    # In this one spot, default True: if this is the first time we got to
74
    # this chunk of code, we are always going to ask.
75
    ask = pref.GetBool("alwaysAskForToolbar", True)
76

77
    if ask:
78
        select_toolbar_dialog = FreeCADGui.PySideUic.loadUi(
79
            os.path.join(os.path.dirname(__file__), "select_toolbar_dialog.ui")
80
        )
81

82
        select_toolbar_dialog.comboBox.clear()
83

84
        for group in custom_toolbars:
85
            ref = FreeCAD.ParamGet("User parameter:BaseApp/Workbench/Global/Toolbar/" + group)
86
            name = ref.GetString("Name", "")
87
            if name:
88
                select_toolbar_dialog.comboBox.addItem(name)
89
            else:
90
                FreeCAD.Console.PrintWarning(
91
                    f"Custom toolbar {group} does not have a Name element\n"
92
                )
93
        new_menubar_option_text = translate("AddonsInstaller", "Create new toolbar")
94
        select_toolbar_dialog.comboBox.addItem(new_menubar_option_text)
95

96
        result = select_toolbar_dialog.exec()
97
        if result == QtWidgets.QDialog.Accepted:
98
            selection = select_toolbar_dialog.comboBox.currentText()
99
            if select_toolbar_dialog.checkBox.checkState() == QtCore.Qt.Unchecked:
100
                pref.SetBool("alwaysAskForToolbar", False)
101
            else:
102
                pref.SetBool("alwaysAskForToolbar", True)
103
            if selection == new_menubar_option_text:
104
                return create_new_custom_toolbar()
105
            return get_toolbar_with_name(selection)
106
        return None
107

108
    # If none of the above code returned...
109
    custom_toolbar_name = pref.GetString("CustomToolbarName", "Auto-Created Macro Toolbar")
110
    toolbar = get_toolbar_with_name(custom_toolbar_name)
111
    if not toolbar:
112
        # They told us not to ask, but then the toolbar got deleted... ask anyway!
113
        ask = pref.RemBool("alwaysAskForToolbar")
114
        return ask_for_toolbar(repo, custom_toolbars)
115
    return toolbar
116

117

118
def get_toolbar_with_name(name: str) -> object:
119
    """Try to find a toolbar with a given name. Returns the preference group for the toolbar
120
    if found, or None if it does not exist."""
121
    top_group = FreeCAD.ParamGet("User parameter:BaseApp/Workbench/Global/Toolbar")
122
    custom_toolbars = top_group.GetGroups()
123
    for toolbar in custom_toolbars:
124
        group = FreeCAD.ParamGet("User parameter:BaseApp/Workbench/Global/Toolbar/" + toolbar)
125
        group_name = group.GetString("Name", "")
126
        if group_name == name:
127
            return group
128
    return None
129

130

131
def create_new_custom_toolbar() -> object:
132
    """Create a new custom toolbar and returns its preference group."""
133

134
    # We need two names: the name of the auto-created toolbar, as it will be displayed to the
135
    # user in various menus, and the underlying name of the toolbar group. Both must be
136
    # unique.
137

138
    # First, the displayed name
139
    custom_toolbar_name = "Auto-Created Macro Toolbar"
140
    top_group = FreeCAD.ParamGet("User parameter:BaseApp/Workbench/Global/Toolbar")
141
    custom_toolbars = top_group.GetGroups()
142
    name_taken = check_for_toolbar(custom_toolbar_name)
143
    if name_taken:
144
        i = 2  # Don't use (1), start at (2)
145
        while True:
146
            test_name = custom_toolbar_name + f" ({i})"
147
            if not check_for_toolbar(test_name):
148
                custom_toolbar_name = test_name
149
            i = i + 1
150

151
    # Second, the toolbar preference group name
152
    i = 1
153
    while True:
154
        new_group_name = "Custom_" + str(i)
155
        if new_group_name not in custom_toolbars:
156
            break
157
        i = i + 1
158

159
    custom_toolbar = FreeCAD.ParamGet(
160
        "User parameter:BaseApp/Workbench/Global/Toolbar/" + new_group_name
161
    )
162
    custom_toolbar.SetString("Name", custom_toolbar_name)
163
    custom_toolbar.SetBool("Active", True)
164
    return custom_toolbar
165

166

167
def check_for_toolbar(toolbar_name: str) -> bool:
168
    """Returns True if the toolbar exists, otherwise False"""
169
    return get_toolbar_with_name(toolbar_name) is not None
170

171

172
def install_toolbar_button(repo: Addon) -> None:
173
    """If the user has requested a toolbar button be installed, this function is called
174
    to continue the process and request any additional required information."""
175
    pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons")
176
    custom_toolbar_name = pref.GetString("CustomToolbarName", "Auto-Created Macro Toolbar")
177

178
    # Default to false here: if the variable hasn't been set, we don't assume
179
    # that we have to ask, because the simplest is to just create a new toolbar
180
    # and never ask at all.
181
    ask = pref.GetBool("alwaysAskForToolbar", False)
182

183
    # See if there is already a custom toolbar for macros:
184
    top_group = FreeCAD.ParamGet("User parameter:BaseApp/Workbench/Global/Toolbar")
185
    custom_toolbars = top_group.GetGroups()
186
    if custom_toolbars:
187
        # If there are already custom toolbars, see if one of them is the one we used last time
188
        found_toolbar = False
189
        for toolbar_name in custom_toolbars:
190
            test_toolbar = FreeCAD.ParamGet(
191
                "User parameter:BaseApp/Workbench/Global/Toolbar/" + toolbar_name
192
            )
193
            name = test_toolbar.GetString("Name", "")
194
            if name == custom_toolbar_name:
195
                custom_toolbar = test_toolbar
196
                found_toolbar = True
197
                break
198
        if ask or not found_toolbar:
199
            # We have to ask the user what to do...
200
            custom_toolbar = ask_for_toolbar(repo, custom_toolbars)
201
            if custom_toolbar:
202
                custom_toolbar_name = custom_toolbar.GetString("Name")
203
                pref.SetString("CustomToolbarName", custom_toolbar_name)
204
    else:
205
        # Create a custom toolbar
206
        custom_toolbar = FreeCAD.ParamGet(
207
            "User parameter:BaseApp/Workbench/Global/Toolbar/Custom_1"
208
        )
209
        custom_toolbar.SetString("Name", custom_toolbar_name)
210
        custom_toolbar.SetBool("Active", True)
211

212
    if custom_toolbar:
213
        install_macro_to_toolbar(repo, custom_toolbar)
214
    else:
215
        FreeCAD.Console.PrintMessage("In the end, no custom toolbar was set, bailing out\n")
216

217

218
def find_installed_icon(repo: Addon) -> str:
219
    """The icon the macro specifies is usually not the actual installed icon, but rather a cached
220
    copy. This function looks for a file with the same name located in the macro installation
221
    path."""
222
    macro_repo_dir = FreeCAD.getUserMacroDir(True)
223
    if repo.macro.icon:
224
        basename = os.path.basename(repo.macro.icon)
225
        # Simple case first: the file is just in the macro directory...
226
        if os.path.isfile(os.path.join(macro_repo_dir, basename)):
227
            return os.path.join(macro_repo_dir, basename)
228
        # More complex: search for it
229
        for root, dirs, files in os.walk(macro_repo_dir):
230
            for name in files:
231
                if name == basename:
232
                    return os.path.join(root, name)
233
        return ""
234
    elif repo.macro.xpm:
235
        return os.path.normpath(os.path.join(macro_repo_dir, repo.macro.name + "_icon.xpm"))
236
    else:
237
        return ""
238

239

240
def install_macro_to_toolbar(repo: Addon, toolbar: object) -> None:
241
    """Adds an icon for the given macro to the given toolbar."""
242
    menuText = repo.display_name
243
    tooltipText = f"<b>{repo.display_name}</b>"
244
    if repo.macro.comment:
245
        tooltipText += f"<br/><p>{repo.macro.comment}</p>"
246
        whatsThisText = repo.macro.comment
247
    else:
248
        whatsThisText = translate(
249
            "AddonsInstaller", "A macro installed with the FreeCAD Addon Manager"
250
        )
251
    statustipText = (
252
        translate("AddonsInstaller", "Run", "Indicates a macro that can be 'run'")
253
        + " "
254
        + repo.display_name
255
    )
256
    pixmapText = find_installed_icon(repo)
257

258
    # Add this command to that toolbar
259
    command_name = FreeCADGui.Command.createCustomCommand(
260
        repo.macro.filename,
261
        menuText,
262
        tooltipText,
263
        whatsThisText,
264
        statustipText,
265
        pixmapText,
266
    )
267
    toolbar.SetString(command_name, "FreeCAD")
268

269
    # Force the toolbars to be recreated
270
    wb = FreeCADGui.activeWorkbench()
271
    wb.reloadActive()
272

273

274
def remove_custom_toolbar_button(repo: Addon) -> None:
275
    """If this repo contains a macro, look through the custom commands and
276
    see if one is set up for this macro. If so, remove it, including any
277
    toolbar entries."""
278

279
    command = FreeCADGui.Command.findCustomCommand(repo.macro.filename)
280
    if not command:
281
        return
282
    custom_toolbars = FreeCAD.ParamGet("User parameter:BaseApp/Workbench/Global/Toolbar")
283
    toolbar_groups = custom_toolbars.GetGroups()
284
    for group in toolbar_groups:
285
        toolbar = custom_toolbars.GetGroup(group)
286
        if toolbar.GetString(command, "*") != "*":
287
            toolbar.RemString(command)
288

289
    FreeCADGui.Command.removeCustomCommand(command)
290

291
    # Force the toolbars to be recreated
292
    wb = FreeCADGui.activeWorkbench()
293
    wb.reloadActive()
294

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.