Debian Codegraph @

pynicotine/gtkgui/widgets/popupmenu.py

raw
1 # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
2 # COPYRIGHT (C) 2016-2017 Michael Labouebe <[email protected]>
3 # COPYRIGHT (C) 2008-2009 quinox <[email protected]>
4 # COPYRIGHT (C) 2006-2009 daelstorm <[email protected]>
5 # COPYRIGHT (C) 2003-2004 Hyriand <[email protected]>
6 #
7 # GNU GENERAL PUBLIC LICENSE
8 # Version 3, 29 June 2007
9 #
10 # This program is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22
23 import os
24 import sys
25
26 from gi.repository import Gdk
27 from gi.repository import Gio
28 from gi.repository import GLib
29 from gi.repository import Gtk
30
31 from pynicotine.config import config
32 from pynicotine.core import core
33 from pynicotine.gtkgui.application import GTK_API_VERSION
34 from pynicotine.gtkgui.widgets import clipboard
35 from pynicotine.gtkgui.widgets.accelerator import Accelerator
36 from pynicotine.utils import TRANSLATE_PUNCTUATION
37
38
39 class PopupMenu:
40
41 popup_id_counter = 0
42
43 def __init__(self, application, parent=None, callback=None, connect_events=True):
44
45 self.model = Gio.Menu()
46 self.application = application
47 self.parent = parent
48 self.callback = callback
49
50 self.popup_menu = None
51 self.menu_button = None
52 self.gesture_click = None
53 self.gesture_press = None
54 self.valid_parent_widgets = Gtk.Box if GTK_API_VERSION >= 4 else (Gtk.Box, Gtk.EventBox)
55
56 if connect_events and parent:
57 self.connect_events(parent)
58
59 self.pending_items = []
60 self.actions = {}
61 self.items = {}
62 self.submenus = []
63
64 self.menu_section = None
65 self.editing = False
66
67 PopupMenu.popup_id_counter += 1
68 self.popup_id = PopupMenu.popup_id_counter
69
70 def destroy(self):
71 self.clear()
72 self.__dict__.clear()
73
74 def set_parent(self, parent):
75
76 if parent:
77 self.connect_events(parent)
78 self.parent = parent
79
80 def set_menu_button(self, button):
81
82 if self.menu_button is not None:
83 self.menu_button.set_menu_model(None)
84
85 self.menu_button = button
86
87 if button is None:
88 return
89
90 button.set_menu_model(self.model)
91
92 # Workaround for GTK bug where clicks stop working after clicking inside popover once
93 if GTK_API_VERSION >= 4 and os.environ.get("GDK_BACKEND") == "broadway":
94 popover = list(button)[-1]
95 popover.set_has_arrow(False)
96
97 def create_context_menu(self, parent):
98
99 if self.popup_menu:
100 return self.popup_menu
101
102 # Menus can only attach to a Gtk.Box/Gtk.EventBox parent, otherwise sizing and theming issues may occur
103 while not isinstance(parent, self.valid_parent_widgets):
104 parent = parent.get_parent()
105
106 if GTK_API_VERSION >= 4:
107 self.popup_menu = Gtk.PopoverMenu.new_from_model_full(self.model, # pylint: disable=no-member
108 Gtk.PopoverMenuFlags.NESTED)
109 self.popup_menu.set_parent(parent)
110 self.popup_menu.set_halign(Gtk.Align.START)
111 self.popup_menu.set_has_arrow(False)
112
113 # Workaround for wrong widget receiving focus after closing menu in GTK 4
114 self.popup_menu.connect("closed", lambda *_args: self.parent.child_focus(Gtk.DirectionType.TAB_FORWARD))
115 else:
116 self.popup_menu = Gtk.Menu.new_from_model(self.model)
117 self.popup_menu.attach_to_widget(parent)
118
119 return self.popup_menu
120
121 def _create_action(self, action_id, stateful=False):
122
123 state = GLib.Variant.new_boolean(False) if stateful else None
124 action = Gio.SimpleAction(name=action_id, state=state)
125
126 self.application.add_action(action)
127 return action
128
129 def _create_menu_item(self, item):
130 """
131 Types of menu items:
132 > - submenu
133 $ - boolean
134 O - choice
135 # - regular
136 = - hidden when disabled
137 ^ - hidden in macOS menu bar
138 """
139
140 submenu = False
141 boolean = False
142 choice = False
143 item_type = item[0][0]
144 label = item[0][1:]
145
146 if item_type == ">":
147 submenu = True
148
149 elif item_type == "$":
150 boolean = True
151
152 elif item_type == "O":
153 choice = True
154
155 if isinstance(item[1], str):
156 # Action name provided, don't create action here
157 action_id = item[1]
158 action = None
159
160 else:
161 normalized_label = "-".join(label.translate(TRANSLATE_PUNCTUATION).lower().split())
162 action_id = f"app.menu-{normalized_label}-{self.popup_id}"
163 action = self._create_action(action_id.replace("app.", "", 1), (boolean or choice))
164
165 if choice and len(item) > 2 and isinstance(item[2], str):
166 # Choice target name
167 action_id = f"{action_id}::{item[2]}"
168
169 menuitem = Gio.MenuItem.new(label, action_id)
170
171 if item_type == "=":
172 menuitem.set_attribute_value("hidden-when", GLib.Variant.new_string("action-disabled"))
173
174 elif item_type == "^":
175 menuitem.set_attribute_value("hidden-when", GLib.Variant.new_string("macos-menubar"))
176
177 if submenu:
178 menuitem.set_submenu(item[1].model)
179 self.submenus.append(item[1])
180
181 if GTK_API_VERSION == 3:
182 # Ideally, we wouldn't hide disabled submenus, but a GTK limitation forces us to
183 # https://discourse.gnome.org/t/question-how-do-i-disable-a-menubar-menu-in-gtk-is-it-even-possible/906/9
184 menuitem.set_attribute_value("hidden-when", GLib.Variant.new_string("action-disabled"))
185
186 elif action and item[1]:
187 # Callback
188 action_name = "change-state" if boolean or choice else "activate"
189 action.connect(action_name, *item[1:])
190
191 self.items[label] = menuitem
192
193 if action is not None:
194 self.actions[label] = action
195
196 return menuitem
197
198 def _add_item_to_section(self, item):
199
200 if not self.menu_section or not item[0]:
201 # Create new section
202
203 self.menu_section = Gio.Menu()
204 menuitem = Gio.MenuItem.new_section(label=None, section=self.menu_section)
205 self.model.append_item(menuitem)
206
207 if not item[0]:
208 return
209
210 menuitem = self._create_menu_item(item)
211 self.menu_section.append_item(menuitem)
212
213 def update_model(self):
214 """This function is called before a menu model needs to be manipulated
215 (enabling/disabling actions, showing a menu in the GUI)"""
216
217 if not self.pending_items:
218 return
219
220 for item in self.pending_items:
221 self._add_item_to_section(item)
222
223 self.pending_items.clear()
224
225 for submenu in self.submenus:
226 submenu.update_model()
227
228 def add_items(self, *items):
229 for item in items:
230 self.pending_items.append(item)
231
232 def clear(self):
233
234 for submenu in self.submenus:
235 # Ensure we remove all submenu actions
236 submenu.clear()
237
238 self.submenus.clear()
239 self.model.remove_all()
240
241 for action in self.actions.values():
242 self.application.remove_action(action.get_name())
243
244 self.actions.clear()
245 self.items.clear()
246
247 self.menu_section = None
248
249 def popup(self, pos_x, pos_y, controller=None, menu=None):
250
251 if menu is None:
252 menu = self.create_context_menu(self.parent)
253
254 if GTK_API_VERSION >= 4:
255 if not pos_x and not pos_y:
256 pos_x = pos_y = 0
257
258 rectangle = Gdk.Rectangle()
259 rectangle.x = pos_x
260 rectangle.y = pos_y
261
262 # Width/height 4 instead of 1 to work around this GTK bug in most cases:
263 # https://gitlab.gnome.org/GNOME/gtk/-/issues/5712
264 rectangle.width = rectangle.height = 4
265
266 menu.set_pointing_to(rectangle)
267 menu.popup()
268 return
269
270 event = None
271
272 if controller is not None:
273 sequence = controller.get_current_sequence()
274
275 if sequence is not None:
276 event = controller.get_last_event(sequence)
277
278 menu.popup_at_pointer(event)
279
280 # Events #
281
282 def _callback(self, controller=None, pos_x=None, pos_y=None):
283
284 menu = None
285 menu_model = self
286 callback = self.callback
287 self.update_model()
288
289 if isinstance(self.parent, Gtk.TreeView):
290 if pos_x and pos_y:
291 from pynicotine.gtkgui.widgets.treeview import set_treeview_selected_row
292
293 bin_x, bin_y = self.parent.convert_widget_to_bin_window_coords(pos_x, pos_y)
294 set_treeview_selected_row(self.parent, bin_x, bin_y)
295
296 if not self.parent.get_path_at_pos(bin_x, bin_y):
297 # Special case for column header menu
298
299 menu_model = self.parent.column_menu
300 menu = menu_model.create_context_menu(menu_model.parent)
301 callback = menu_model.callback
302
303 elif not self.parent.get_selection().count_selected_rows():
304 # No rows selected, don't show menu
305 return False
306
307 if callback is not None:
308 callback(menu_model, self.parent)
309
310 self.popup(pos_x, pos_y, controller, menu=menu)
311 return True
312
313 def _callback_click_gtk4(self, controller, _num_p, pos_x, pos_y):
314 return self._callback(controller, pos_x, pos_y)
315
316 def _callback_click_gtk4_darwin(self, controller, _num_p, pos_x, pos_y):
317
318 try:
319 event = controller.get_last_event()
320 except TypeError:
321 # PyGObject <3.48.0
322 return False
323
324 if event.triggers_context_menu():
325 return self._callback(controller, pos_x, pos_y)
326
327 return False
328
329 def _callback_click_gtk3(self, controller, _num_p, pos_x, pos_y):
330
331 sequence = controller.get_current_sequence()
332
333 if sequence is not None:
334 event = controller.get_last_event(sequence)
335 show_context_menu = event.triggers_context_menu()
336 else:
337 # Workaround for GTK 3.22.30
338 show_context_menu = (controller.get_current_button() == Gdk.BUTTON_SECONDARY)
339
340 if show_context_menu:
341 return self._callback(controller, pos_x, pos_y)
342
343 return False
344
345 def _callback_menu(self, *_args):
346 return self._callback()
347
348 def connect_events(self, parent):
349
350 if GTK_API_VERSION >= 4:
351 self.gesture_click = Gtk.GestureClick()
352 self.gesture_click.set_button(Gdk.BUTTON_SECONDARY)
353 self.gesture_click.connect("pressed", self._callback_click_gtk4)
354 parent.add_controller(self.gesture_click)
355
356 self.gesture_press = Gtk.GestureLongPress()
357 parent.add_controller(self.gesture_press)
358
359 Accelerator("<Shift>F10", parent, self._callback_menu)
360
361 if sys.platform == "darwin":
362 gesture_click_darwin = Gtk.GestureClick()
363 parent.add_controller(gesture_click_darwin)
364
365 gesture_click_darwin.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
366 gesture_click_darwin.connect("pressed", self._callback_click_gtk4_darwin)
367
368 else:
369 self.gesture_click = Gtk.GestureMultiPress(widget=parent)
370 self.gesture_click.set_button(0)
371 self.gesture_click.connect("pressed", self._callback_click_gtk3)
372
373 self.gesture_press = Gtk.GestureLongPress(widget=parent)
374
375 # Shift+F10
376 parent.connect("popup-menu", self._callback_menu)
377
378 self.gesture_click.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
379
380 self.gesture_press.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
381 self.gesture_press.set_touch_only(True)
382 self.gesture_press.connect("pressed", self._callback)
383
384
385 class FilePopupMenu(PopupMenu):
386
387 def __init__(self, application, parent=None, callback=None, connect_events=True):
388
389 super().__init__(application=application, parent=parent, callback=callback,
390 connect_events=connect_events)
391
392 self._setup_file_menu()
393
394 def _setup_file_menu(self):
395
396 self.add_items(
397 ("#" + "selected_files", None),
398 ("", None)
399 )
400
401 def set_num_selected_files(self, num_files):
402
403 self.actions["selected_files"].set_enabled(False)
404 self.items["selected_files"].set_label(_("%s File(s) Selected") % num_files)
405 self.model.remove(0)
406 self.model.prepend_item(self.items["selected_files"])
407
408
409 class UserPopupMenu(PopupMenu):
410
411 def __init__(self, application, parent=None, callback=None, connect_events=True, username=None,
412 tab_name=None):
413
414 super().__init__(application=application, parent=parent, callback=callback,
415 connect_events=connect_events)
416
417 self.username = username
418 self.tab_name = tab_name
419 self.popup_menu_private_rooms = None
420
421 if tab_name != "private_rooms":
422 self.popup_menu_private_rooms = UserPopupMenu(self.application, username=username, tab_name="private_rooms")
423 self.setup_user_menu(username)
424
425 def setup_user_menu(self, username):
426
427 self.set_user(username)
428
429 self.add_items(
430 ("#" + "username", self.on_copy_user),
431 ("", None)
432 )
433
434 if self.tab_name != "userinfo":
435 self.add_items(("#" + _("View User _Profile"), self.on_user_profile))
436
437 if self.tab_name != "privatechat":
438 self.add_items(("#" + _("_Send Message"), self.on_send_message))
439
440 if self.tab_name != "userbrowse":
441 self.add_items(("#" + _("_Browse Files"), self.on_browse_user))
442
443 if self.tab_name != "userlist":
444 self.add_items(("$" + _("_Add Buddy"), self.on_add_to_list))
445
446 self.add_items(
447 ("", None),
448 ("$" + _("Ban User"), self.on_ban_user),
449 ("$" + _("Ignore User"), self.on_ignore_user),
450 ("", None),
451 ("$" + _("Ban IP Address"), self.on_ban_ip),
452 ("$" + _("Ignore IP Address"), self.on_ignore_ip),
453 ("#" + _("Show IP A_ddress"), self.on_show_ip_address),
454 ("", None),
455 (">" + _("Private Rooms"), self.popup_menu_private_rooms)
456 )
457
458 def update_username_item(self):
459
460 if not self.username:
461 return
462
463 user_item = self.items.get("username")
464
465 if not user_item:
466 return
467
468 user_item.set_label(self.username.replace("_", "__")) # Escape underscores to disable mnemonics
469 self.model.remove(0)
470 self.model.prepend_item(user_item)
471
472 def set_user(self, username):
473
474 if username == self.username:
475 return
476
477 self.username = username
478 self.update_username_item()
479
480 if self.popup_menu_private_rooms is not None:
481 self.popup_menu_private_rooms.set_user(self.username)
482
483 def toggle_user_items(self):
484
485 self.editing = True
486
487 local_username = core.users.login_username or config.sections["server"]["login"]
488 add_to_list = _("_Add Buddy")
489
490 if add_to_list in self.actions:
491 self.actions[add_to_list].set_state(GLib.Variant.new_boolean(self.username in core.buddies.users))
492
493 for action_id, value in (
494 (_("Ban User"), core.network_filter.is_user_banned(self.username)),
495 (_("Ignore User"), core.network_filter.is_user_ignored(self.username)),
496 (_("Ban IP Address"), core.network_filter.is_user_ip_banned(self.username)),
497 (_("Ignore IP Address"), core.network_filter.is_user_ip_ignored(self.username))
498 ):
499 # Disable menu item if it's our own username and we haven't banned ourselves before
500 self.actions[action_id].set_enabled(GLib.Variant.new_boolean(self.username != local_username or value))
501 self.actions[action_id].set_state(GLib.Variant.new_boolean(value))
502
503 self.popup_menu_private_rooms.populate_private_rooms()
504 self.popup_menu_private_rooms.update_model()
505
506 self.actions[_("Private Rooms")].set_enabled(bool(self.popup_menu_private_rooms.items))
507 self.editing = False
508
509 def populate_private_rooms(self):
510
511 self.clear()
512
513 for room, data in core.chatrooms.private_rooms.items():
514 is_owned = core.chatrooms.is_private_room_owned(room)
515 is_operator = core.chatrooms.is_private_room_operator(room)
516
517 if not is_owned and not is_operator:
518 continue
519
520 if self.username == data.owner:
521 continue
522
523 is_user_member = (self.username in data.members)
524 is_user_operator = (self.username in data.operators)
525
526 if not is_user_operator:
527 if is_user_member:
528 self.add_items(
529 ("#" + _("Remove from Private Room %s") % room, self.on_private_room_remove_user, room))
530 else:
531 self.add_items(
532 ("#" + _("Add to Private Room %s") % room, self.on_private_room_add_user, room))
533
534 if not is_owned:
535 continue
536
537 if is_user_operator:
538 self.add_items(
539 ("#" + _("Remove as Operator of %s") % room, self.on_private_room_remove_operator, room))
540
541 elif is_user_member:
542 self.add_items(
543 ("#" + _("Add as Operator of %s") % room, self.on_private_room_add_operator, room))
544
545 self.add_items(("", None))
546
547 def update_model(self):
548 super().update_model()
549 self.update_username_item()
550
551 # Events #
552
553 def on_search_user(self, *_args):
554
555 self.application.window.lookup_action("search-mode").change_state(GLib.Variant.new_string("user"))
556 self.application.window.user_search_entry.set_text(self.username)
557 self.application.window.change_main_page(self.application.window.search_page)
558 GLib.idle_add(lambda: self.application.window.search_entry.grab_focus() == -1, priority=GLib.PRIORITY_HIGH_IDLE)
559
560 def on_send_message(self, *_args):
561 core.privatechat.show_user(self.username)
562
563 def on_show_ip_address(self, *_args):
564 core.users.request_ip_address(self.username, notify=True)
565
566 def on_user_profile(self, *_args):
567 core.userinfo.show_user(self.username)
568
569 def on_browse_user(self, *_args):
570 core.userbrowse.browse_user(self.username)
571
572 def on_private_room_add_user(self, _action, _parameter, room):
573 core.chatrooms.add_user_to_private_room(room, self.username)
574
575 def on_private_room_remove_user(self, _action, _parameter, room):
576 core.chatrooms.remove_user_from_private_room(room, self.username)
577
578 def on_private_room_add_operator(self, _action, _parameter, room):
579 core.chatrooms.add_operator_to_private_room(room, self.username)
580
581 def on_private_room_remove_operator(self, _action, _parameter, room):
582 core.chatrooms.remove_operator_from_private_room(room, self.username)
583
584 def on_add_to_list(self, action, state):
585
586 if self.editing:
587 return
588
589 if state.get_boolean():
590 core.buddies.add_buddy(self.username)
591 else:
592 core.buddies.remove_buddy(self.username)
593
594 action.set_state(state)
595
596 def on_ban_user(self, action, state):
597
598 if self.editing:
599 return
600
601 if state.get_boolean():
602 core.network_filter.ban_user(self.username)
603 else:
604 core.network_filter.unban_user(self.username)
605
606 action.set_state(state)
607
608 def on_ban_ip(self, action, state):
609
610 if self.editing:
611 return
612
613 if state.get_boolean():
614 core.network_filter.ban_user_ip(self.username)
615 else:
616 core.network_filter.unban_user_ip(self.username)
617
618 action.set_state(state)
619
620 def on_ignore_ip(self, action, state):
621
622 if self.editing:
623 return
624
625 if state.get_boolean():
626 core.network_filter.ignore_user_ip(self.username)
627 else:
628 core.network_filter.unignore_user_ip(self.username)
629
630 action.set_state(state)
631
632 def on_ignore_user(self, action, state):
633
634 if self.editing:
635 return
636
637 if state.get_boolean():
638 core.network_filter.ignore_user(self.username)
639 else:
640 core.network_filter.unignore_user(self.username)
641
642 action.set_state(state)
643
644 def on_copy_user(self, *_args):
645 clipboard.copy_text(self.username)