dag: add word wrapping to the diff widget
[git-cola.git] / cola / qtutils.py
blobacceea1e93f02bca110b658fd3c2c5d30a6a1cf1
1 """Miscellaneous Qt utility functions."""
2 from __future__ import absolute_import, division, print_function, unicode_literals
3 import os
5 from qtpy import compat
6 from qtpy import QtGui
7 from qtpy import QtCore
8 from qtpy import QtWidgets
9 from qtpy.QtCore import Qt
10 from qtpy.QtCore import Signal
12 from . import core
13 from . import hotkeys
14 from . import icons
15 from . import utils
16 from .i18n import N_
17 from .compat import int_types
18 from .compat import ustr
19 from .models import prefs
20 from .widgets import defs
23 STRETCH = object()
24 SKIPPED = object()
27 def active_window():
28 """Return the active window for the current application"""
29 return QtWidgets.QApplication.activeWindow()
32 def connect_action(action, fn):
33 """Connect an action to a function"""
34 action.triggered[bool].connect(lambda x: fn(), type=Qt.QueuedConnection)
37 def connect_action_bool(action, fn):
38 """Connect a triggered(bool) action to a function"""
39 action.triggered[bool].connect(fn, type=Qt.QueuedConnection)
42 def connect_button(button, fn):
43 """Connect a button to a function"""
44 # Some versions of Qt send the `bool` argument to the clicked callback,
45 # and some do not. The lambda consumes all callback-provided arguments.
46 button.clicked.connect(lambda *args, **kwargs: fn(), type=Qt.QueuedConnection)
49 def connect_checkbox(widget, fn):
50 """Connect a checkbox to a function taking bool"""
51 widget.clicked.connect(
52 lambda *args, **kwargs: fn(get(checkbox)), type=Qt.QueuedConnection
56 def connect_released(button, fn):
57 """Connect a button to a function"""
58 button.released.connect(fn, type=Qt.QueuedConnection)
61 def button_action(button, action):
62 """Make a button trigger an action"""
63 connect_button(button, action.trigger)
66 def connect_toggle(toggle, fn):
67 """Connect a toggle button to a function"""
68 toggle.toggled.connect(fn, type=Qt.QueuedConnection)
71 def disconnect(signal):
72 """Disconnect signal from all slots"""
73 try:
74 signal.disconnect()
75 except TypeError: # allow unconnected slots
76 pass
79 def get(widget):
80 """Query a widget for its python value"""
81 if hasattr(widget, 'isChecked'):
82 value = widget.isChecked()
83 elif hasattr(widget, 'value'):
84 value = widget.value()
85 elif hasattr(widget, 'text'):
86 value = widget.text()
87 elif hasattr(widget, 'toPlainText'):
88 value = widget.toPlainText()
89 elif hasattr(widget, 'sizes'):
90 value = widget.sizes()
91 elif hasattr(widget, 'date'):
92 value = widget.date().toString(Qt.ISODate)
93 else:
94 value = None
95 return value
98 def hbox(margin, spacing, *items):
99 """Create an HBoxLayout with the specified sizes and items"""
100 return box(QtWidgets.QHBoxLayout, margin, spacing, *items)
103 def vbox(margin, spacing, *items):
104 """Create a VBoxLayout with the specified sizes and items"""
105 return box(QtWidgets.QVBoxLayout, margin, spacing, *items)
108 def buttongroup(*items):
109 """Create a QButtonGroup for the specified items"""
110 group = QtWidgets.QButtonGroup()
111 for i in items:
112 group.addButton(i)
113 return group
116 def set_margin(layout, margin):
117 """Set the content margins for a layout"""
118 layout.setContentsMargins(margin, margin, margin, margin)
121 def box(cls, margin, spacing, *items):
122 """Create a QBoxLayout with the specified sizes and items"""
123 stretch = STRETCH
124 skipped = SKIPPED
125 layout = cls()
126 layout.setSpacing(spacing)
127 set_margin(layout, margin)
129 for i in items:
130 if isinstance(i, QtWidgets.QWidget):
131 layout.addWidget(i)
132 elif isinstance(
135 QtWidgets.QHBoxLayout,
136 QtWidgets.QVBoxLayout,
137 QtWidgets.QFormLayout,
138 QtWidgets.QLayout,
141 layout.addLayout(i)
142 elif i is stretch:
143 layout.addStretch()
144 elif i is skipped:
145 continue
146 elif isinstance(i, int_types):
147 layout.addSpacing(i)
149 return layout
152 def form(margin, spacing, *widgets):
153 """Create a QFormLayout with the specified sizes and items"""
154 layout = QtWidgets.QFormLayout()
155 layout.setSpacing(spacing)
156 layout.setFieldGrowthPolicy(QtWidgets.QFormLayout.ExpandingFieldsGrow)
157 set_margin(layout, margin)
159 for idx, (name, widget) in enumerate(widgets):
160 if isinstance(name, (str, ustr)):
161 layout.addRow(name, widget)
162 else:
163 layout.setWidget(idx, QtWidgets.QFormLayout.LabelRole, name)
164 layout.setWidget(idx, QtWidgets.QFormLayout.FieldRole, widget)
166 return layout
169 def grid(margin, spacing, *widgets):
170 """Create a QGridLayout with the specified sizes and items"""
171 layout = QtWidgets.QGridLayout()
172 layout.setSpacing(spacing)
173 set_margin(layout, margin)
175 for row in widgets:
176 item = row[0]
177 if isinstance(item, QtWidgets.QWidget):
178 layout.addWidget(*row)
179 elif isinstance(item, QtWidgets.QLayoutItem):
180 layout.addItem(*row)
182 return layout
185 def splitter(orientation, *widgets):
186 """Create a spliter over the specified widgets
188 :param orientation: Qt.Horizontal or Qt.Vertical
191 layout = QtWidgets.QSplitter()
192 layout.setOrientation(orientation)
193 layout.setHandleWidth(defs.handle_width)
194 layout.setChildrenCollapsible(True)
196 for idx, widget in enumerate(widgets):
197 layout.addWidget(widget)
198 layout.setStretchFactor(idx, 1)
200 # Workaround for Qt not setting the WA_Hover property for QSplitter
201 # Cf. https://bugreports.qt.io/browse/QTBUG-13768
202 layout.handle(1).setAttribute(Qt.WA_Hover)
204 return layout
207 def label(text=None, align=None, fmt=None, selectable=True):
208 """Create a QLabel with the specified properties"""
209 widget = QtWidgets.QLabel()
210 if align is not None:
211 widget.setAlignment(align)
212 if fmt is not None:
213 widget.setTextFormat(fmt)
214 if selectable:
215 widget.setTextInteractionFlags(Qt.TextBrowserInteraction)
216 widget.setOpenExternalLinks(True)
217 if text:
218 widget.setText(text)
219 return widget
222 class ComboBox(QtWidgets.QComboBox):
223 """Custom read-only combobox with a convenient API"""
225 def __init__(self, items=None, editable=False, parent=None, transform=None):
226 super(ComboBox, self).__init__(parent)
227 self.setEditable(editable)
228 self.transform = transform
229 self.item_data = []
230 if items:
231 self.addItems(items)
232 self.item_data.extend(items)
234 def set_index(self, idx):
235 idx = utils.clamp(idx, 0, self.count() - 1)
236 self.setCurrentIndex(idx)
238 def add_item(self, text, data):
239 self.addItem(text)
240 self.item_data.append(data)
242 def current_data(self):
243 return self.item_data[self.currentIndex()]
245 def set_value(self, value):
246 if self.transform:
247 value = self.transform(value)
248 try:
249 index = self.item_data.index(value)
250 except ValueError:
251 index = 0
252 self.setCurrentIndex(index)
255 def combo(items, editable=False, parent=None):
256 """Create a readonly (by default) combobox from a list of items"""
257 return ComboBox(editable=editable, items=items, parent=parent)
260 def combo_mapped(data, editable=False, transform=None, parent=None):
261 """Create a readonly (by default) combobox from a list of items"""
262 widget = ComboBox(editable=editable, transform=transform, parent=parent)
263 for (k, v) in data:
264 widget.add_item(k, v)
265 return widget
268 def textbrowser(text=None):
269 """Create a QTextBrowser for the specified text"""
270 widget = QtWidgets.QTextBrowser()
271 widget.setOpenExternalLinks(True)
272 if text:
273 widget.setText(text)
274 return widget
277 def add_completer(widget, items):
278 """Add simple completion to a widget"""
279 completer = QtWidgets.QCompleter(items, widget)
280 completer.setCaseSensitivity(Qt.CaseInsensitive)
281 completer.setCompletionMode(QtWidgets.QCompleter.InlineCompletion)
282 widget.setCompleter(completer)
285 def prompt(msg, title=None, text='', parent=None):
286 """Presents the user with an input widget and returns the input."""
287 if title is None:
288 title = msg
289 if parent is None:
290 parent = active_window()
291 result = QtWidgets.QInputDialog.getText(
292 parent, title, msg, QtWidgets.QLineEdit.Normal, text
294 return (result[0], result[1])
297 def prompt_n(msg, inputs):
298 """Presents the user with N input widgets and returns the results"""
299 dialog = QtWidgets.QDialog(active_window())
300 dialog.setWindowModality(Qt.WindowModal)
301 dialog.setWindowTitle(msg)
303 long_value = msg
304 for k, v in inputs:
305 if len(k + v) > len(long_value):
306 long_value = k + v
308 metrics = QtGui.QFontMetrics(dialog.font())
309 min_width = min(720, metrics.width(long_value) + 100)
310 dialog.setMinimumWidth(min_width)
312 ok_b = ok_button(msg, enabled=False)
313 close_b = close_button()
315 form_widgets = []
317 def get_values():
318 return [pair[1].text().strip() for pair in form_widgets]
320 for name, value in inputs:
321 lineedit = QtWidgets.QLineEdit()
322 # Enable the OK button only when all fields have been populated
323 # pylint: disable=no-member
324 lineedit.textChanged.connect(
325 lambda x: ok_b.setEnabled(all(get_values())), type=Qt.QueuedConnection
327 if value:
328 lineedit.setText(value)
329 form_widgets.append((name, lineedit))
331 # layouts
332 form_layout = form(defs.no_margin, defs.button_spacing, *form_widgets)
333 button_layout = hbox(defs.no_margin, defs.button_spacing, STRETCH, close_b, ok_b)
334 main_layout = vbox(defs.margin, defs.button_spacing, form_layout, button_layout)
335 dialog.setLayout(main_layout)
337 # connections
338 connect_button(ok_b, dialog.accept)
339 connect_button(close_b, dialog.reject)
341 accepted = dialog.exec_() == QtWidgets.QDialog.Accepted
342 text = get_values()
343 ok = accepted and all(text)
344 return (ok, text)
347 def standard_item_type_value(value):
348 """Return a custom UserType for use in QTreeWidgetItem.type() overrides"""
349 return custom_item_type_value(QtGui.QStandardItem, value)
352 def graphics_item_type_value(value):
353 """Return a custom UserType for use in QGraphicsItem.type() overrides"""
354 return custom_item_type_value(QtWidgets.QGraphicsItem, value)
357 def custom_item_type_value(cls, value):
358 """Return a custom cls.UserType for use in cls.type() overrides"""
359 user_type = enum_value(cls.UserType)
360 return user_type + value
363 def enum_value(value):
364 """Qt6 has enums with an inner '.value' attribute."""
365 if hasattr(value, 'value'):
366 value = value.value
367 return value
370 class TreeWidgetItem(QtWidgets.QTreeWidgetItem):
372 TYPE = standard_item_type_value(101)
374 def __init__(self, path, icon, deleted):
375 QtWidgets.QTreeWidgetItem.__init__(self)
376 self.path = path
377 self.deleted = deleted
378 self.setIcon(0, icons.from_name(icon))
379 self.setText(0, path)
381 def type(self):
382 return self.TYPE
385 def paths_from_indexes(model, indexes, item_type=TreeWidgetItem.TYPE, item_filter=None):
386 """Return paths from a list of QStandardItemModel indexes"""
387 items = [model.itemFromIndex(i) for i in indexes]
388 return paths_from_items(items, item_type=item_type, item_filter=item_filter)
391 def _true_filter(_x):
392 return True
395 def paths_from_items(items, item_type=TreeWidgetItem.TYPE, item_filter=None):
396 """Return a list of paths from a list of items"""
397 if item_filter is None:
398 item_filter = _true_filter
399 return [i.path for i in items if i.type() == item_type and item_filter(i)]
402 def tree_selection(tree_item, items):
403 """Returns an array of model items that correspond to the selected
404 QTreeWidgetItem children"""
405 selected = []
406 count = min(tree_item.childCount(), len(items))
407 for idx in range(count):
408 if tree_item.child(idx).isSelected():
409 selected.append(items[idx])
411 return selected
414 def tree_selection_items(tree_item):
415 """Returns selected widget items"""
416 selected = []
417 for idx in range(tree_item.childCount()):
418 child = tree_item.child(idx)
419 if child.isSelected():
420 selected.append(child)
422 return selected
425 def selected_item(list_widget, items):
426 """Returns the model item that corresponds to the selected QListWidget
427 row."""
428 widget_items = list_widget.selectedItems()
429 if not widget_items:
430 return None
431 widget_item = widget_items[0]
432 row = list_widget.row(widget_item)
433 if row < len(items):
434 item = items[row]
435 else:
436 item = None
437 return item
440 def selected_items(list_widget, items):
441 """Returns an array of model items that correspond to the selected
442 QListWidget rows."""
443 item_count = len(items)
444 selected = []
445 for widget_item in list_widget.selectedItems():
446 row = list_widget.row(widget_item)
447 if row < item_count:
448 selected.append(items[row])
449 return selected
452 def open_file(title, directory=None):
453 """Creates an Open File dialog and returns a filename."""
454 result = compat.getopenfilename(
455 parent=active_window(), caption=title, basedir=directory
457 return result[0]
460 def open_files(title, directory=None, filters=''):
461 """Creates an Open File dialog and returns a list of filenames."""
462 result = compat.getopenfilenames(
463 parent=active_window(), caption=title, basedir=directory, filters=filters
465 return result[0]
468 def opendir_dialog(caption, path):
469 """Prompts for a directory path"""
470 options = (
471 QtWidgets.QFileDialog.Directory
472 | QtWidgets.QFileDialog.DontResolveSymlinks
473 | QtWidgets.QFileDialog.ReadOnly
474 | QtWidgets.QFileDialog.ShowDirsOnly
476 return compat.getexistingdirectory(
477 parent=active_window(), caption=caption, basedir=path, options=options
481 def save_as(filename, title='Save As...'):
482 """Creates a Save File dialog and returns a filename."""
483 result = compat.getsavefilename(
484 parent=active_window(), caption=title, basedir=filename
486 return result[0]
489 def copy_path(filename, absolute=True):
490 """Copy a filename to the clipboard"""
491 if filename is None:
492 return
493 if absolute:
494 filename = core.abspath(filename)
495 set_clipboard(filename)
498 def set_clipboard(text):
499 """Sets the copy/paste buffer to text."""
500 if not text:
501 return
502 clipboard = QtWidgets.QApplication.clipboard()
503 clipboard.setText(text, QtGui.QClipboard.Clipboard)
504 if not utils.is_darwin() and not utils.is_win32():
505 clipboard.setText(text, QtGui.QClipboard.Selection)
506 persist_clipboard()
509 # pylint: disable=line-too-long
510 def persist_clipboard():
511 """Persist the clipboard
513 X11 stores only a reference to the clipboard data.
514 Send a clipboard event to force a copy of the clipboard to occur.
515 This ensures that the clipboard is present after git-cola exits.
516 Otherwise, the reference is destroyed on exit.
518 C.f. https://stackoverflow.com/questions/2007103/how-can-i-disable-clear-of-clipboard-on-exit-of-pyqt4-application
520 """ # noqa
521 clipboard = QtWidgets.QApplication.clipboard()
522 event = QtCore.QEvent(QtCore.QEvent.Clipboard)
523 QtWidgets.QApplication.sendEvent(clipboard, event)
526 def add_action_bool(widget, text, fn, checked, *shortcuts):
527 tip = text
528 action = _add_action(widget, text, tip, fn, connect_action_bool, *shortcuts)
529 action.setCheckable(True)
530 action.setChecked(checked)
531 return action
534 def add_action(widget, text, fn, *shortcuts):
535 tip = text
536 return _add_action(widget, text, tip, fn, connect_action, *shortcuts)
539 def add_action_with_status_tip(widget, text, tip, fn, *shortcuts):
540 return _add_action(widget, text, tip, fn, connect_action, *shortcuts)
543 def _add_action(widget, text, tip, fn, connect, *shortcuts):
544 action = QtWidgets.QAction(text, widget)
545 if hasattr(action, 'setIconVisibleInMenu'):
546 action.setIconVisibleInMenu(True)
547 if tip:
548 action.setStatusTip(tip)
549 connect(action, fn)
550 if shortcuts:
551 action.setShortcuts(shortcuts)
552 if hasattr(Qt, 'WidgetWithChildrenShortcut'):
553 action.setShortcutContext(Qt.WidgetWithChildrenShortcut)
554 widget.addAction(action)
555 return action
558 def set_selected_item(widget, idx):
559 """Sets a the currently selected item to the item at index idx."""
560 if isinstance(widget, QtWidgets.QTreeWidget):
561 item = widget.topLevelItem(idx)
562 if item:
563 item.setSelected(True)
564 widget.setCurrentItem(item)
567 def add_items(widget, items):
568 """Adds items to a widget."""
569 for item in items:
570 if item is None:
571 continue
572 widget.addItem(item)
575 def set_items(widget, items):
576 """Clear the existing widget contents and set the new items."""
577 widget.clear()
578 add_items(widget, items)
581 def create_treeitem(filename, staged=False, deleted=False, untracked=False):
582 """Given a filename, return a TreeWidgetItem for a status widget
584 "staged", "deleted, and "untracked" control which icon is used.
587 icon_name = icons.status(filename, deleted, staged, untracked)
588 icon = icons.name_from_basename(icon_name)
589 return TreeWidgetItem(filename, icon, deleted=deleted)
592 def add_close_action(widget):
593 """Adds close action and shortcuts to a widget."""
594 return add_action(widget, N_('Close...'), widget.close, hotkeys.CLOSE, hotkeys.QUIT)
597 def app():
598 """Return the current application"""
599 return QtWidgets.QApplication.instance()
602 def desktop():
603 """Return the desktop"""
604 return app().desktop()
607 def desktop_size():
608 desk = desktop()
609 rect = desk.screenGeometry(QtGui.QCursor().pos())
610 return (rect.width(), rect.height())
613 def center_on_screen(widget):
614 """Move widget to the center of the default screen"""
615 width, height = desktop_size()
616 cx = width // 2
617 cy = height // 2
618 widget.move(cx - widget.width() // 2, cy - widget.height() // 2)
621 def default_size(parent, width, height, use_parent_height=True):
622 """Return the parent's size, or the provided defaults"""
623 if parent is not None:
624 width = parent.width()
625 if use_parent_height:
626 height = parent.height()
627 return (width, height)
630 def default_monospace_font():
631 if utils.is_darwin():
632 family = 'Monaco'
633 else:
634 family = 'Monospace'
635 mfont = QtGui.QFont()
636 mfont.setFamily(family)
637 return mfont
640 def diff_font_str(context):
641 cfg = context.cfg
642 font_str = cfg.get(prefs.FONTDIFF)
643 if not font_str:
644 font_str = default_monospace_font().toString()
645 return font_str
648 def diff_font(context):
649 return font(diff_font_str(context))
652 def font(string):
653 qfont = QtGui.QFont()
654 qfont.fromString(string)
655 return qfont
658 def create_button(
659 text='', layout=None, tooltip=None, icon=None, enabled=True, default=False
661 """Create a button, set its title, and add it to the parent."""
662 button = QtWidgets.QPushButton()
663 button.setCursor(Qt.PointingHandCursor)
664 button.setFocusPolicy(Qt.NoFocus)
665 if text:
666 button.setText(' ' + text)
667 if icon is not None:
668 button.setIcon(icon)
669 button.setIconSize(QtCore.QSize(defs.small_icon, defs.small_icon))
670 if tooltip is not None:
671 button.setToolTip(tooltip)
672 if layout is not None:
673 layout.addWidget(button)
674 if not enabled:
675 button.setEnabled(False)
676 if default:
677 button.setDefault(True)
678 return button
681 def tool_button():
682 """Create a flat border-less button"""
683 button = QtWidgets.QToolButton()
684 button.setPopupMode(QtWidgets.QToolButton.InstantPopup)
685 button.setCursor(Qt.PointingHandCursor)
686 button.setFocusPolicy(Qt.NoFocus)
687 # Highlight colors
688 palette = QtGui.QPalette()
689 highlight = palette.color(QtGui.QPalette.Highlight)
690 highlight_rgb = rgb_css(highlight)
692 button.setStyleSheet(
694 /* No borders */
695 QToolButton {
696 border: none;
697 background-color: none;
699 /* Hide the menu indicator */
700 QToolButton::menu-indicator {
701 image: none;
703 QToolButton:hover {
704 border: %(border)spx solid %(highlight_rgb)s;
707 % dict(border=defs.border, highlight_rgb=highlight_rgb)
709 return button
712 def create_action_button(tooltip=None, icon=None):
713 """Create a small toolbutton for use in dock title widgets"""
714 button = tool_button()
715 if tooltip is not None:
716 button.setToolTip(tooltip)
717 if icon is not None:
718 button.setIcon(icon)
719 button.setIconSize(QtCore.QSize(defs.small_icon, defs.small_icon))
720 return button
723 def ok_button(text, default=True, enabled=True, icon=None):
724 if icon is None:
725 icon = icons.ok()
726 return create_button(text=text, icon=icon, default=default, enabled=enabled)
729 def close_button(text=None, icon=None):
730 text = text or N_('Close')
731 icon = icons.mkicon(icon, icons.close)
732 return create_button(text=text, icon=icon)
735 def edit_button(enabled=True, default=False):
736 return create_button(
737 text=N_('Edit'), icon=icons.edit(), enabled=enabled, default=default
741 def refresh_button(enabled=True, default=False):
742 return create_button(
743 text=N_('Refresh'), icon=icons.sync(), enabled=enabled, default=default
747 def checkbox(text='', tooltip='', checked=None):
748 """Create a checkbox"""
749 return _checkbox(QtWidgets.QCheckBox, text, tooltip, checked)
752 def radio(text='', tooltip='', checked=None):
753 """Create a radio button"""
754 return _checkbox(QtWidgets.QRadioButton, text, tooltip, checked)
757 def _checkbox(cls, text, tooltip, checked):
758 """Create a widget and apply properties"""
759 widget = cls()
760 if text:
761 widget.setText(text)
762 if tooltip:
763 widget.setToolTip(tooltip)
764 if checked is not None:
765 widget.setChecked(checked)
766 return widget
769 class DockTitleBarWidget(QtWidgets.QFrame):
770 def __init__(self, parent, title, stretch=True):
771 QtWidgets.QFrame.__init__(self, parent)
772 self.setAutoFillBackground(True)
773 self.label = qlabel = QtWidgets.QLabel(title, self)
774 qfont = qlabel.font()
775 qfont.setBold(True)
776 qlabel.setFont(qfont)
777 qlabel.setCursor(Qt.OpenHandCursor)
779 self.close_button = create_action_button(
780 tooltip=N_('Close'), icon=icons.close()
783 self.toggle_button = create_action_button(
784 tooltip=N_('Detach'), icon=icons.external()
787 self.corner_layout = hbox(defs.no_margin, defs.spacing)
789 if stretch:
790 separator = STRETCH
791 else:
792 separator = SKIPPED
794 self.main_layout = hbox(
795 defs.small_margin,
796 defs.titlebar_spacing,
797 qlabel,
798 separator,
799 self.corner_layout,
800 self.toggle_button,
801 self.close_button,
803 self.setLayout(self.main_layout)
805 connect_button(self.toggle_button, self.toggle_floating)
806 connect_button(self.close_button, self.toggle_visibility)
808 def toggle_floating(self):
809 self.parent().setFloating(not self.parent().isFloating())
810 self.update_tooltips()
812 def toggle_visibility(self):
813 self.parent().toggleViewAction().trigger()
815 def set_title(self, title):
816 self.label.setText(title)
818 def add_corner_widget(self, widget):
819 self.corner_layout.addWidget(widget)
821 def update_tooltips(self):
822 if self.parent().isFloating():
823 tooltip = N_('Attach')
824 else:
825 tooltip = N_('Detach')
826 self.toggle_button.setToolTip(tooltip)
829 def create_dock(name, title, parent, stretch=True, widget=None, fn=None):
830 """Create a dock widget and set it up accordingly."""
831 dock = QtWidgets.QDockWidget(parent)
832 dock.setWindowTitle(title)
833 dock.setObjectName(name)
834 titlebar = DockTitleBarWidget(dock, title, stretch=stretch)
835 dock.setTitleBarWidget(titlebar)
836 dock.setAutoFillBackground(True)
837 if hasattr(parent, 'dockwidgets'):
838 parent.dockwidgets.append(dock)
839 if fn:
840 widget = fn(dock)
841 assert isinstance(widget, QtWidgets.QFrame), "Docked widget has to be a QFrame"
842 if widget:
843 dock.setWidget(widget)
844 return dock
847 def hide_dock(widget):
848 widget.toggleViewAction().setChecked(False)
849 widget.hide()
852 def create_menu(title, parent):
853 """Create a menu and set its title."""
854 qmenu = DebouncingMenu(title, parent)
855 return qmenu
858 class DebouncingMenu(QtWidgets.QMenu):
859 """Menu that debounces mouse release action ie. stops it if occurred
860 right after menu creation.
862 Disables annoying behaviour when RMB is pressed to show menu, cursor is
863 moved accidentally 1px onto newly created menu and released causing to
864 execute menu action
867 threshold_ms = 400
869 def __init__(self, title, parent):
870 QtWidgets.QMenu.__init__(self, title, parent)
871 self.created_at = utils.epoch_millis()
872 if hasattr(self, 'setToolTipsVisible'):
873 self.setToolTipsVisible(True)
875 def mouseReleaseEvent(self, event):
876 threshold = DebouncingMenu.threshold_ms
877 if (utils.epoch_millis() - self.created_at) > threshold:
878 QtWidgets.QMenu.mouseReleaseEvent(self, event)
881 def add_menu(title, parent):
882 """Create a menu and set its title."""
883 menu = create_menu(title, parent)
884 if hasattr(parent, 'addMenu'):
885 parent.addMenu(menu)
886 else:
887 parent.addAction(menu.menuAction())
888 return menu
891 def create_toolbutton(text=None, layout=None, tooltip=None, icon=None):
892 button = tool_button()
893 if icon is not None:
894 button.setIcon(icon)
895 button.setIconSize(QtCore.QSize(defs.default_icon, defs.default_icon))
896 if text is not None:
897 button.setText(' ' + text)
898 button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
899 if tooltip is not None:
900 button.setToolTip(tooltip)
901 if layout is not None:
902 layout.addWidget(button)
903 return button
906 def create_toolbutton_with_callback(callback, text, icon, tooltip, layout=None):
907 """Create a toolbutton that runs the specified callback"""
908 toolbutton = create_toolbutton(text=text, layout=layout, tooltip=tooltip, icon=icon)
909 connect_button(toolbutton, callback)
910 return toolbutton
913 # pylint: disable=line-too-long
914 def mimedata_from_paths(context, paths, include_urls=True):
915 """Return mimedata with a list of absolute path URLs
917 Set `include_urls` to False to prevent URLs from being included
918 in the mimedata. This is useful in some terminals that do not gracefully handle
919 multiple URLs being included in the payload.
921 This allows the mimedata to contain just plain a plain text value that we
922 are able to format ourselves.
924 Older verisons of gnome-terminal expected a utf-16 encoding, but that
925 behavior is no longer needed.
926 """ # noqa
927 abspaths = [core.abspath(path) for path in paths]
928 paths_text = core.list2cmdline(abspaths)
930 # The text/x-moz-list format is always included by Qt, and doing
931 # mimedata.removeFormat('text/x-moz-url') has no effect.
932 # http://www.qtcentre.org/threads/44643-Dragging-text-uri-list-Qt-inserts-garbage
934 # Older versions of gnome-terminal expect utf-16 encoded text, but other terminals,
935 # e.g. terminator, expect utf-8, so use cola.dragencoding to override the default.
936 # NOTE: text/x-moz-url does not seem to be used/needed by modern versions of
937 # gnome-terminal, kitty, and terminator.
938 mimedata = QtCore.QMimeData()
939 mimedata.setText(paths_text)
940 if include_urls:
941 urls = [QtCore.QUrl.fromLocalFile(path) for path in abspaths]
942 encoding = context.cfg.get('cola.dragencoding', 'utf-16')
943 encoded_text = core.encode(paths_text, encoding=encoding)
944 mimedata.setUrls(urls)
945 mimedata.setData('text/x-moz-url', encoded_text)
947 return mimedata
950 def path_mimetypes(include_urls=True):
951 """Return a list of mimetypes that we generate"""
952 mime_types = [
953 'text/plain',
954 'text/plain;charset=utf-8',
956 if include_urls:
957 mime_types.append('text/uri-list')
958 mime_types.append('text/x-moz-url')
959 return mime_types
962 class BlockSignals(object):
963 """Context manager for blocking a signals on a widget"""
965 def __init__(self, *widgets):
966 self.widgets = widgets
967 self.values = []
969 def __enter__(self):
970 """Block Qt signals for all of the captured widgets"""
971 self.values = [widget.blockSignals(True) for widget in self.widgets]
972 return self
974 def __exit__(self, exc_type, exc_val, exc_tb):
975 """Restore Qt signals when we exit the scope"""
976 for (widget, value) in zip(self.widgets, self.values):
977 widget.blockSignals(value)
980 class Channel(QtCore.QObject):
981 finished = Signal(object)
982 result = Signal(object)
985 class Task(QtCore.QRunnable):
986 """Disable auto-deletion to avoid gc issues
988 Python's garbage collector will try to double-free the task
989 once it's finished, so disable Qt's auto-deletion as a workaround.
993 def __init__(self):
994 QtCore.QRunnable.__init__(self)
996 self.channel = Channel()
997 self.result = None
998 self.setAutoDelete(False)
1000 def run(self):
1001 self.result = self.task()
1002 self.channel.result.emit(self.result)
1003 self.channel.finished.emit(self)
1005 # pylint: disable=no-self-use
1006 def task(self):
1007 return None
1009 def connect(self, handler):
1010 self.channel.result.connect(handler, type=Qt.QueuedConnection)
1013 class SimpleTask(Task):
1014 """Run a simple callable as a task"""
1016 def __init__(self, fn, *args, **kwargs):
1017 Task.__init__(self)
1019 self.fn = fn
1020 self.args = args
1021 self.kwargs = kwargs
1023 def task(self):
1024 return self.fn(*self.args, **self.kwargs)
1027 class RunTask(QtCore.QObject):
1028 """Runs QRunnable instances and transfers control when they finish"""
1030 def __init__(self, parent=None):
1031 QtCore.QObject.__init__(self, parent)
1032 self.tasks = []
1033 self.task_details = {}
1034 self.threadpool = QtCore.QThreadPool.globalInstance()
1035 self.result_fn = None
1037 def start(self, task, progress=None, finish=None, result=None):
1038 """Start the task and register a callback"""
1039 self.result_fn = result
1040 if progress is not None:
1041 progress.show()
1042 # prevents garbage collection bugs in certain PyQt4 versions
1043 self.tasks.append(task)
1044 task_id = id(task)
1045 self.task_details[task_id] = (progress, finish, result)
1046 task.channel.finished.connect(self.finish, type=Qt.QueuedConnection)
1047 self.threadpool.start(task)
1049 def finish(self, task):
1050 task_id = id(task)
1051 try:
1052 self.tasks.remove(task)
1053 except ValueError:
1054 pass
1055 try:
1056 progress, finish, result = self.task_details[task_id]
1057 del self.task_details[task_id]
1058 except KeyError:
1059 finish = progress = result = None
1061 if progress is not None:
1062 progress.hide()
1064 if result is not None:
1065 result(task.result)
1067 if finish is not None:
1068 finish(task)
1071 # Syntax highlighting
1074 def rgb(r, g, b):
1075 color = QtGui.QColor()
1076 color.setRgb(r, g, b)
1077 return color
1080 def rgba(r, g, b, a=255):
1081 color = rgb(r, g, b)
1082 color.setAlpha(a)
1083 return color
1086 def RGB(args):
1087 return rgb(*args)
1090 def rgb_css(color):
1091 """Convert a QColor into an rgb(int, int, int) CSS string"""
1092 return 'rgb(%d, %d, %d)' % (color.red(), color.green(), color.blue())
1095 def rgb_hex(color):
1096 """Convert a QColor into a hex aabbcc string"""
1097 return '%02x%02x%02x' % (color.red(), color.green(), color.blue())
1100 def hsl(h, s, light):
1101 return QtGui.QColor.fromHslF(
1102 utils.clamp(h, 0.0, 1.0), utils.clamp(s, 0.0, 1.0), utils.clamp(light, 0.0, 1.0)
1106 def hsl_css(h, s, light):
1107 return rgb_css(hsl(h, s, light))
1110 def make_format(fg=None, bg=None, bold=False):
1111 fmt = QtGui.QTextCharFormat()
1112 if fg:
1113 fmt.setForeground(fg)
1114 if bg:
1115 fmt.setBackground(bg)
1116 if bold:
1117 fmt.setFontWeight(QtGui.QFont.Bold)
1118 return fmt
1121 class ImageFormats(object):
1122 def __init__(self):
1123 # returns a list of QByteArray objects
1124 formats_qba = QtGui.QImageReader.supportedImageFormats()
1125 # portability: python3 data() returns bytes, python2 returns str
1126 decode = core.decode
1127 formats = [decode(x.data()) for x in formats_qba]
1128 self.extensions = {'.' + fmt for fmt in formats}
1130 def ok(self, filename):
1131 _, ext = os.path.splitext(filename)
1132 return ext.lower() in self.extensions
1135 def set_scrollbar_values(widget, hscroll_value, vscroll_value):
1136 """Set scrollbars to the specified values"""
1137 hscroll = widget.horizontalScrollBar()
1138 if hscroll and hscroll_value is not None:
1139 hscroll.setValue(hscroll_value)
1141 vscroll = widget.verticalScrollBar()
1142 if vscroll and vscroll_value is not None:
1143 vscroll.setValue(vscroll_value)
1146 def get_scrollbar_values(widget):
1147 """Return the current (hscroll, vscroll) scrollbar values for a widget"""
1148 hscroll = widget.horizontalScrollBar()
1149 if hscroll:
1150 hscroll_value = get(hscroll)
1151 else:
1152 hscroll_value = None
1153 vscroll = widget.verticalScrollBar()
1154 if vscroll:
1155 vscroll_value = get(vscroll)
1156 else:
1157 vscroll_value = None
1158 return (hscroll_value, vscroll_value)
1161 def scroll_to_item(widget, item):
1162 """Scroll to an item while retaining the horizontal scroll position"""
1163 hscroll = None
1164 hscrollbar = widget.horizontalScrollBar()
1165 if hscrollbar:
1166 hscroll = get(hscrollbar)
1167 widget.scrollToItem(item)
1168 if hscroll is not None:
1169 hscrollbar.setValue(hscroll)
1172 def select_item(widget, item):
1173 """Scroll to and make a QTreeWidget item selected and current"""
1174 scroll_to_item(widget, item)
1175 widget.setCurrentItem(item)
1176 item.setSelected(True)
1179 def get_selected_values(widget, top_level_idx, values):
1180 """Map the selected items under the top-level item to the values list"""
1181 # Get the top-level item
1182 item = widget.topLevelItem(top_level_idx)
1183 return tree_selection(item, values)
1186 def get_selected_items(widget, idx):
1187 """Return the selected items under the top-level item"""
1188 item = widget.topLevelItem(idx)
1189 return tree_selection_items(item)