tcltk block input while processing in r - r

RGTK2 block user input while processing its explain how to block user input using RGTK2 but I dont know how to add that code to my GUI code, im using tcltk. What I want same like in RGTK2 block user input while processing but using tcltk2
I use this code to run button "filter cluster" and the command function is filter (function to do something)
tkpack(tkbutton(f4, text='Filter Cluster', command=filter), side='left',padx= 5, pady = 20)

In tcltk, you would use tkgrab.set on a non-responsive window and tkfocus on a window that has a binding on the <Key> event that prevents further processing. An inconspicuous tkframe is great for that sort of thing — set it to size 1×1, but ensure it is on the screen — as it has no default behaviour to get in the way. (You'll also want to make a bunch of cosmetic changes, such as marking the widgets as disabled and setting the cursor to watch.) In 8.6, there's tk busy (call with tcl("tk","busy",…) since the Tcl tk command appears to not have a convenient mapping) which makes this all much easier (though I don't know if/how that's mapped into R). The simplest way to release a grabbed window is to destroy it, but you can also tkgrab.release.
Do not use a global grab. They're easy to get wrong and can cause you a lot of grief. (If you insist, you're strongly recommended to make mouse activity cancel it and to test very thoroughly. Locking up your display is not a pleasant experience!) The default local grabs are less of a problem, since you can switch to another program and kill off a stuck app if necessary.
The full documentation for Tk (and Tcl) is online; pick the version of the docs for the version of the library that you're using, probably 8.5, hopefully 8.6 ('cos it has some nice extras) and possibly 8.4 (old skool!) As the R documentation for tcltk says, you can invoke anything in Tcl or Tk through tcl(…), passing in the words of the command name and arguments as many strings… (Tcl is a naturally var-args language and uses that extensively.) The limited scope of the default convenience mapping should not hinder you substantively.
General advice, not so closely related to your question
Most Tk programmers try to write their code to not lock users out that way if possible. You get a better user experience if you can keep the GUI responsive and instead just temporarily disable (via the state option on most reactive widgets) the parts that would otherwise trigger reentrancy problems for the duration. (The long-running processing might be also event-driven, or put in another thread, or even delegated to a sub-process. Just remember, Tk GUIs are strictly single threaded — the implementation assumes this very deeply, though it's possible to have wholly independent apps in different threads, if rather hairy to get working right — so you've got to come back to the GUI thread to update anything in the GUI.)

Related

What's the idea behing W-, P- and I-files?

