GTK detecting window resize from the user - gtk

In GTK (or pygtk or gtkmm...)
How can I detect that an application window has been manually resized by the user, as is typically done by dragging the window's edge?
I need to find a way to differentiate manual resizes from resizes that originate from gtk, such as changes in window content.

Have you tried connecting to the GDK_CONFIGURE event?
Check out this example under the
"Moving window" section. The example shows a callback doing something when the window is moved, but the configure event is a catch-all for moving, resizing and stack order events.

I managed to pull this off by watching for size_allocate and size_request signals on the GtkWindow. If size_request ever got smaller, I called resize(1,1). If size_allocate was ever bigger than expected, I turned the system off.
One thing I made sure to handle was size_request returning big, then small, and having size_allocate be big and then small. I don't know if this is possible, but I fixed it by making sure to only decrease the expected values for size_allocate when I got a smaller size_allocate, not when I got a smaller size_request.
Make sure that your size_request handler comes after the base class' handler so that you get the right values. I did this by overriding the method and then calling the base class method first.
I've tried this in both 1 and 2 dimensions and it seems to work either way.

In my case I was trying to distinguish between a user resizing a Gtk.Paned from the user resizing the whole window. Both emitted the notify::position signal.
My solution was, since I can't know if the user is resizing the window from the widget, reverse what I wanted to know. Record if the user has re-positioned the widget and ignore updates if the user didn't initiate them on my widget.
That is to say, instead of testing "if window being resized" I recorded the button-press-event and button-release-event's locally so I could instead test "if widget being re-positioned"
from gi.repository import Gtk
class MyPaned(Gtk.Paned):
_user_activated = False
def on_position(self, _, gparamspec):
if self._user_activated:
# widget touched
else:
# window resized (probably)
def on_button_press(self, *_):
self._user_activated = True
def on_button_release(self, *_):
self._user_activated = False
dev __init__(self, *args):
super(MyPaned, self).__init__(*args)
self.connect('notify::position', self.on_position)
self.connect('button-press-event', self.on_button_press)
self.connect('button-release-event', self.on_button_release)
Effectively by recorded when the user started and ended interacting with my widget directly, I could assume the rest of the time was due to the window being resized. (Until I find more cases)

In PyGTK, I've always watched for the expose_event for a window resize, then use the get_allocation method to get the new size.

You may be able to throw something together by using gdk_window_get_root_origin to get the top left corner of the window and gdk_window_get_geometry to get the width and height. Then you could hook a callback into the GDK_BUTTON_PRESS_MASK and check to see if the button press occurs near/on one of the edges of the window.
Of course, this seems quite hackish and it really bothers me that I couldn't find some simple way in the documentation for GdkWindow to do this. There is a gdk_window_begin_resize_drag function which really makes me think there's a cleaner way to do this, but I didn't see anything more obvious than my answer.

Related

VS Code brings search result line to the center of the screen

