aborting Windows IME composition / clearing composition string - windows

I'm having trouble aborting IME composition on Windows.
I'm handling WM_IME_STARTCOMPOSITION and positioning my candidate window, and WM_IME_COMPOSITION as I press a key to start composing as you'd expect. I'm then handling WM_IME_ENDCOMPOSITION at the end and normal use cases are fine.
However, my problem is when I change focus inside of the application. I don't receive WM_IME_ENDCOMPOSITION so I have to deal with this situation manually. What I am doing is this:
ImmNotifyIME( himc, NI_COMPOSITIONSTR, CPS_CANCEL, 0 );
ImmNotifyIME( himc, NI_CLOSECANDIDATE, 0, 0 );
The candidate list correctly disappears, but the composition string isn't cleared. If I then call ImmGetCompositionString with GCS_COMPSTR, it's still there. Therefore if I give focus back, receive WM_IME_STARTCOMPOSITION and the first WM_IME_COMPOSITION - I end up inheriting the previous composition string, which I don't want. I want to start afresh.
ImmSetCompositionString() looks also like it would work but I can't figure out how to get it to clear the string.
Does anyone have any suggestions? MSDN seems to suggest that the calls to ImmNotifyIME() would do the job, but I must be missing something.

You may clear composition with this:
ImmSetCompositionStringW(himc, SCS_SETSTR, L"", sizeof(wchar_t), L"", sizeof(wchar_t));
In addition, in my application, when input loses focus I release input context:
ImmReleaseContext(hwnd, himc);
And get it again when focus gained:
ImmGetContext(hwnd);

Related

How to display debug info or console.log equivalent in Lua

I am creating many games using Lua and LOVE2D, but whenever I implement a new function and want to test it out, or simply want to know a value of a variable in Lua, I either display it on the game screen or just hope that it works.
Now my question is...
IS THERE A WAY TO DISPLAY SOME INFO, such as A VARIABLE VALUE or something else into the terminal or somewhere else? Just like console.log in javascript which displays some content in the javascript console in the browser. So, is there a way to do this is Lua?? using LOVE2D?
I am using a Mac, so I have a terminal and not a command prompt. Is there a way to display some content there? Anywhere else would also be fine, I just need to see if those values are as expected or not.
Use a conf.lua file to enable the console, then you should be able to use a standard print(). You can read the wiki entry here.
Note: You have to run Lua and Love2D via the terminal for this to work. Running Lua and Love2D like this is required for the print statements to show:
/Applications/love.app/Contents/MacOS/love "/Users/myuser/Desktop/love2d-test-proj"
You just need to add a conf.lua file to the same location where your main.lua. Your file may be as simple as this:
function love.conf(t)
t.console = true
end
But feel free to copy the whole configuration file from the above link and edit what you need.
I can't be completely sure about this, because I have no access to Mac, but the console is disabled by default and even on Windows, no prints are shown until you turn it on.
Alternatively You can also display debug info in the game itself like some games do.
What I like to do is add something like debugVariable = {} for logging events that happen in each loop and debugPermanent = {} for events that happen rarely. Possibly add convenience functions for writing to the variables:
function debugAddVariable(str)
table.insert(debugVariable, str)
end
--..and similarly for debugPermanent
Now a function to draw our debug info:
function debugDraw()
love.graphics.push() --remember graphics state
love.graphics.origin() --clear any previous transforms
love.graphics.setColor(--[[select color for debug info]])
love.graphics.setFont(--[[select font for debug info]])
for i, v in ipairs(debugPermanent) do
love.graphics.print(v)
love.graphics.translate(0, --[[fontHeight]])
end
for i, v in ipairs(debugVariable) do
love.graphics.print(v)
love.graphics.translate(0, --[[fontHeight]])
end
debugVariable = {} --clear debugVariable to prepare it for the next loop
love.graphics.pop() --recall graphics state
end
And we just call this draw function at the end of our love.draw() and the texts should appear.
Obviously, this method can be refined further and further almost infinitely, displaying specific variables, and adding graphs for some other variables to clarify the information you want to show, but that's kind of outside of the scope of the question.
Lastly Feel free to check here for debug libraries submitted by users.