I'm working with appBuilder and procedure editor in Progress Release 11.6.
As mentioned in some previous questions, regularly I'm having problems with the appBuilder, not wanting to open files, corrupting them (deleting parts of source code), ..., one of the reasons now seems to be the limit that a procedure cannot exceed 32K, comments included.
At first I thought "Are we back in the stone age?", pardon my reaction.
But now I start thinking that we are completely abusing the whole concept, therefore I'd like to show my view on W-, P- and I-files, please confirm (or correct):
W-files are meant only to contain GUI definitions, like a form with some frames, buttons, fill-in fields, ..., any real programming needs to be done in P-files.
P-files contain the real intelligence: there the procedures and functions are elaborated, that can be used by the rest of the P-files, or finally by the W-files.
I-files are just there to include general behaviour.
Let me give you an example:
W-file:
DEFINE VARIABLE combo_information VIEW-AS COMBOBOX /* with some information on the content, if this is static */
...
ON CHOOSE OF combo_information DO:
RUN very_large_procedure.
END.
...
{about.i} /* see here-after */
...
P-file:
PROCEDURE very_large_procedure:
DO /* a lot */
END.
I-file (about.i):
/* Describes the help-about menu item */
While working like this (only putting the GUI-related things in the W-file and let the "real" programming be done in the P-files), the mentioned 32K limit will never be reached. In top of that, adding a procedure can be done easily, the appBuilder will not delete it as the appBuilder won't ever open the P-file.
Is my view correct (and what about the I-files)?
In case yes: one technical question: how can I launch a procedure from a P-file inside a W-file? (Obviously, the mentioned example can't work as in the W-file I did not mention where to look for the very_large_procedure)
The naming is arbitrary and you may occasionally find other extensions being used. Having said that:
"W" is for "window", it is supposed to contain code that is related to making a GUI work. It is very often abused to contain any sort of code. It is usually abused in that way by people who learned to code on the app builder or who have never coded on anything but Windows.
"P" is for "Progress" and retconned to "Procedure". It was the standard back in the old days prior to the appearance of Windows GUI code. Any "headless" code or character mode code would typically go into a dot-p file.
"I" is for "include". This is a very old school way to create reusable code snippets and common "header files". Include files are commonly parameterized. Potentially with either named or positional arguments.
Another major extension is ".cls" files. These are for OO4GL classes (OpenEdge 10 and above).
Launching procedures is acheived by running them:
RUN myproc.p.
or
RUN guiproc.w.
Or, if by "launch", you mean "start a session" then you use the "-p procedureName" startup parameter along with prowin32.exe or prowin.exe for Windows GUI code or _progres.exe for batch or character code.

Benefits of using pyuic vs uic.loadUi

I am currently working with python and Qt which is kind of new for me coming from the C++ version and I realised that in the oficial documentation it says that an UI file can be loaded both from .ui or creating a python class and transforming the file into .py file.
I get the benefits of using .ui it is dynamically loaded so no need to transform it into python file with every change but what are the benefits of doing that?, Do you get any improvements in run time? Is it something else?
Thanks
Well, this question is dangerously near to the "Opinion-based" flag, but it's also a common one and I believe it deserves at least a partial answer.
Conceptually, both using the pyuic approach and the uic.loadUi() method are the same and behave in very similar ways, but with some slight differencies.
To better explain all this, I'll use the documentation about using Designer as a reference.
pyuic approach, or the "python object" method
This is probably the most popular method, especially amongst beginners. What it does is to create a python object that is used to create the ui and, if used following the "single inheritance" approach, it also behaves as an "interface" to the ui itself, since the ui object its instance creates has all widgets available as its attributes: if you create a push button, it will be available as ui.pushButton, the first label will be ui.label and so on.
In the first example of the documentation linked above, that ui object is stand-alone; that's a very basic example (I believe it was given just to demonstrate its usage, since it wouldn't provide a lot of interaction besides the connections created within Designer) and is not very useful, but it's very similar to the single inheritance method: the button would be self.ui.pushButton, etc.
IF the "multiple inheritance" method is used, the ui object will coincide with the widget subclass. In that case, the button will be self.pushButton, the label self.label, etc.
This is very important from the python point of view, because it means that those attribute names will overwrite any other instance attribute that will use the same name: if you have a function named "saveFile" and you name the button "saveFile", you won't have any [direct] access to that instance method any more as soon as setupUi is returned. In this case, using the single inheritance method might be helpful - but, in reality, you could just be more careful about function and object names.
Finally, if you don't know what the pyuic generated file does and what's it for, you might be inclined to use it to create your program. That is wrong for a lot of reasons, but, most importantly, because you might certainly realize at some point that you have to edit your ui, and merging the new changes with your modified code is clearly a PITA you don't want to face.
I recently answered a related question, trying to explain what happens when setupUi() is called in much more depth.
Using uic.loadUi
I'd say that this is a more "modular" approach, mostly because it's much more direct: as already pointed out in the question, you don't have to constantly regenerate the ui files each time they're modified.
But, there's a catch.
First of all: obviously the loading, parsing and building of an UI from an XML file is not as fast as creating the ui directly from code (which is exactly what the pyuic file does within setupUi()).
Then, there is at least one relatively small bug about layout contents margins: when using loadUi, the default system/form margins might be completely ignored and set to 0 if not explicitly set. There is a workaround about that, explained in Size of verticalLayout is different in Qt Designer and PyQt program (thanks to eyllanesc).
A comparison
pyuic approach
Pros:
it's faster; in a very simple test with a hundred buttons and a tablewidget with more than 1200 items I measured the following bests:
pyuic loading: 33.2ms
loadUi loading: 51.8ms
this ratio is obviously not linear for a multitude of reasons, but you can get the idea
if used with the single inheritance method, it can prevent accidental instance attribute overwritings, and it also means a more "contained" object structure
using python imports ensures a more coherent project structure, especially in the deployment process (having non-python files is a common source of problems)
the contents of those files are actually instructive, especially for beginners
Cons:
you always must remember to regenerate the python files everytime you update an ui; we all know how easy is to forget an apparently meaningless step like this might be, expecially after hours of coding: I've seen plenty of situations for which people was banging heads on desks (hopefully both theirs) for hours because of untraceable issues, before realizing that they just forgot to run pyuic or didn't run it on the right files; my own forehead still hurts ;-)
file tracking: you have to count two files for each ui, and you might forget one of them along the way when migrating/forking/etc, and if you forgot an ui file it possibly means that you have to recreate it completely from scratch
n00b alert: beginners are commonly led to think that the generated python file is the one to be used to create their programs, which is obviously wrong; unfortunately, the # WARNING! message is not clear enough (I've been almost begging the head PyQt developer about this); while this is obviously not an actual problem of this approach, right now it results in being so
some of the contents of a pyuic generated files are usually unnecessary (most importantly, the object name, which is used only for specific cases), and that's pretty obvious, since it's automatically generated ("you might need that, so better safe than sorry"); also, related to the issue above, people might be led to think that everything pyuic creates is actually needed for a GUI, resulting in unnecessary code that decreases its readability
loadUi method
Pros:
it's direct and immediate: you edit your ui on Designer, you save it (or, at least, you remember to do it...), and when you run your code it's already there; no fuss, no muss, and desks/foreheads are safe(r)
file tracking and deployment: it's just one file per ui, you can put all those ui files in a separate folder, you don't have to do anything else and you don't risk to forget something on the way
direct access to widgets (but this can be achieved using the multiple inheritance approach also)
Cons:
the layout issue mentioned above
possible instance attribute overwriting and no "ui" object "containment"
slightly slower loading
path and deployment: loading is done using os relative paths and system separators, so if you put the ui in a directory different from the py file that loads that .ui you'll have to consider that; also, some package managers use to compress everything, resulting in access errors unless paths are correctly managed
In my opinion, all considering, the loadUi method is usually the better choice. It doesn't distract me, it allows better conceptual compartmentation (which is usually good and also follows a pattern similar to MVC much more closely, conceptually speaking) and I strongly believe it as being far less prone to programmer errors, for a multitude of reasons.
But that's clearly a matter of choice.
We should also and always remember that, like every other choice we do, using ui files is an option.
There is people who completely avoids them (as there is people who uses them literally for anything), but, like everything, it all and always depends on the context.
A big benefit of using pyuic is that code autocompletion will work.
This can make programming much easier and faster.
Then there's the fact that everything loads faster.
pyuic6-Tool can be used to automate the call of pyuic6 when the application is run and only convert .ui files when they change.
It's a little bit longer to set up than just using uic.loadUi but the autocompletion is well worth it if you use something like PyCharm.