When you search for a keyword in VS Code, and it returns x results, as you start browsing among those results, the screen always centers vertically the active result on the screen. This may be useful in some situations, but in cases where I want to "frame" all my results in the same active screen, it's very annoying that it jumps the code, even by 2-3 lines...
OK, if in that viewable portion of the code there are no results, and I click on the next result, it'd make sense to bring me to the first one. But if let's say 4-5 results are already in the viewable portion of the code, I would like to set it so that it prevents that centering all the time. So is there such a setting?
I hope I explained it well enough so that you understand what I mean. TIA for any help.
I don't think that is configurable if the next find match is outside of the viewport. I see this in the code:
(https://github.com/microsoft/vscode/blob/7a0a293b38c353cd9773316a022d8f926d481715/src/vs/editor/contrib/find/browser/findModel.ts)
private _setCurrentFindMatch(match: Range): void {
let matchesPosition = this._decorations.setCurrentFindMatch(match);
this._state.changeMatchInfo(
matchesPosition,
this._decorations.getCount(),
match
);
this._editor.setSelection(match);
this._editor.revealRangeInCenterIfOutsideViewport(match, ScrollType.Smooth);
}
So revealRangeInCenterIfOutsideViewport() will always put the next find match into the center if it is not initially not in the viewport.
In the search code, there is the similar:
this.searchResultEditor.revealLineInCenterIfOutsideViewport(matchRange.startLineNumber);
So I would think there is no scrolling if the next serach result is already in view.
For me, there is no scrolliing at all if the next find match is anywhere in the viewport. Do you see some scrolling if it is at the very bottom, for example?

How to handle window resizes in GTK4?

I am trying to build a virtualized grid container to display 100k+ files in PyGTK 4 on Fedora 35. I succeeded in creating the layout and scrolling support which works beautifully.
In order to support resizing of my application window, I need to react to changes its size. I already connected to the notify signal of the window and handle the default-width, default-height, maximized and unmaximized events to update the geometry of my layout. However, everytime I invoke get_width() of my widget/app window after the maximized event I only get the width before the window was maximized! Is this by design?
I've been trying pretty hard but I fail to come to a working solution for this simple problem. Can anyone help me?
Edit
Here is some code to outline how I am trying to measure the window size. I modified the code to use connect_after instead of connectas proposed by #GüntherWagner. However, the behavior is the same for both methods:
class TestLayout(Gtk.ScrolledWindow):
def on_realize(self, widget):
...
self.get_root().connect_after('notify', self.on_notify)
def on_notify(self, widget, param):
if param.name in [..., 'maximized', 'unmaximized']:
self.draw()
def draw(self):
self.width = self.get_width()
self.height = self.get_height()

How to add a "tutorial message div" to figures?

After installing R2018b, the first figure I opened contained an interesting message (shown in blue):
The reason it's interesting is because it contains features like text wrapping, transparency, the fact that the image maintains a constant width even though the text resizes (this reminded me of CSS3 flexbox, hence the tag), etc.
The last part of the animation is in slow motion, to better show how the div's size follows that of the figure.
In case it matters, I'm using Win 10 v1803.
Question:
I'd like to know how we can draw similar, custom, divs (for a lack of a better word) in our figures. (It's important to stress that this is not a UIFigure!)
What I found so far:
The Learn More link opens the page:
web(fullfile(docroot, 'matlab/creating_plots/interactively-explore-plotted-data.html'))
yet breakpoints in the entry points of either web or docroot (or even doc) aren't hit.
Assuming that this element is a Child of the figure, I attempted to locate a handle to it:
>> set(gcf,'MenuBar','none'); findall(gcf)
ans =
22×1 graphics array:
Figure (1)
ContextMenu
AnnotationPane
Axes
AxesToolbar
Text
Text
Text
ToolbarStateButton (Brush/Select Data)
ToolbarStateButton (Data Tips)
ToolbarStateButton (Rotate 3-D)
ToolbarStateButton (Pan)
ToolbarStateButton (Zoom In)
ToolbarStateButton (Zoom Out)
ToolbarPushButton (Restore View)
Button
Button
Button
Button
Button
Button
Button
however, making these controls invisible using set(h(2:end), 'Visible', false) didn't make the div disappear.
Saving the figure as .fig or generating code for it, doesn't leave any trace of this div.
When uiinspect-ing the figure, this div doesn't show (or at least, I couldn't find it).
I don't know what exactly I did to make it reappear once more, but since it's set to appear on the very first time you boot R2018b, I suspect deleting prefdir (obviously, after backing it up) and restarting MATLAB could bring it back.
The only thing I didn't try yet, is to attach a java debugger to MATLAB and attempt to trace the caller to com.mathworks.mlservices.MLHelpServices.setCurrentLocation (from mlservices.jar), which opens the help browser.
After some digging in the Java side of things (starting from findjobj, followed by a lot of .getComponent(0).getComponent(0)...), I've finally managed to locate the component in question. Here's what I learned:
This component is called InfoPanel, and is part of MATLAB's Java API. The class definition itself is found in:
MATLAB/R2018b/java/jar/hg.jar!/com/mathworks/hg/util/InfoPanel.class
To make it appear, we need to call the static method addBannerPanel, passing in a figure handle:
com.mathworks.hg.util.InfoPanel.addBannerPanel( figure(randi(1E4)) );
Or another signature that also accepts a custom panel:
jIP = com.mathworks.hg.util.InfoPanel;
jIP.setBackground(java.awt.Color(0.8, 0.7, 0.1));
com.mathworks.hg.util.InfoPanel.addBannerPanel( figure(randi(1E4)), jIP );
The MATLAB setting that controls whether this should appear is showinteractioninfobar inside the <prefdir>/matlab.settings XML.
It appears that the "interesting parts" of InfoPanel are private, which means it allows barely any customization (mostly some colors; not the string or the icon), but it should be fairly easy to make a copy of this class and expose all elements we need.