Change the way an object is displayed in debugger/inspector variable-value table

I would like to know if there is a message I can override in Pharo so that my custom classes display more descriptive information in the inspector/debuger much like simple variable types do, like Integers or Strings. For instance:
Instead of that, I would like it to show a more custom and informative description consisting of its internal variales so as to have a tighter/tidier view of the variables instead of having to click on it and open another chart (therefore losing sight of the information on the previous chart). I know you can increase the amount of charts shown below, but that is not the point of the question. I would like to achieve something like this:
I have browsed the pharo forums and found nothing, I have also tried overriding over 30 methods hoping that one of them changed the output. Only the class message seemed to change the output, but I could only return an instance of Metaclass and besides messing with this message would break a lot of stuff. Finally I tried to reverse engineer the debugger and then the inspector to see at which point is the table constructed and what values are used or which messages are sent to build said values, but it was just too much for me, the callstack kept growing and I couldn't even scratch the surface.
Luckily, doing this in any Smalltalk is very easy. Types inherited from Object are expected to answer to the message printString, and ultimately printOn: aStream. Those messages are expected to give a description of the object. So, you should just override printOn: in your class (printString uses printOn:) and all the browsers and inspectors will automatically use it. There other possibilities in Pharo, if you want to provide more complex information in different tabs, but I think printOn: will suffice for you.
An example would be:
MyPoint>>printOn: aStream
aStream nextPut: ${.
x printOn: aStream.
aStream nextPutAll: ', '
y printOn: aStream.
aStream nextPut: $}
In Smalltalk, every time you observe something you don't like or understand, you ask the question: Which message is doing this?
In your case, the question would be: Which message creates the string a MyPoint that I see everywhere?
Next, to answer your question you need to find a good place for inserting a halt and then debug from there until you find the culprit. To do this just find the simplest expression that would reproduce the issue and debug it. In your case the right-click command in the Playground will do. So,
Write and select (MyPoint on: 14 and: -5) halt in a Playground.
Right-click and issue the Print it command (I'm assuming you already checked that this command produces the string 'a MyPoint').
Debug
Go over the evaluation of #DoIt, which answers the result
Continue this way alternating between Into and Over to make sure you follow the result to where it's being taken
Eventually you will reach the implementation of Object >> #printString. Bingo!
Now you can open a System Browser and take a look at this method, study how it's been implemented in different classes, etc. Your investigation should show you that the most basic message for printing is #printOn:. You may also want to take a look at other implementors so to better understand what people usually do. (Bear in mind that writing good #printOn:s is a minimalist art)
Overriding printOn: will work for simple cases where you want to just change description.
Pharo allows a lot more than that!
Due the extensible (moldable) nature of our inspector, you do not need to override a method to get your own visualisation of the object.
For example, look this array visualisation:
This is obtained adding this method to Collection:
gtInspectorItemsIn: composite
<gtInspectorPresentationOrder: 0>
^ composite fastList
title: 'Items';
display: [ self asOrderedCollection ];
beMultiple;
format: [ :each | GTObjectPrinter asTruncatedTextFrom: each ];
send: [ :result |
result
ifNil: [ nil ]
ifNotNil: [ result size = 1
ifTrue: [ result anyOne ]
ifFalse: [ self species withAll: result ]
]
]
if you browse for senders of gtInspectorPresentationOrder: you will see there are already a lot of special visualisations in the image.
You can take those as an example on how to create your own, adapted exactly to what you need :)

EM_UNDO does not work after programmatically writing to rich edit