Getting list of windows in Tk and destroying specific ones (R)

I was wondering if it is possible to get a list of windows in Tk, and destroy specific ones. I am working in R using the tcltk interface, and am calling a function written by someone else a long time ago (that I cannot edit) which is producing additional windows that I don't want.
From the documentation here, it seems that new Toplevel windows are children of .TkRoot by default. I know that Python has a winfo_children method, which I was thinking of trying to call on .TkRoot but I don't think that method is implemented in the tcltk library. I tried using tcl("winfo", "children", .TkRoot) but I am getting an error: [tcl] bad window path name "{}" (I'm not familiar with actual tcl, so I'm probably messing this command up).
Additionally, if there is a way to call winfo children, what's the best way to process the result to identify specific windows and then destroy them?
Looking at the R sources, I see that you should be doing:
tkwinfo("children", .TkRoot)
Except that I think that won't work either, as .TkRoot doesn't have a corresponding widget on the Tk side of things. Instead, use the string consisting of a single period (.) as the root of the search; that's the name for the initial window on the Tcl side of things. And I suspect that you'll just get back a raw Tcl list of basic Tk widget names without the R wrapping as I just can't see where that conversion is applied…
Be aware that the results may include widgets that you don't expect, and that you need to call it on every window recursively if you want to find everything.

Use Julia to perform computations on a webpage

