1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
|
# (C) Copyright 2005-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
import sys
from pyface.tasks.i_editor_area_pane import IEditorAreaPane, MEditorAreaPane
from traits.api import (
Any,
Bool,
cached_property,
Callable,
Dict,
Instance,
List,
observe,
Property,
provides,
Str,
Tuple,
)
from pyface.qt import is_qt4, QtCore, QtGui, is_qt6, is_pyside
from pyface.action.api import Action, Group, MenuManager
from pyface.tasks.task_layout import PaneItem, Tabbed, Splitter
from pyface.mimedata import PyMimeData
from pyface.api import FileDialog
from pyface.constant import OK
from pyface.drop_handler import IDropHandler, BaseDropHandler, FileDropHandler
from .task_pane import TaskPane
# ----------------------------------------------------------------------------
# 'SplitEditorAreaPane' class.
# ----------------------------------------------------------------------------
@provides(IEditorAreaPane)
class SplitEditorAreaPane(TaskPane, MEditorAreaPane):
""" The toolkit-specific implementation of an SplitEditorAreaPane.
See the IEditorAreaPane interface for API documentation.
"""
# SplitEditorAreaPane interface -------------------------------------
# Currently active tabwidget
active_tabwidget = Instance(QtGui.QTabWidget)
# list of installed drop handlers
drop_handlers = List(IDropHandler)
# Additional callback functions. Few useful callbacks that can be included:
# 'new': new file action (takes no argument)
# 'open': open file action (takes file_path as single argument)
# 'open_dialog': show the open file dialog (responsibility of the callback,
# takes no argument), overrides 'open' callback
# They are used to create shortcut buttons for these actions in the empty
# pane that gets created when the user makes a split
callbacks = Dict({}, key=Str, value=Callable)
# The constructor of the empty widget which comes up when one creates a split
create_empty_widget = Callable
# Private interface ---------------------------------------------------
#: A list of connected Qt signals to be removed before destruction.
#: First item in the tuple is the Qt signal. The second item is the event
#: handler.
_connections_to_remove = List(Tuple(Any, Callable))
_private_drop_handlers = List(IDropHandler)
_all_drop_handlers = Property(
List(IDropHandler),
observe=["drop_handlers", "_private_drop_handlers"],
)
def __private_drop_handlers_default(self):
""" By default, two private drop handlers are installed:
1. For dropping of tabs from one pane to other
2. For dropping of supported files from file-browser pane or outside
the application
"""
return [
TabDropHandler(),
FileDropHandler(
extensions=self.file_drop_extensions,
open_file=lambda path: self.trait_set(file_dropped=path),
),
]
@cached_property
def _get__all_drop_handlers(self):
return self.drop_handlers + self._private_drop_handlers
def _create_empty_widget_default(self):
return lambda: self.active_tabwidget.create_empty_widget()
# ------------------------------------------------------------------------
# 'TaskPane' interface.
# ------------------------------------------------------------------------
def create(self, parent):
""" Create and set the toolkit-specific control that represents the
pane.
"""
# Create and configure the Editor Area Widget.
self.control = EditorAreaWidget(self, parent)
self.active_tabwidget = self.control.tabwidget()
# handle application level focus changes
QtGui.QApplication.instance().focusChanged.connect(self._focus_changed)
# set key bindings
self.set_key_bindings()
def destroy(self):
""" Destroy the toolkit-specific control that represents the pane.
"""
if self.control is not None:
# disconnect application level focus change signals first, else it gives
# weird runtime errors trying to access non-existent objects
QtGui.QApplication.instance().focusChanged.disconnect(
self._focus_changed
)
for editor in self.editors[:]:
self.remove_editor(editor)
while self._connections_to_remove:
signal, handler = self._connections_to_remove.pop()
signal.disconnect(handler)
# Remove reference to active tabwidget so that it can be deleted
# together with the main control
self.active_tabwidget = None
super().destroy()
# ------------------------------------------------------------------------
# 'IEditorAreaPane' interface.
# ------------------------------------------------------------------------
def activate_editor(self, editor):
""" Activates the specified editor in the pane.
"""
active_tabwidget = self._get_editor_tabwidget(editor)
active_tabwidget.setCurrentWidget(editor.control)
self.active_tabwidget = active_tabwidget
editor_widget = editor.control.parent()
editor_widget.setVisible(True)
editor_widget.raise_()
# Set focus on last active widget in editor if possible
if editor.control.focusWidget():
editor.control.focusWidget().setFocus()
else:
editor.control.setFocus()
# Set active_editor at the end of the method so that the notification
# occurs when everything is ready.
self.active_editor = editor
def add_editor(self, editor):
""" Adds an editor to the active_tabwidget
"""
editor.editor_area = self
editor.create(self.active_tabwidget)
index = self.active_tabwidget.addTab(
editor.control, self._get_label(editor)
)
# There seem to be a bug in pyside or qt, where the index is set to 1
# when you create the first tab. This is a hack to fix it.
if self.active_tabwidget.count() == 1:
index = 0
self.active_tabwidget.setTabToolTip(index, editor.tooltip)
self.editors.append(editor)
def remove_editor(self, editor):
""" Removes an editor from the associated tabwidget
"""
tabwidget, index = self._get_editor_tabwidget_index(editor)
tabwidget.removeTab(index)
self.editors.remove(editor)
editor.destroy()
editor.editor_area = None
if not self.editors:
self.active_editor = None
# ------------------------------------------------------------------------
# 'IAdvancedEditorAreaPane' interface.
# ------------------------------------------------------------------------
def get_layout(self):
""" Returns a LayoutItem that reflects the current state of the
tabwidgets in the split framework.
"""
return self.control.get_layout()
def set_layout(self, layout):
""" Applies the given LayoutItem.
"""
self.control.set_layout(layout)
# ------------------------------------------------------------------------
# 'SplitEditorAreaPane' interface.
# ------------------------------------------------------------------------
def get_context_menu(self, pos):
""" Return a context menu containing split/collapse actions.
Parameters
----------
pos : QtCore.QPoint
Mouse position in global coordinates for which the context menu was
requested.
Returns
-------
menu : pyface.action.menu_manager.MenuManager or None
Context menu, or None if the given position doesn't correspond
to any of the tab widgets.
"""
menu = MenuManager()
for tabwidget in self.tabwidgets():
widget_pos = tabwidget.mapFromGlobal(pos)
if tabwidget.rect().contains(widget_pos):
splitter = tabwidget.parent()
break
else:
# no split/collapse context menu for positions outside any
# tabwidget region
return None
# add split actions (only show for non-empty tabwidgets)
if not splitter.is_empty():
split_group = Group(
Action(
id="split_hor",
name="Create new pane to the right",
on_perform=lambda: splitter.split(
orientation=QtCore.Qt.Orientation.Horizontal
),
),
Action(
id="split_ver",
name="Create new pane below",
on_perform=lambda: splitter.split(
orientation=QtCore.Qt.Orientation.Vertical
),
),
id="split",
)
menu.append(split_group)
# add collapse action (only show for collapsible splitters)
if splitter.is_collapsible():
if splitter is splitter.parent().leftchild:
if splitter.parent().orientation() == QtCore.Qt.Orientation.Horizontal:
text = "Merge with right pane"
else:
text = "Merge with bottom pane"
else:
if splitter.parent().orientation() == QtCore.Qt.Orientation.Horizontal:
text = "Merge with left pane"
else:
text = "Merge with top pane"
collapse_group = Group(
Action(
id="merge",
name=text,
on_perform=lambda: splitter.collapse(),
),
id="collapse",
)
menu.append(collapse_group)
return menu
# ------------------------------------------------------------------------
# Protected interface.
# ------------------------------------------------------------------------
def _get_label(self, editor):
""" Return a tab label for an editor.
"""
try:
label = editor.name
if editor.dirty:
label = "*" + label
except AttributeError:
label = ""
return label
def _get_editor(self, editor_widget):
""" Returns the editor corresponding to editor_widget
"""
for editor in self.editors:
if getattr(editor, "control", None) is editor_widget:
return editor
return None
def set_key_bindings(self):
""" Set keyboard shortcuts for tabbed navigation
"""
# Add shortcuts for scrolling through tabs.
if sys.platform == "darwin":
next_seq = "Ctrl+}"
prev_seq = "Ctrl+{"
else:
next_seq = "Ctrl+PgDown"
prev_seq = "Ctrl+PgUp"
shortcut = QtGui.QShortcut(QtGui.QKeySequence(next_seq), self.control)
shortcut.activated.connect(self._next_tab)
self._connections_to_remove.append(
(shortcut.activated, self._next_tab)
)
shortcut = QtGui.QShortcut(QtGui.QKeySequence(prev_seq), self.control)
shortcut.activated.connect(self._previous_tab)
self._connections_to_remove.append(
(shortcut.activated, self._previous_tab)
)
# Add shortcuts for switching to a specific tab.
mod = "Ctrl+" if sys.platform == "darwin" else "Alt+"
mapper = QtCore.QSignalMapper(self.control)
if is_pyside and is_qt6:
mapper.mappedInt.connect(self._activate_tab)
self._connections_to_remove.append(
(mapper.mappedInt, self._activate_tab)
)
else:
mapper.mapped.connect(self._activate_tab)
self._connections_to_remove.append(
(mapper.mapped, self._activate_tab)
)
for i in range(1, 10):
sequence = QtGui.QKeySequence(mod + str(i))
shortcut = QtGui.QShortcut(sequence, self.control)
shortcut.activated.connect(mapper.map)
self._connections_to_remove.append(
(shortcut.activated, mapper.map)
)
mapper.setMapping(shortcut, i - 1)
def _activate_tab(self, index):
""" Activates the tab with the specified index, if there is one.
"""
self.active_tabwidget.setCurrentIndex(index)
current_widget = self.active_tabwidget.currentWidget()
for editor in self.editors:
if current_widget == editor.control:
self.activate_editor(editor)
def _next_tab(self):
""" Activate the tab after the currently active tab.
"""
index = self.active_tabwidget.currentIndex()
new_index = (
index + 1 if index < self.active_tabwidget.count() - 1 else 0
)
self._activate_tab(new_index)
def _previous_tab(self):
""" Activate the tab before the currently active tab.
"""
index = self.active_tabwidget.currentIndex()
new_index = (
index - 1 if index > 0 else self.active_tabwidget.count() - 1
)
self._activate_tab(new_index)
def tabwidgets(self):
""" Returns the list of tabwidgets associated with the current editor
area.
"""
return self.control.tabwidgets()
def _get_editor_tabwidget(self, editor):
""" Given an editor, return its tabwidget. """
return editor.control.parent().parent()
def _get_editor_tabwidget_index(self, editor):
""" Given an editor, return its tabwidget and index. """
tabwidget = self._get_editor_tabwidget(editor)
index = tabwidget.indexOf(editor.control)
return tabwidget, index
# Trait change handlers ------------------------------------------------
@observe("editors:items:[dirty, name]")
def _update_label(self, event):
editor = event.object
tabwidget, index = self._get_editor_tabwidget_index(editor)
tabwidget.setTabText(index, self._get_label(editor))
@observe("editors:items:tooltip")
def _update_tooltip(self, event):
editor = event.object
tabwidget, index = self._get_editor_tabwidget_index(editor)
tabwidget.setTabToolTip(index, editor.tooltip)
# Signal handlers -----------------------------------------------------#
def _find_ancestor_draggable_tab_widget(self, control):
""" Find the draggable tab widget to which a widget belongs. """
while not isinstance(control, DraggableTabWidget):
control = control.parent()
return control
def _focus_changed(self, old, new):
"""Set the active tabwidget after an application-level change in focus.
"""
if new is not None:
if isinstance(new, DraggableTabWidget):
if new.editor_area == self:
self.active_tabwidget = new
elif isinstance(new, QtGui.QTabBar):
if self.control.isAncestorOf(new):
self.active_tabwidget = self._find_ancestor_draggable_tab_widget(
new
)
else:
# Check if any of the editor widgets have focus.
# If so, make it active.
for editor in self.editors:
control = editor.control
if control is not None and control.isAncestorOf(new):
active_tabwidget = self._find_ancestor_draggable_tab_widget(
control
)
active_tabwidget.setCurrentWidget(control)
self.active_tabwidget = active_tabwidget
break
def _active_tabwidget_changed(self, new):
"""Set the active editor whenever the active tabwidget updates.
"""
if new is None or new.parent().is_empty():
active_editor = None
else:
active_editor = self._get_editor(new.currentWidget())
self.active_editor = active_editor
# ----------------------------------------------------------------------------
# Auxiliary classes.
# ----------------------------------------------------------------------------
class EditorAreaWidget(QtGui.QSplitter):
""" Container widget to hold a QTabWidget which are separated by other
QTabWidgets via splitters.
An EditorAreaWidget is essentially a Node object in the editor area layout
tree.
"""
def __init__(self, editor_area, parent=None, tabwidget=None):
""" Creates an EditorAreaWidget object.
editor_area : global SplitEditorAreaPane
parent : parent splitter
tabwidget : tabwidget object contained by this splitter
"""
super().__init__(parent=parent)
self.editor_area = editor_area
if not tabwidget:
tabwidget = DraggableTabWidget(
editor_area=self.editor_area, parent=self
)
# add the tabwidget to the splitter
self.addWidget(tabwidget)
# showing the tabwidget after reparenting
tabwidget.show()
# Initializes left and right children to None (since no initial splitter
# children are present)
self.leftchild = None
self.rightchild = None
def get_layout(self):
""" Returns a LayoutItem that reflects the layout of the current
splitter.
"""
ORIENTATION_MAP = {
QtCore.Qt.Orientation.Horizontal: "horizontal",
QtCore.Qt.Orientation.Vertical: "vertical",
}
# obtain layout based on children layouts
if not self.is_leaf():
layout = Splitter(
self.leftchild.get_layout(),
self.rightchild.get_layout(),
orientation=ORIENTATION_MAP[self.orientation()],
)
# obtain the Tabbed layout
else:
if self.is_empty():
layout = Tabbed(
PaneItem(id=-1, width=self.width(), height=self.height()),
active_tab=0,
)
else:
items = []
for i in range(self.tabwidget().count()):
widget = self.tabwidget().widget(i)
# mark identification for empty_widget
editor = self.editor_area._get_editor(widget)
item_id = self.editor_area.editors.index(editor)
item_width = self.width()
item_height = self.height()
items.append(
PaneItem(
id=item_id, width=item_width, height=item_height
)
)
layout = Tabbed(
*items, active_tab=self.tabwidget().currentIndex()
)
return layout
def set_layout(self, layout):
""" Applies the given LayoutItem to current splitter.
"""
ORIENTATION_MAP = {
"horizontal": QtCore.Qt.Orientation.Horizontal,
"vertical": QtCore.Qt.Orientation.Vertical,
}
# if not a leaf splitter
if isinstance(layout, Splitter):
self.split(orientation=ORIENTATION_MAP[layout.orientation])
self.leftchild.set_layout(layout=layout.items[0])
self.rightchild.set_layout(layout=layout.items[1])
# setting sizes of children along splitter direction
if layout.orientation == "horizontal":
sizes = [self.leftchild.width(), self.rightchild.width()]
self.resize(sum(sizes), self.leftchild.height())
else:
sizes = [self.leftchild.height(), self.rightchild.height()]
self.resize(self.leftchild.width(), sum(sizes))
self.setSizes(sizes)
# if it is a leaf splitter
elif isinstance(layout, Tabbed):
# don't clear-out empty_widget's information if all it contains is an
# empty_widget
if not self.is_empty():
self.tabwidget().clear()
for item in layout.items:
if not item.id == -1:
editor = self.editor_area.editors[item.id]
self.tabwidget().addTab(
editor.control, self.editor_area._get_label(editor)
)
self.resize(item.width, item.height)
self.tabwidget().setCurrentIndex(layout.active_tab)
def tabwidget(self):
""" Obtain the tabwidget associated with current EditorAreaWidget
(returns None for non-leaf splitters)
"""
for child in self.children():
if isinstance(child, QtGui.QTabWidget):
return child
return None
def tabwidgets(self):
""" Return a list of tabwidgets associated with current splitter or
any of its descendants.
"""
tabwidgets = []
if self.is_leaf():
tabwidgets.append(self.tabwidget())
else:
tabwidgets.extend(self.leftchild.tabwidgets())
tabwidgets.extend(self.rightchild.tabwidgets())
return tabwidgets
def sibling(self):
""" Returns another child of its parent. Returns None if it can't find
any sibling.
"""
parent = self.parent()
if self.is_root():
return None
if self is parent.leftchild:
return parent.rightchild
elif self is parent.rightchild:
return parent.leftchild
def is_root(self):
""" Returns True if the current EditorAreaWidget is the root widget.
"""
parent = self.parent()
if isinstance(parent, EditorAreaWidget):
return False
else:
return True
def is_leaf(self):
""" Returns True if the current EditorAreaWidget is a leaf, i.e., it has
a tabwidget as one of it's immediate child.
"""
# a leaf has it's leftchild and rightchild None
if not self.leftchild and not self.rightchild:
return True
return False
def is_empty(self):
""" Returns True if the current splitter's tabwidget doesn't contain any
tab.
"""
return bool(self.tabwidget().empty_widget)
def is_collapsible(self):
""" Returns True if the current splitter can be collapsed to its sibling,
i.e. if it is (a) either empty, or (b) it has a sibling which is a leaf.
"""
if self.is_root():
return False
if self.is_empty():
return True
sibling = self.sibling()
if sibling.is_leaf():
return True
else:
return False
def split(self, orientation=QtCore.Qt.Orientation.Horizontal):
""" Split the current splitter into two children splitters. The current
splitter's tabwidget is moved to the left child while a new empty
tabwidget is added to the right child.
orientation : whether to split horizontally or vertically
"""
# set splitter orientation
self.setOrientation(orientation)
orig_size = self.sizes()[0]
# create new children
self.leftchild = EditorAreaWidget(
self.editor_area, parent=self, tabwidget=self.tabwidget()
)
self.rightchild = EditorAreaWidget(
self.editor_area, parent=self, tabwidget=None
)
# add newly generated children
self.addWidget(self.leftchild)
self.addWidget(self.rightchild)
# set equal sizes of splits
self.setSizes([orig_size // 2, orig_size // 2])
# make the rightchild's tabwidget active & show its empty widget
self.editor_area.active_tabwidget = self.rightchild.tabwidget()
def collapse(self):
""" Collapses the current splitter and its sibling splitter to their
parent splitter. Merges together the tabs of both's tabwidgets.
Does nothing if the current splitter is not collapsible.
"""
if not self.is_collapsible():
return
parent = self.parent()
sibling = self.sibling()
# this will happen only if self is empty, else it will not be
# collapsible at all
if sibling and (not sibling.is_leaf()):
parent.setOrientation(sibling.orientation())
# reparent sibling's children to parent
parent.addWidget(sibling.leftchild)
parent.addWidget(sibling.rightchild)
parent.leftchild = sibling.leftchild
parent.rightchild = sibling.rightchild
# blindly make the first tabwidget active as it is not clear which
# tabwidget should get focus now (FIXME??)
self.editor_area.active_tabwidget = parent.tabwidgets()[0]
self.setParent(None)
sibling.setParent(None)
return
# save original currentwidget to make active later
# (if self is empty, make the currentwidget of sibling active)
if not self.is_empty():
orig_currentWidget = self.tabwidget().currentWidget()
else:
orig_currentWidget = sibling.tabwidget().currentWidget()
left = parent.leftchild.tabwidget()
right = parent.rightchild.tabwidget()
target = DraggableTabWidget(
editor_area=self.editor_area, parent=parent
)
# add tabs of left and right tabwidgets to target
for source in (left, right):
# Note: addTab removes widgets from source tabwidget, so
# grabbing all the source widgets beforehand
# (not grabbing empty_widget)
widgets = [
source.widget(i)
for i in range(source.count())
if not source.widget(i) is source.empty_widget
]
for editor_widget in widgets:
editor = self.editor_area._get_editor(editor_widget)
target.addTab(
editor_widget, self.editor_area._get_label(editor)
)
# add target to parent
parent.addWidget(target)
# make target the new active tabwidget and make the original focused
# widget active in the target too
self.editor_area.active_tabwidget = target
target.setCurrentWidget(orig_currentWidget)
# remove parent's splitter children
parent.leftchild = None
parent.rightchild = None
self.setParent(None)
sibling.setParent(None)
class DraggableTabWidget(QtGui.QTabWidget):
""" Implements a QTabWidget with event filters for tab drag and drop
"""
def __init__(self, editor_area, parent):
"""
editor_area : global SplitEditorAreaPane
parent : parent of the tabwidget
"""
super().__init__(parent)
self.editor_area = editor_area
# configure QTabWidget
self.setTabBar(DraggableTabBar(editor_area=editor_area, parent=self))
self.setDocumentMode(True)
self.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus)
self.setFocusProxy(None)
self.setMovable(False) # handling move events myself
self.setTabsClosable(True)
self.setAutoFillBackground(True)
# set drop and context menu policies
self.setAcceptDrops(True)
self.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.DefaultContextMenu)
# connecting signals
self.tabCloseRequested.connect(self._close_requested)
self.currentChanged.connect(self._current_changed)
# shows the custom empty widget containing buttons for relevant actions
self.show_empty_widget()
def show_empty_widget(self):
""" Shows the empty widget (containing buttons to open new file, and
collapse the split).
"""
self.empty_widget = None
self.editor_area.active_tabwidget = self
# callback to editor_area's public `create_empty_widget` Callable trait
empty_widget = self.editor_area.create_empty_widget()
self.addTab(empty_widget, "")
self.empty_widget = empty_widget
self.setFocus()
# don't allow tab closing if empty widget comes up on a root tabwidget
if self.parent().is_root():
self.setTabsClosable(False)
self.setTabText(0, " ")
def hide_empty_widget(self):
""" Hides the empty widget (containing buttons to open new file, and
collapse the split) based on whether the tabwidget is empty or not.
"""
index = self.indexOf(self.empty_widget)
self.removeTab(index)
self.empty_widget.deleteLater()
self.empty_widget = None
self.setTabsClosable(True)
def create_empty_widget(self):
""" Creates the QFrame object to be shown when the current tabwidget is
empty.
"""
frame = QtGui.QFrame(parent=self)
frame.setFrameShape(QtGui.QFrame.Shape.StyledPanel)
layout = QtGui.QVBoxLayout(frame)
# Add new file button and open file button only if the `callbacks` trait
# of the editor_area has a callable for key `new` and key `open`
new_file_action = self.editor_area.callbacks.get("new", None)
open_file_action = self.editor_area.callbacks.get("open_dialog", None)
open_show_dialog = False
if open_file_action is None:
open_file_action = self.editor_area.callbacks.get("open", None)
open_show_dialog = True
if not (new_file_action and open_file_action):
return frame
layout.addStretch()
# generate new file button
newfile_btn = QtGui.QPushButton("Create a new file", parent=frame)
newfile_btn.clicked.connect(new_file_action)
layout.addWidget(newfile_btn, alignment=QtCore.Qt.AlignmentFlag.AlignHCenter)
# generate label
label = QtGui.QLabel(parent=frame)
label.setText(
"""<span style='font-size:14px; color:#999999'>
or
</span>"""
)
layout.addWidget(label, alignment=QtCore.Qt.AlignmentFlag.AlignHCenter)
# generate open button
open_btn = QtGui.QPushButton(
"Select files from your computer", parent=frame
)
def _open():
if open_show_dialog:
open_dlg = FileDialog(action="open")
open_dlg.open()
self.editor_area.active_tabwidget = self
if open_dlg.return_code == OK:
open_file_action(open_dlg.path)
else:
open_file_action()
open_btn.clicked.connect(_open)
layout.addWidget(open_btn, alignment=QtCore.Qt.AlignmentFlag.AlignHCenter)
# generate label
label = QtGui.QLabel(parent=frame)
label.setText(
"""<span style='font-size:14px; color:#999999'>
Tip: You can also drag and drop files/tabs here.
</span>"""
)
layout.addWidget(label, alignment=QtCore.Qt.AlignmentFlag.AlignHCenter)
layout.addStretch()
frame.setLayout(layout)
return frame
def get_names(self):
""" Utility function to return names of all the editors open in the
current tabwidget.
"""
names = []
for i in range(self.count()):
editor_widget = self.widget(i)
editor = self.editor_area._get_editor(editor_widget)
if editor:
names.append(editor.name)
return names
# Signal handlers ----------------------------------------------------
def _close_requested(self, index):
""" Re-implemented to close the editor when it's tab is closed
"""
widget = self.widget(index)
# if close requested on empty_widget, collapse the pane and return
if widget is self.empty_widget:
self.parent().collapse()
return
editor = self.editor_area._get_editor(widget)
editor.close()
def _current_changed(self, index):
"""Re-implemented to update active editor
"""
self.setCurrentIndex(index)
editor_widget = self.widget(index)
self.editor_area.active_editor = self.editor_area._get_editor(
editor_widget
)
def tabInserted(self, index):
""" Re-implemented to hide empty_widget when adding a new widget
"""
# sets tab tooltip only if a real editor was added (not an empty_widget)
editor = self.editor_area._get_editor(self.widget(index))
if editor:
self.setTabToolTip(index, editor.tooltip)
if self.empty_widget:
self.hide_empty_widget()
def tabRemoved(self, index):
""" Re-implemented to show empty_widget again if all tabs are removed
"""
if not self.count() and not self.empty_widget:
self.show_empty_widget()
## Event handlers -----------------------------------------------------#
def contextMenuEvent(self, event):
""" To show collapse context menu even on empty tabwidgets
Parameters
----------
event : QtGui.QContextMenuEvent
"""
local_pos = event.pos()
if self.empty_widget is not None or self.tabBar().rect().contains(
local_pos
):
# Only display if we are in the tab bar region or the whole area if
# we are displaying the default empty widget.
global_pos = self.mapToGlobal(local_pos)
menu = self.editor_area.get_context_menu(pos=global_pos)
if menu is not None:
qmenu = menu.create_menu(self)
if hasattr(qmenu, 'exec'):
qmenu.exec(global_pos)
else:
qmenu.exec_(global_pos)
def dragEnterEvent(self, event):
""" Re-implemented to highlight the tabwidget on drag enter
"""
for handler in self.editor_area._all_drop_handlers:
if handler.can_handle_drop(event, self):
self.editor_area.active_tabwidget = self
self.setBackgroundRole(QtGui.QPalette.ColorRole.Highlight)
event.acceptProposedAction()
return
super().dragEnterEvent(event)
def dropEvent(self, event):
""" Re-implemented to handle drop events
"""
for handler in self.editor_area._all_drop_handlers:
if handler.can_handle_drop(event, self):
handler.handle_drop(event, self)
self.setBackgroundRole(QtGui.QPalette.ColorRole.Window)
event.acceptProposedAction()
break
def dragLeaveEvent(self, event):
""" Clear widget highlight on leaving
"""
self.setBackgroundRole(QtGui.QPalette.ColorRole.Window)
return super().dragLeaveEvent(event)
class DraggableTabBar(QtGui.QTabBar):
""" Implements a QTabBar with event filters for tab drag
"""
def __init__(self, editor_area, parent):
super().__init__(parent)
self.editor_area = editor_area
self.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.DefaultContextMenu)
self.drag_obj = None
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.MouseButton.LeftButton:
index = self.tabAt(event.pos())
tabwidget = self.parent()
if tabwidget.widget(index) and (
not tabwidget.widget(index) == tabwidget.empty_widget
):
self.drag_obj = TabDragObject(
start_pos=event.pos(), tabBar=self
)
return super().mousePressEvent(event)
def mouseMoveEvent(self, event):
""" Re-implemented to create a drag event when the mouse is moved for a
sufficient distance while holding down mouse button.
"""
# go into the drag logic only if a drag_obj is active
if self.drag_obj:
# is the left mouse button still pressed?
if not event.buttons() == QtCore.Qt.MouseButton.LeftButton:
pass
# has the mouse been dragged for sufficient distance?
elif (
event.pos() - self.drag_obj.start_pos
).manhattanLength() < QtGui.QApplication.startDragDistance():
pass
# initiate drag
else:
drag = QtGui.QDrag(self.drag_obj.widget)
mimedata = PyMimeData(data=self.drag_obj, pickle=False)
drag.setPixmap(self.drag_obj.get_pixmap())
drag.setHotSpot(self.drag_obj.get_hotspot())
drag.setMimeData(mimedata)
if hasattr(drag, 'exec'):
drag.exec()
else:
drag.exec_()
self.drag_obj = None # deactivate the drag_obj again
return
return super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
""" Re-implemented to deactivate the drag when mouse button is
released
"""
self.drag_obj = None
return super().mouseReleaseEvent(event)
class TabDragObject(object):
""" Class to hold information related to tab dragging/dropping
"""
def __init__(self, start_pos, tabBar):
"""
Parameters
----------
start_pos : position in tabBar coordinates where the drag was started
tabBar : tabBar containing the tab on which drag started
"""
self.start_pos = start_pos
self.from_index = tabBar.tabAt(self.start_pos)
self.from_editor_area = tabBar.parent().editor_area
self.widget = tabBar.parent().widget(self.from_index)
self.from_tabbar = tabBar
def get_pixmap(self):
""" Returns the drag pixmap including page widget and tab rectangle.
"""
# instatiate the painter object with gray-color filled pixmap
tabBar = self.from_tabbar
tab_rect = tabBar.tabRect(self.from_index)
size = self.widget.rect().size()
result_pixmap = QtGui.QPixmap(size)
painter = QtGui.QStylePainter(result_pixmap, tabBar)
painter.fillRect(result_pixmap.rect(), QtCore.Qt.GlobalColor.lightGray)
painter.setCompositionMode(QtGui.QPainter.CompositionMode.CompositionMode_SourceOver)
optTabBase = QtGui.QStyleOptionTabBarBase()
optTabBase.initFrom(tabBar)
painter.drawPrimitive(QtGui.QStyle.PrimitiveElement.PE_FrameTabBarBase, optTabBase)
# region of active tab
if is_qt4: # grab wasn't introduced until Qt5
pixmap1 = QtGui.QPixmap.grabWidget(tabBar, tab_rect)
else:
pixmap1 = tabBar.grab(tab_rect)
painter.drawPixmap(0, 0, pixmap1)
# region of the page widget
if is_qt4:
pixmap2 = QtGui.QPixmap.grabWidget(self.widget)
else:
pixmap2 = self.widget.grab()
painter.drawPixmap(
0, tab_rect.height(), size.width(), size.height(), pixmap2
)
# finish painting
painter.end()
return result_pixmap
def get_hotspot(self):
return (
self.start_pos
- self.from_tabbar.tabRect(self.from_index).topLeft()
)
# ----------------------------------------------------------------------------
# Default drop handlers.
# ----------------------------------------------------------------------------
class TabDropHandler(BaseDropHandler):
""" Class to handle tab drop events
"""
# whether to allow dragging of tabs across different opened windows
allow_cross_window_drop = Bool(False)
def can_handle_drop(self, event, target):
if isinstance(event.mimeData(), PyMimeData) and isinstance(
event.mimeData().instance(), TabDragObject
):
if not self.allow_cross_window_drop:
drag_obj = event.mimeData().instance()
return drag_obj.from_editor_area == target.editor_area
else:
return True
return False
def handle_drop(self, event, target):
# get the drop object back
drag_obj = event.mimeData().instance()
# extract widget label
# (editor_area is common to both source and target in most cases but when
# the dragging happens across different windows, they are not, and hence it
# must be pulled in directly from the source)
editor = target.editor_area._get_editor(drag_obj.widget)
label = target.editor_area._get_label(editor)
# if drop occurs at a tab bar, insert the tab at that position
if not target.tabBar().tabAt(event.pos()) == -1:
index = target.tabBar().tabAt(event.pos())
target.insertTab(index, drag_obj.widget, label)
else:
# if the drag initiated from the same tabwidget, put the tab
# back at the original index
if target is drag_obj.from_tabbar.parent():
target.insertTab(drag_obj.from_index, drag_obj.widget, label)
# else, just add it at the end
else:
target.addTab(drag_obj.widget, label)
# make the dropped widget active
target.setCurrentWidget(drag_obj.widget)
|