Working in C++ Builder 10 Seattle on Win7-64.
I have a TRichEdit control into which I can write from a button click event:
MyRichEdit->SelText = t_string;
I want to be able to undo that change, so I have a menu item with shortcut Ctrl+Z that does this:
SendMessage(MyRichEdit->Handle, EM_UNDO, 0, 0);
The Undo works as expected if I have typed into the rich edit, but not to undo the programmatically assigned "paste".
I had similar code in an old application that was built with Borland C++ Builder v6, and it works there.
My question then is: Should the above code undo the write-to-SelText? Or is there something else I need to do?
The implementation of the SelText setter looks like this:
procedure TCustomEdit.SetSelText(const Value: string);
begin
SendTextMessage(Handle, EM_REPLACESEL, 0, Value);
end;
The documentation for EM_REPLACESEL says:
Parameters
wParam
Specifies whether the replacement operation can be undone. If this is
TRUE, the operation can be undone. If this is FALSE , the operation
cannot be undone.
lParam
A pointer to a null-terminated string containing the replacement text.
The VCL is sending 0 which is FALSE and so the operation cannot be undone. You will need to avoid using SelText and instead send the EM_REPLACESEL directly, passing TRUE as wParam.
I examined the source code for the Delphi 6 VCL and it too always passes 0 for wParam when sending this message, so I would have expected the old versions of the VCL to behave in the same way. All the same, you now know how to resolve the issue.
As an aside, you can replace sending of EM_UNDO with a call to MyRichEdit->Undo() which does exactly the same thing.

Swift: using NSRunningApplication