I was wondering if it is possible to use Julia to perform computations on a webpage in an automated way.
For example suppose we have a 3x3 html form in which we input some numbers. These form a square matrix A, and we can find its eigenvalues in Julia pretty straightforward. I would like to use Julia to make the computation and then return the results.
In my understanding (which is limited in this direction) I guess the process should be something like:
collect the data entered in the form
send the data to a machine which has Julia installed
run the Julia code with the given data and store the result
send the result back to the webpage and show it.
Do you think something like this is possible? (I've seen some stuff using HttpServer which allows computation with the browser, but I'm not sure this is the right thing to use) If yes, which are the things which I need to look into? Do you have any examples of such implementations of web calculations?
If you are using or can use Node.js, you can use node-julia. It has some limitations, but should work fine for this.
Coincidentally, I was already mostly done with putting together an example that does this. A rough mockup is available here, which uses express to serve the pages and plotly to display results (among other node modules).
Another option would be to write the server itself in Julia using Mux.jl and skip server-side javascript entirely.
Yes, it can be done with HttpServer.jl
It's pretty simple - you make a small script that starts your HttpServer, which now listens to the designated port. Part of configuring the web server is that you define some handlers (functions) that are invoked when certain events take place in your app's life cycle (new request, error, etc).
Here's a very simple official example:
https://github.com/JuliaWeb/HttpServer.jl/blob/master/examples/fibonacci.jl
However, things can get complex fast:
you already need to perform 2 actions:
a. render your HTML page where you take the user input (by default)
b. render the response page as a consequence of receiving a POST request
you'll need to extract the data payload coming through the form. Data sent via GET is easy to reach, data sent via POST not so much.
if you expose this to users you need to setup some failsafe measures to respawn your server script - otherwise it might just crash and exit.
if you open your script to the world you must make sure that it's not vulnerable to attacks - you don't want to empower a hacker to execute random Julia code on your server or access your DB.
So for basic usage on a small case, yes, HttpServer.jl should be enough.
If however you expect a bigger project, you can give Genie a try (https://github.com/essenciary/Genie.jl). It's still work in progress but it handles most of the low level work allowing developers to focus on the specific app logic, rather than on the transport layer (Genie's author here, btw).
If you get stuck there's GitHub issues and a Gitter channel.
Try Escher.jl.
This enables you to build up the web page in Julia.

Using a pyqt widget from a linearly running console application

My scenario here is the following: I am using a pyqt widget to display a solid color fullscreen on a second display and observe this display with a camera that is continuously capturing images. I do some processing with the images and this is the data I am interested in. This works great when used interactively with ipython and matplotlib using the qt4agg backend like so
% ipython -pylab
# ... import PatternDisplay, starting camera
pd = PatternDisplay(); pd.show(); pd.showColor(r=255,g=255,b=255)
imshow(cam.current_image)
I need a similar behavior now in a console script though: it should display the PatternDisplay widget, capture an image, than change the color on the PatternDisplay and take a new image and so on.
The problem is now that the PatternDisplay is never updated/redrawn in my script, likely because PyQt never gets a chance to run it's event queue. I had no luck trying to move the linear worker part of my script into a QThread because I cannot communicate with the PatternDisplay Widget from another Thread any longer. I tried to replicate the implementation of ipython/matplotlib, but I didn't fully understand it, it is quite complicated - it avoids running the QApplication main loop via monkey patching and somehow moves QT into it's own thread. It then checks periodically using a QTimer if a new command was entered by the user.
Isn't there an easy way to achieve what I want to do? I am gladly providing more information if needed. Thanks for any help!
What you need is easier than IPython's job - IPython makes the Qt application and the command line interactive at the same time.
I think the way to do it in Qt is to use a timer which fires at regular intervals, and connect the signal to the 'slot' representing your function that gets the new image and puts it in the widget. So you're pulling it in from the event loop, rather than trying to push it.
I've not used Qt much, so I can't give specifics, but the more I think about it, the more I think that's the right way to do it.
I solved the same problem (i.e. interactive ipython console in terminal, and GUI thread running independently) in the following way with ipython 0.10 (code here)
1. Construct QApplication object, but don't enter its event loop explicitly
2. Run the embedded IPython instance
3. Run the UI code you need by instantiating your window and calling show() on it (like here with the yade.qt.Controller(), which I aliased to F12. (I did not find a way how to ask the embedded shell to run a command at the start of the session, as if the user had typed it)
(You can also show() your window first, then run the embedded ipython. It will provide event loop for Qt.)
(BTW I also tried running Qt4 from a background thread (using both python threads module, and Qt4.QThreads), but it refuses to run in such way stubbornly. Don't bother going that way.)
The disadvantage is that UI will be blocked while ipython is busy. I hope to finding something better for 0.11, which should have much better threading facilities (I asked on ipython-users about how to unblock the UI).
HTH, v.

Resources