QCompleter and Tab key

I'm trying to make a Completion when pressing tab, you get the first completion of all possibilities.
But, in a QWidget-based main window, pressing tab will make that QLineEdit lost focus, and completion popup hides after that.
Is there a way to fix it ?
Have you tried to subclass QLineEdit and intercept the key press event?
Alternatively you could set up an event filter.
Whew. It took me some time to figure this out :) Multiple times I have tried to solve this problem, but always gave up. Now, I dug enough to find the answer.
OP, please pardon me, because the code here is Python, but should be understandable and work for C++ as well.
Basically, the problem I had was "how to select an entry in the QCompleter"; I didn't notice before, but the answer is in the popup() method. QCompleter works with a model and a view, which contains the things to show.
You can change the current row as you wish, then get the index of that row in the model, then select it in the pop-up.
In my code, I subclassed QLineEdit, created a tabPressed signal which is emitted every time Tab is pressed. Then, connected this signal to a method of the same class which does this:
get the current index;
select the index in the popup;
advance to the next row.
As implementation, this is very trivial, but for my current purpose this is enough. Here's the skeleton (just for the tab part, it's missing the model and everything else).
class MyLineEdit(QLineEdit):
tabPressed = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self._compl = QCompleter()
self.tabPressed.connect(self.next_completion)
def next_completion(self):
index = self._compl.currentIndex()
self._compl.popup().setCurrentIndex(index)
start = self._compl.currentRow()
if not self._compl.setCurrentRow(start + 1):
self._compl.setCurrentRow(0)
def event(self, event):
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab:
self.tabPressed.emit()
return True
return super().event(event)
You may need to adjust/fix few things, but this is the basic idea.
EDIT:
For details see
http://www.qtcentre.org/threads/23518-How-to-change-completion-rule-of-QCompleter
There's a little issue: when Return is pressed, the things don't work properly. Maybe you can find a solution to this problem in the link above, or in the referenced resources therein. I'll fix this in the next few days and update this answer.
There is probably a better solution but one that comes to mind is to change the focus policy for all other widgets on the form to something that doesn't include "tab" focus. The only options that don't use the tab key are Qt::ClickFocus and Qt::NoFocus.

How to get the height of the gtktreeview header?

I've looked in the gtk source code and the header height is private. I've tried something but it didn't work as wanted (the heightWithHeader is 1?!)
Glib::RefPtr<Gdk::Window> pWindow = treeView.get_bin_window();
treeView.set_headers_visible(true);
pWindow->get_size(width, heightWithHeader);
treeView.set_headers_visible(false);
pWindow->get_size(width, heightWithoutHeader);
r_treeView.set_headers_visible(true);
returnValue = heightWithHeader - heightWithoutHeader;
Can you help me with another solution or a fix to my code?
Update: I have to adjust the height of the treeview to display a fixed number of rows. I do this by adjusting the size of the container (a scrolledwindow) to headerHeight + numberRowsToDisplay * heightOfRow.
The reason your code doesn't work is very probably that you're being "too impatient", not giving GTK+ time to do the redraw of the widgets before you make the headers invisible again.
GTK+ doesn't draw immediately when you do a call that requires a redraw. Instead redraws are queued, and then done all at once from the GTK+ main loop. This way, doing two changes to widgets in sequence does not cause two redraws, but only one.
It's a bit of a hack, but you could try the "classic" GTK+ event-flushing trick, by inserting a loop like this after you turn on the headers:
while(gtk_events_pending())
gtk_main_iteration();
This simply loops for as long as there are events in GTK+'s queue (the draw changes mentioned above are events, internally), and flushes them, then gives control back to you. This will very probably result in some visual flicker, though.