Control close event pyglet - python-3.x

I have a program that has multiple windows in pyglet, and I want to make one window unclosable, rather to set its visibility to false. Is there a way I can access the event handle for close, to make it instead of closing the window, possibly return a bool or a string like "should close."?

Found the answer to my own question, first define a custom event loop with window_event_loop = pyglet.app.EventLoop(), then create a handler for .event for the event loop
#window_event_loop.event
def on_window_close(window):
# Extra code here
return pyglet.event.EVENT_HANDLED

Related

Can't update GtkIconView from within a click event on a GtkListBox in a GtkDialog

Here's what the click event currently looks like for the ListBox in the dialog code.
def OnSelectCategory(self, listbox, data=None):
try:
# Get the text of the selected category.
selected = listbox.get_selected_row()
label = selected.get_child()
itemText = label.get_text()
# Get the tags for the selected category.
tagtext = self.categoryTags.get(itemText)
self.updateStatusbar("Collecting videos...")
# Start a thread to scan for videos.
self.threadEvent = threading.Event()
self.videoscanThread = threading.Thread(target=self.ScanForVideos, args=(self.threadEvent, tagtext,))
self.videoscanThread.daemon = True
self.videoscanThread.start()
self.threadEvent.set()
except Exception as e:
print("Exception from 'OnSelectCategory':", str(e))
At first, I could not get the status bar to update the text immediately. I had originally called the function to update the text directly. The status bar text would not update until the ScanForVideos function had finished. So, I moved the ScanForVideos code into a thread. The thread waits on an event to begin.
The thread (ScanForVideos) runs several 'for' loops looking for a matching condition. When the condition is found, the code appends to the liststore for the IconView. At the end of the thread function, the code sets the IconView model to the liststore. The IconView seems to update with a few items, but, not all that should be there. Additionally, the code seems to be 'hung' because I cannot dismiss the dialog that contains the IconView. I have to stop debugging within Visual Studio Code.
I feel like I'm violating something I'm not aware of in Python coding. Or, my design to update the IconView is not correct. Can anyone shed some light on what I may be doing wrong?
I realized that I was trying to update some UI widgets from within my background thread. I then stumbled upon GLib.idle_add. I wrote a separate function to update the UI widgets and called idle_add passing the name of the function. This allowed me to update the GUI from a background thread.

Terminating each() block in Protractor

I was automating the an application (using Protractor) and I have come across situation where I wanted to select the an option from the type ahead using the DOWN arrow button from the Keyboard. Here is how I am approaching to this action.
After typing part into the text field I am getting the reference of each option that appear in the type ahead.
Now, I am using .each() method of protractor to iterate through each of the option to look for the required option.
I'm making the script to hit DOWN arrow button to iterate through each option in the type ahead.
Suppose there are 10 options displayed in the type ahead and the option that I need to select is at 5th position. Now when I reach the 5th position I am selecting the option but each() function still continues.
I want the loop to terminate when required option is selected. Something like BREAK statement in FOR loops.
BTW I have tried the above scenario with FOR loop but unable to use BREAK statement within then() handler.
Please let me know how to cope up with this situation.
You could throw an exception to terminate the loop. Put the loop inside try and use catch to wrangle your results. You can also just use a boolean variable to indicate that you have found a match and ignore everything after that point. I would just use a for loop though.
Edit:
You could add a variable to hold an action before the allBenchmarks.each
var action
Then inside the test
if(dataValue == optionToSelect){
action = function() {benchmark.click(); ...}
}
After the loop exits call the action
if (action) action()

Linux x11 XGrabKeyboard() cause keyboard to be frozen