I'm trying to activate a running application, but can't seem to get the app.activateWithOptions call correct as each of the four attempts below result in compile time errors.
import AppKit
var ws = NSWorkspace.sharedWorkspace()
var apps = ws.runningApplications
var app :NSRunningApplication
for app in apps {
if (app.activationPolicy == NSApplicationActivationPolicy.Regular) {
app.activateWithOptions(options: ActivateIgnoringOtherApps)
app.activateWithOptions(options: NSApplicationActivateIgnoringOtherApps)
app.activateWithOptions(options: NSRunningApplication.ActivateIgnoringOtherApps)
app.activateWithOptions(options: NSRunningApplication.NSApplicationActivateIgnoringOtherApps)
println(app.localizedName)
}
}
The declaration var app : NSRunningApplication is pointless, because the app in the for...in line declares a different app. You should just delete that line, as it is misleading you and is utterly pointless and confusing.
Thus, it is that app, the one in the for...in that you need to specify the type of. You won't get any further in this attempt to compile until you fix that:
for app in apps as [NSRunningApplication] {
Now you can begin to fix your errors, one by one. I'll just give you a hint for the first one; it should be:
app.activateWithOptions(.ActivateIgnoringOtherApps)
The remaining three lines are left as an exercise for the reader! Even then you will still be in some trouble, though, because you are not combining the options - instead, you are activating the same app four separate times, which is silly and not at all what you want. You should combine the options first and then active the app once.
On the whole, it looks from your code as if you do not know Swift at all. You really should stop and learn it before you try to use it. Otherwise you'll just be flailing (as you clearly are now).
Thanks for the answer Matt. I'll add that if you are looking for just your application (rather than you can add a line before activating it. The following two lines will assign your application to the constant "app" and then activates it. This is useful for when yo want to get an NSAlert on the screen from an app running in the background.
let app = NSRunningApplication.currentApplication()
app.activateWithOptions(.ActivateIgnoringOtherApps)
let user_choice = alert.runModal()

What's so bad about using button captions as variables in VB6?

I received some justified critical feedback on my last question (How to gracefully exit from the middle of a nested subroutine when user cancels?) for using the caption of a command button as a state variable. I did it because it's efficient, serving two or three purposes at once with very little code, but I understand how it could also cause problems, particularly in the slightly sloppy way I originally presented it.
I feel like this deserves its own discussion, so here's the same idea cleaned up a bit and modified to do it "right" (which basically means defining the strings in a single place so your code won't start failing because you simply changed the text of a command button). I know my variable and control naming convention is poor (OK, nonexistent), so apologies in advance. But I'd like to stay focused on the caption as state variable discussion.
So here we go:
' Global variables for this form
Dim DoTheThingCaption(1) As String
Dim UserCancel, FunctionCompleted As Boolean
Private Sub Form_Initialize()
' Define the possible captions (is there a #define equivalent for strings?)
DoTheThingCaption(0) = "Click to Start Doing the Thing"
DoTheThingCaption(1) = "Click to Stop Doing the Thing"
' Set the caption state when form initializes
DoTheThing.Caption = DoTheThingCaption(0)
End Sub
Private Sub DoTheThing_Click() ' Command Button
If DoTheThing.Caption = DoTheThingCaption(0) Then
UserCancel = False ' this is the first time we've entered this sub
Else ' We've re-entered this routine (user clicked on button again
' while this routine was already running), so we want to abort
UserCancel = True ' Set this so we'll see it when we exit this re-entry
DoTheThing.Enabled = False 'Prevent additional clicks
Exit Sub
End If
' Indicate that we're now Doing the Thing and how to cancel
DoTheThing.Caption = DoTheThingCaption(1)
For i = 0 To ReallyBigNumber
Call DoSomethingSomewhatTimeConsuming
If UserCancel = True Then Exit For ' Exit For Loop if requested
DoEvents ' Allows program to see GUI events
Next
' We've either finished or been canceled, either way
' we want to change caption back
DoTheThing.Caption = DoTheThingCaption(0)
If UserCancel = True Then GoTo Cleanup
'If we get to here we've finished successfully
FunctionCompleted = True
Exit Sub '******* We exit sub here if we didn't get canceled *******
Cleanup:
'We can only get to here if user canceled before function completed
FunctionCompleted = False
UserCancel = False ' clear this so we can reenter later
DoTheThing.Enabled = True 'Prevent additional clicks
End Sub '******* We exit sub here if we did get canceled *******
So there it is. Is there still anything really that bad about doing it this way? Is it just a style issue? Is there something else that would give me these four things in a more desirable or maintainable way?
Instant GUI feedback that user's button press has resulted in action
Instant GUI feedback in the location where user's eyes already are on how to CANCEL if action is not desired
A one-button way for users to start/cancel an operation (reducing the amount of clutter on the GUI)
A simple, immediate command button disable to prevent multiple close requests
I can see one concern might be the close coupling (in several ways) between the code and the GUI, so I could see how that could get to be a big problem for large projects (or at least large GUIs). This happens to be a smaller project where there are only 2 or 3 buttons that would receive this sort of "treatment".
The single biggest problem with this technique is that it uses a string as a boolean. By definition, a boolean variable can have only two states, while a string can have any number of states.
Now, you've mitigated the danger inherent in this somewhat by relying on an array of predefined strings to define allowed values for the command button text. This leaves a handful of lesser issues:
Logic is less-than-explicit regarding current and available states (there are actually four possible states for the form: not-started, started, completed, started-but-canceling) - maintenance will require careful observation of the potential interactions between button text and boolean variable states to determine what the current state is / should be. A single enumeration would make these states explicit, making the code easier to read and understand, thereby simplifying maintenance.
You're relying on the behavior of a control property (button text) to remain consistent with that of the exposed property value type (string). This is the sort of assumption that makes migrating old VB6 code to newer languages / platforms absolute hell.
String comparison is much, much slower than a simple test of a boolean variable. In this instance, this won't matter. In general, it's just as easy to avoid it.
You're using DoEvents to simulate multi-threading (not directly relevant to the question... but, ugh).
The biggest issue i've come accross when working on (very old) code like this [button captions as variables] is that globalisation is a nightmare.... I had to move a old vb6 app to use English and German... it took weeks, if not months.
You're using goto's as well..... a bit of refactoring needed perhaps to make the code readable??
**Edit in response to comments
I'd only use a goto in vb6 at the top of each proc;
on error goto myErrorHandler.
then at the very bottom of the proc i'd have a one liner that would pass err to a global handler, to log the error.
Ignoring the general architecture/coupling problems because you are aware of those issues, one problem with your approach is because VB6 controls do magic stuff when you set properties.
You may think you are just setting a property but in many cases you are causing events to fire also. Setting a checkbox value to true fires the click event. Setting the tabindex on a tab control causes a click event. There are many cases.
If I remember correctly I also think there are scenarios where if you set a property, and then read it immediately, you will not see the update. I believe a screen refresh has to occur before you see the new value.
I have seen too much horrible VB6 code that uses control properties as storage. If you ever find this kind of code you will recognize it because it is scattered with redundant calls to Refresh methods, DoEvents and you will frequently see the UI get hung. This is often caused by infinite loops where a property is set, an event is fired and then another property is set and eventually someone writes a line of code that updates the first property again.
If those issues don't scare you enough then think of this. Some of us just are not that smart. I've been coding in VB6 for over 10 years and have personally written probably around 750K LOC and I keep staring at your example above and I find it very difficult to understand what it going on. Assume that all the people that will need to read your code in the future will be really dumb and make us happy by writing really simple looking code.
I think it's better to decouple the caption text from the state of processing. Also the goto's make it hard to read. Here is my refactored version...
Private Const Caption_Start As String = "Click to Start Doing the Thing"
Private Const Caption_Stop As String = "Click to Stop Doing the Thing"
Private Enum eStates
State_Initialized
State_Running
State_Canceled
State_Completed
End Enum
Private Current_State As eStates
Private Sub Form_Initialize()
DoTheThing.Caption = Caption_Start
Current_State = State_Initialized
End Sub
Private Sub DoTheThing_Click()
If Current_State = State_Running Then
'currently running - so set state to canceled, reset caption'
'and disable button until loop can respond to the cancel'
Current_State = State_Canceled
DoTheThing.Caption = Caption_Start
DoTheThing.Enabled = False
Else
'not running - so set state and caption'
Current_State = State_Running
DoTheThing.Caption = Caption_Stop
'do the work'
For i = 0 To ReallyBigNumber
Call DoSomethingSomewhatTimeConsuming
'at intervals check the state for cancel'
If Current_State = State_Canceled Then
're-enable button and bail out of the loop'
DoTheThing.Enabled = True
Exit For
End If
DoEvents
Next
'did we make it to the end without being canceled?'
If Current_State <> State_Canceled Then
Current_State = State_Completed
DoTheThing.Caption = Caption_Start
End If
End If
End Sub
Apart from removing the GOTos as DJ did in his answer, there is nothing really wrong about your approach. The button caption can have only two states, and you use those two states to define the flow in your code.
I have however two reasons why I would do it differently:
Your method creates problems when you want to translate your program into a different language (in my experience you should always plan for that), because the captions would change in another language
It goes against the principle of seperating the user interface from the program flow. This may not be an important thing for you, but when a program gets bigger and more complex, having a clear seperation of the UI from the logic makes things much easier.
To sum it up, for the case at hand your solution certainly works, and there is no reason why it shouldn't. But on the other hand experience has taught us that with more complex programs, this way can cause problems which you can easily avoid by using a slightly different approach.
Also, I think it is safe to assume that everybody who criticised your example did so because they made a simnilar choice at some point, and later realised that it was a mistake.
I know I did.
This ties your underlying algorithm to specific behavior in your UI. Now, if you want to change either one of them, you have to make changes to both. As your app grows in size, if you don't keep your changes local by encapsulating logic, maintenance will become a nightmare.
If anyone for any reason ever needs to work on your code, they won't find practices and conventions they are familiar and comfortable with, so the boundaries of functionality won't exist. In other words, you are headed in the wrong direction on the Coupling/Cohesion trail. Functionally integrating State management with the UI is the classic poster child for this issue.
Do you understand OOP at all? (Not a criticism, but a legitimate question. If you did, this would be a lot clearer to you. Even if it's only VB6 OOP.)
Localization has the biggest impact on the type of logic OP is presenting. As several people mentioned it - what if you need to translate the app into Chinese? And German? And Russian?
You'd have to add additional constants covering those languages too... pure hell. GUI data should remain what it is, a GUI data.
The method OP describes here reminded me what Henry ford said: "Any customer can have a car painted any color that he wants so long as it is black".

Resources