I'm writing a lua program that needs to call an external popup (let's call it Poppy) provided as an external library/API by another active programme (environment is Windows).
Poppy has a bad habit; when invoked, it pops up, does its work and then vanishes -- leaving the current Lua dialog hidden behind Poppy's parent program.
After calling Poppy, dlg.BRINGFRONT="YES" will bring the iup dialog dlg to the front.
Is there a technique to identify what dlg should be -- i.e. what was the topmost iup dialog before the external API was invoked?
I've read the iup documentation and can't see a way to do this. However, as I need to call Poppy in a large number of instances, I'd like to simplify the process of bringing the current dialog to the front.
I'm invoking Poppy thus:
local res = Poppy('INDI')
dlg.BRINGFRONT="YES"
return res
Inside the code that invokes Poppy in Windows, you can call:
HWND dlg_handle = GetActiveWindow();
Then when Poppy returns, call:
SetForegroundWindow(dlg_handle);
I've succeeded in doing this using the Winapi library and the following code:
winapi = require ("winapi")
currentwin = winapi.get_foreground_window()
--invoke Poppy here and wait for control to return
currentwin:set_foreground()
Related
So I've been trying to configure my Awesome WM config (rc.lua) to detect if my IBM model M13 is connected to my laptop upon login/reset. This is to change what the modkey should be since the M13 doesn't have a super key.
The following code makes sense to me and changes modkey within the function being made for the awful.spawn.easy_async function, but after finishing the modkey changes back to Mod4.
modkey = "Mod4"
awful.spawn.easy_async(
"xinput list",
function(stdout, stderr, reason, code)
local msg = "Regular keyboard Modkey = Super"
-- Debug notification that shows that the modkey is
-- at its default for the superkey Mod4
naughty.notify({
text = modkey,
timeout =7
})
if code ~= 0 then
msg = "Missing xinput to see devices\nModkey = Super"
elseif stdout:match("CHESEN") == "CHESEN" then
-- CHESEN is my PS/2 to USB adapter
msg = "IBM M13 detected\nModkey = Alt"
modkey = "Mod1" -- Sets new modkey to Alt
end
-- Notification message
naughty.notify({
text = msg,
timeout =7
})
end
)
-- Debug notification to verify key but key goes back to Mod4
naughty.notify({
text = modkey,
timeout =7
})
The output can be seen here. It doesn't print the notifications in order but the prints of Mod 4 are both of the debug prints.
Notification Output
I don't use Lua much aside from changing my configs from time to time so I'm having difficulty understanding how my global variable modkey can be changed with out it resetting. Other methods I tried was to have the function defined as a function I called setModKey to be passed as a parameter to easy_async and I tried setting modkey using _G to set it as _G.modkey, but I end up getting the same result.
Am I missing something fundamental to Lua or is this affected by how Awesome WM utilizes Lua? Any help will be very appreciated.
Use io.popen instead of awful.spawn.easy_async. Yes, normally using io.popen is really not recommended, but here the following happens:
Awesome starts
You call easy_async to capture the output of xinput list
Since it is async, your config continues to be loaded, so e.g. all your keybindings are set
easy_async does its job and you set modkey to something else.
This means that any keybinding which will be defined from now on use the new modkey, but all already-existing keybindings are not modified by this. So, basically nothing happens.
And for your debugging calls to naughty.notify: The one after the function is triggered first and only then, later, the inner one triggers. So it does not go back, but instead you first show the old value and only later the new one.
Probably looking for an answer to an age-old question, but I would like to block script execution. In my use-case blocking the browser is acceptable.
Also, in my use-case I am trying to do this from a Firefox extension, which means my code is "Chrome code", running in the browser environment.
This can easily be done by using a modal window, then programmatically closing the window. So this demonstrates that there is a blocking mechanism that exists.
Is there any way to achieve modal blocking without actually creating or opening the modal window? Some way to tap into the blocking mechanism used for modal windows?
I've done a lot of searching on this subject, but to no avail.
Using nsIProcess you can block the thread.
You can create an executable which has a sleep or usleep method or equivalent. Then run the process synchronously (nsIProcess.run) and set blocking argument to true.
Of course for portability you will need to create an executable appropriate for each platform you wish to support, and supply code for discrimination.
Basic code is something like the following. I have verified on 'nix (Mac OS X) this code to work, using a bash script with only the line sleep .03:
let testex = Components.classes["#mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsIFile);
testex.initWithPath("/Users/allasso/Desktop/pause.sh");
let process = Components.classes["#mozilla.org/process/util;1"]
.createInstance(Components.interfaces.nsIProcess);
process.init(testex);
let delay = 30; // convert this to milliseconds in the executable
process.run(true,[delay],1); // `run` method runs synchronously, first arg says to block thread
In an extension you probably would want to make your nsIFile file object more portable:
Components.utils.import("resource://gre/modules/FileUtils.jsm");
let testex = FileUtils.getFile("ProfD",["extension#moz.org","resources","pause.sh"]);
Of course keep in mind that Javascript is basically single-threaded, so unless you are blocking a thread spawned using Web Workers you will be freezing the entire UI during the sleep period (just like you would if you opened a modal window).
References:
https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIProcess
https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIFile
https://developer.mozilla.org/en-US/Add-ons/Code_snippets/File_I_O#Getting_special_files
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/basic_usage
OPTION 1
There is enterModalState and leaveModalState in nsIDOMWindowUtils here: MDN :: nsIDOMWindowUtils Reference
However they don't seem to work for me. This topic might explain why: nsIDOMWindowUtils.isInModalState() not working they topic says isInModalState is marked [noscript] which I see, but enterModalState and leaveModalState are not marked [noscript] I have no idea why it's not working.
What does work for me though is suppressEventHandling:
var utils = Services.wm.getMostRecentWindow('navigator:browser').
QueryInterface(Components.interfaces.nsIInterfaceRequestor).
getInterface(Components.interfaces.nsIDOMWindowUtils);
utils.suppressEventHandling(true); //set arg to false to unsupress
OPTION 2
You can open a tiny window with the source window as the window you want to make modal and as dialog but open it off screen. Its dialog so it wont show a new window the OS tab bars. However hitting alt+f4 will close that win, but you can attach event listeners (or maybe use the utils.suppressEventHandling so keyboard doesnt work in it) to avoid the closing till you want it closed. Here's the code:
var sDOMWin = Services.wm.getMostRecentWindow(null);
var sa = Cc["#mozilla.org/supports-array;1"].createInstance(Ci.nsISupportsArray);
var wuri = Cc["#mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
wuri.data = 'about:blank';
sa.AppendElement(wuri);
let features = "chrome,modal,width=1,height=1,left=-100";
if (PrivateBrowsingUtils.permanentPrivateBrowsing || PrivateBrowsingUtils.isWindowPrivate(sDOMWin)) {
features += ",private";
} else {
features += ",non-private";
}
var XULWindow = Services.ww.openWindow(sDOMWin, 'chrome://browser/content/browser.xul', null, features, sa);
/*
XULWindow.addEventListener('load', function() {
var DOMWindow = XULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
DOMWindow.gBrowser.selectedTab.linkedBrowser.webNavigation.stop(Ci.nsIWebNavigation.STOP_ALL);
DOMWindow.gBrowser.swapBrowsersAndCloseOther(DOMWindow.gBrowser.selectedTab, aTab);
//DOMWindow.gBrowser.selectedTab = newTab;
}, false);
*/
I'm trying to get tab complete within all open buffers and yasnippet to both work with the tab key. At the moment I can have one or the other. The following code is how I'm handling the yasnippet expand, but as I'm not a lisp programmer I cannot see the mistake here.
If it cannot expand the snippet I would like it to try and expand from the buffer.
;; Auto complete settings / tab settings
;; http://emacsblog.org/2007/03/12/tab-completion-everywhere/ <-- in the comments
(global-set-key [(tab)] 'smart-tab)
(defun smart-tab ()
"This smart tab is minibuffer compliant: it acts as usual in
the minibuffer. Else, if mark is active, indents region. Else if
point is at the end of a symbol, expands it. Else indents the
current line."
(interactive)
(if (minibufferp)
(unless (minibuffer-complete)
(dabbrev-expand nil))
(if mark-active
(indent-region (region-beginning)
(region-end))
(if (looking-at "\\_>")
(unless (yas/expand)
(dabbrev-expand nil))
(indent-for-tab-command)))))
First, I try to understand what the code does, and what you would like it does.
Your code
first checks if the point is in the minibuffer.
If so, then it tries to complete the minibuffer
if (in minibuffer) cannot complete it, it calls dabbrev-expand
else if the point is not in minibuffer
if some region is marked , it indents the region.
if no mark is active, it checks to see if the point is at the end of some word
if so, it checks is yasnippet can expand.
if yas cannot expand, it calls dabbrev-expand
if not, it tries to indent the current line
This is what your code does.
Your code fails due to yas/expand. This command does not return in case the expansion fails.
In case that this command fails, it checks the state of the variable yas/fallback-behavior. If this variable has the value call-other-command, as in your case, the failed yas expansion calls the command bound to the key kept in the variable yas/trigger-key.
In your case , this variable is TAB.
So: You are at the end of the word, You press TAB to complete it, this triggers the interactive smart-tab, which calls yas/expand which in case it fails to expand calls the bound function of TAB, and here is the infinite loop.
The Solution for your problem is to temporaily bound nil to yas/fallback-behavior in this smart-tab function.
Here is how to fix it:
(if (looking-at "\\_>")
(let ((yas/fallback-behavior nil))
(unless (yas/expand)
(dabbrev-expand nil)))
(indent-for-tab-command))
I have a problem which i suppose must be very common and most of you would have faced it.
I have written a program in lua, say main.lua which on receiving key event should modify the coordinates and display the geometry figure.
This lua code calls reg.c, where it kind of registers.
Now in reg.c i have a function engine which receives the key pressed and passes it to the lua function responsible for key handling.
But by the time key event comes, lua code is done with the registration and exits, thus the call from engine() becomes illegal memory access leading to segmentation fault.
Also i suppose we can't have lua call hanging in reg function, and call engine function from somewhere else.
Then what should be the solution, please guide me through this.
#jacob: here is the prototype of what i am trying to achieve:
function key_handler() //this function will get the latest key pressed from some other function
{
draw.image();
draw.geometry();
...
...
while(1)
{
//draw Points until some condition goes wrong
}
}
Now, once entered into key_handler, while he is busy drawing the points unless and until the failing condition occurs, i am unable to receive key pressed till that time.
I hope this explanation is much simpler and have made my point, and will help others to understand the problem.
I am really sorry, but i am not good at expressing or making others understand.
One more thing, i ahve followed the C syntax to explain, however this is completely implemented in lua
Your code snippet is still largely non-informative (ideally one should be able to just run your code in a stock Lua interpreter and see your problem). If you're describing a Lua problem, use Lua code to describe it.
However I'm beginning to see where you want to go.
The thing you need to could do is have a coroutine that's called in your key handler, which passes an argument back to your handler:
function isContinue() --just to simulate whatever function you use getting keypresses.
-- in whatever framework you're using there will probably be a function key_pressed or the like.
print('Initialize checking function')
while true do
print('Continue looping?')
local ans = io.read():match('[yY]')
local action
if not ans then
print('Do what instead?')
action = io.read()
if action:match('kill') then -- abort keychecker.
break
end
end
coroutine.yield(ans,action)
end
print('finalizing isContinue')
return nil,'STOP' -- important to tell key_handler to quit too, else it'll be calling a dead coroutine.
end
function key_handler()
local coro = coroutine.create(isContinue)
local stat,cont,action
while true do
print'Draw point'
stat,cont,action = coroutine.resume(coro)
if not stat then
print('Coroutine errored:',cont)
elseif not cont then
print('isContinue interrupted keyhandler')
print("We'll "..action.." instead.")
break
end
end
print('finalizing key_handler')
end
key_handler()
-- type something containing y or Y to continue, all else aborts.
-- when aborting, you get asked what to do instead of continuing,
--- with "kill" being a special case.
This should be self explanatory. You should probably take a good look at Programming in Lua, chapter 9: Coroutines.
The big difficulty (well, if you're not accustomed to collaborative threading) is that a coroutine should yield itself: it's not the calling function that's in charge of returning control.
Hope this helps you.
I'm working on Word automation and to get rid of "Call was rejected by callee" / "the message filter indicated that the application is busy" errors I implemented an IMessageFilter. The messagefilter works like a charm when I automate Word directly like:
Word.Documents.Open(...)
Document.SaveAs(...)
But when I call TOleContainer.DoVerb(ovPrimary), I still get errors when Word is displaying a modal dialog. Why does the MessageFilter not work with TOleContainers DoVerb methode?
"Call was rejected by callee" is what you always get when Word is in interactive state, ie displaying a dialog. This is not restricted to Word. It also happens with Excel, for example when the user was editing a cell. And it does not have to be obvious in the user interface either. When you start editing a cell, move focus to another application and come back to Excel, the UI doesn't give you a clue but it is still in "interactive" mode and will reject automation calls with the "Call was rejected by callee" error.
So basically when you automate Word in conjunction with user interaction (and not just with Word in a background process), you should be prepared to get and handle these errors.
Edit
If you want to know whether Excel or Word is in interactive mode before calling any other COM method: just ask the COM-server whether it is "Ready":
Result := _GetActiveOleObject('Excel.Application');
try
aSharedInstance := not VarIsClear(Result);
if aSharedInstance then
Version := Result.Version; // If this produces an exception, then use a dedicated instance.
// In case checking the version does not produce an exception, but Excel still isn't
// ready, we'll check that as well.
// By the way, for some unclear reason, partial evaluation does not work on .Ready,
// so we'll do it like this:
if aSharedInstance and (StrToIntDef(StringBefore('.', Version), 0) >= EXCEL_VERSION_2002) then
aSharedInstance := Result.Ready;
except
aSharedInstance := False;
end;
if not aSharedInstance then
Result := CreateOleObject('Excel.Application');
Update
Apparently Word doesn't have a "Ready" property (whoever said Microsoft was consistent?). In that case you need to determine its readiness yourself by calling a simple (and fast) property before the actual call, and assuming that when that throws an exception, Word isn't ready. In the above example the Version is retrieved before the Ready property. If that throws an exception, we just assume that the application (Excel in this case) isn't ready and proceed accordingly.
Something along the lines of:
while Tries <= MaxTries do
try
Version := Word.Version;
Tries := MaxTries + 1; // Indicate success
Word.TheCallYouReallyWantToDo;
except
Inc(Tries);
sleep(0);
end;
Note Word.Version does not throw an exception when a dialog is open, so that is no use for figuring out whether Word is ready. :( You will have to experiment to find one that does.
IMessageFilter doesn't handle all exceptions, for example, at some points, office applications 'suspend' their object model, at which point it cannot be invoked and throws: 0x800AC472 (VBA_E_IGNORE)
In order to get around this, you have to put your call in a loop and wait for it to succeed:
while(true)
{
try
{
office_app.DoSomething();
break;
}
catch(COMException ce)
{
LOG(ce.Message);
}
}
// continue after successful call
See here for more details.