I am writing a program which need to listen the user keyboard stroks.
I use function XGrabKeyboard() and this is my code:
XGrabKeyboard(pDisplay, DefaultRootWindow(pDisplay), True, GrabModeAsync, GrabModeAsync, CurrentTime);
XEvent event;
while (true)
{
XNextEvent(pDisplay, &event);
switch (event.type)
{
...
}
}
But it causes the keyboard and cursor to be frozen.
I looked up the man page, it only says: "The third parameter specifies a Boolean value that indicates whether the keyboard events are to be reported as usual."
I tried both true or false or the 3rd param, both GrabModeAsync and GrabModeSync for the 4th and 5th param, but it doesn't work.
After calling XGrabKeyboard(), the keyboard is frozen and mouse click doesn't response.
Any ideas?
XGrabKeyboard() (if successful - be sure to check the return value), redirects all key events to your client.
So if your "..." inside the while(true) does not properly handle those key events, or does not ever ungrab (XUngrabKeyboard) or release sync events (XAllowEvents, only applies to GrabModeSync), then the keyboard would appear to lock up.
The boolean parameter is owner_events which indicates whether to report key events always to the window provided to XGrabKeyboard, or report them to the window they normally would have gone to without the grab. Typically you want False (report to the grab window).
For typical uses of XGrabKeyboard (I don't know your use-case) the parameters you would want are:
grab window = some window in your app that relates to the reason for the grab
owner_events=False to send all events to that window
pointer_mode=Async to not screw with the pointer
keyboard_mode=Async to just redirect all key events and avoid need for AllowEvents
time=the timestamp from the event triggering the grab, ideally, or one generated by changing a property and grabbing the timestamp off the PropertyNotify
But, it depends. To give any definitive answer you'd probably need to post a compilable program, I think the bug is likely in the "..." part of your code. Try narrowing your app down to a single-file test case that can be run by others perhaps. Or explain more why you are grabbing and what you're trying to accomplish in the big picture.
I cant help with the XGrabKeyboard function - I havent used it before and dont know how it works - but I can suggest another way of getting the keyboard events.
When creating my window using XCreateWindow, the last argument is a XSetWindowAttributes object. This object has a member event_mask, which you can use to choose which events your window will receive.
I set mine like this:
XSetWindowAttributes setWindAttrs
setWindAttrs.event_mask = ExposureMask
| KeyPressMask
| KeyReleaseMask
| ButtonPressMask
| ButtonReleaseMask;
That will mean you receive events for keyboard key presses and mouse button clicks if you pass this object to XCreateWindow on window creation.
Also another note you can use XPending(pDisplay) to check if there are still events waiting to be handled - so it could replace true in your while(true) line.
Edit: Also your freezing issue could be that you dont return false anywhere in your while loop? It may be stuck in an infinite loop, unless you just removed that bit for the post. Try replacing true with xpending as I suggested above and it may fix the issue, or just returning false after handling the event, but this would only handle one event per frame rather than handling all the currently pending events like XPending would do, and I assume that is what you want to do.

MFC dialog frozen

I need help how to unfreeze my dialog box. I'm using MFC and I have an infinite loop I want to execute when a button is pressed. However, the dialog box freezes when the infinite loop starts. Now I looked at this thread where someone was having a similar problem.
Unfortunately I tried multithreading but I found out that It can't work for me because I'm using an api that uses OLE automation and I'm getting an unhandled memory exception. I think this is because program uses the serial port and i read somewhere you can only use the handle to the serial port in one thread.
My program is simply to see if someone has dialed in to my modem and wait for them to send me a file, then hangup. Here is my loop.
while(1)
{
//get rid of input buffer
ts->_this->m_pHAScript->haReleaseRemoteInput();
ts-> _this->textBox->SetWindowTextA("thread Commence");
//wait for connected
if(success = ts->_this->m_pHAScript->haWaitForString("CONNECT",timeout))
{
//getFile
if(success = ts->_this->m_pHAScript->haWaitForXfer(5000))
{
//hangup
ts->_this->haTypeText("+++ath\r");
}
}
}
Is there a way to unfreeze the dialog box?
Add this code inside while loop:
MSG msg;
while(PeekMessage(&msg, GetSafeHwnd(), 0, 0, PM_REMOVE))
{
DispatchMessage(&msg);
}
The GUI in Windows relies on a message loop - somewhere in your code, either explicitly or hidden in a framework, there's a loop that checks for a message in a queue and processes it. If anything blocks the code from returning to that loop, the GUI gets frozen.
There are a few ways around this. One was given by David Brabant, essentially duplicating the loop. Another is to start a new "worker" thread that runs the blocking operation independently. If your message loop has a function that it calls when it is idle, i.e. no more messages are in the queue, you can do some processing there; that's not possible in your example however.

PyQt save to clipboard in a slot

How can I save some text to clipboard by pressing button? clipboard.setText("gg") works by itself
widget.connect(button, QtCore.SIGNAL('clicked()'), clipboard.setText("text") )
throw error, you can only use instance.methodName
widget.connect(button, QtCore.SIGNAL('clicked()'), clipboard, QtCore.SLOT('setText("text")') )
do nothing.
What is wrong?
First, there's a much better way to connect signals to slots on PyQt:
button.clicked.connect(self.method)
You can use lambda functions to pass extra arguments to methods.
Then you call
button1.clicked.connect(lambda : clipboard.setText('btn one'))
button2.clicked.connect(lambda : clipboard.setText('btn two'))
When you pass a function call, in fact the interpreter is evaluating the call and trying to pass the result to the SIGNAL/SLOT connection. That's why your first example doesn't work.
I've written something similar here: https://stackoverflow.com/questions/...from-other-functions

Resources