How to close a window with Spec in Pharo - user-interface

I have a Spec window with several controls. When I click on the Ok button I want the window to be closed.
| m |
m := DynamicComposableModel new.
m instantiateModels: #(text TextModel ok OkToolbar).
m ok okAction: [ self close ].
m openWithSpecLayout: (SpecLayout composed
newColumn: [ : c | c add: #text ; add: #ok height: 30 ];
yourself).
I have tried sending delete and close, but none worked. How can I close the window?

you can do this:
| m |
m := DynamicComposableModel new.
m instantiateModels: #(text TextModel ok OkToolbar).
m ok okAction: [ m window close ].
m openWithSpecLayout: (SpecLayout composed
newColumn: [ : c | c add: #text ; add: #ok height: 30 ];
yourself).

Related

Right Clicking System Tray Icon then Clicking Option in that menu?

Trying to Right Click on tray icon then clicking on a specific item in that menu.
my code is:
#Include C:\Users\basil\Desktop\Scripting/trayicon.ahk
Process, Exist, Probkp.exe
If ErrorLevel <> 0
`Process, Close, Probkp.exe`
Sleep 1000
Run, D:\POS Software\Software\bkp\Probkp.exe
Tray_Refresh()
{
`WM_MOUSEMOVE := 0x200`
`HiddenWindows := A_DetectHiddenWindows`
`DetectHiddenWindows, On`
`TrayTitle := "AHK_class Shell_TrayWnd"`
`ControlNN := "ToolbarWindow323"`
`IcSz := 24`
`Loop, 2`
`{`
`ControlGetPos, xTray,yTray,wdTray,htTray, %ControlNN%, %TrayTitle%`
`y := htTray - 10`
`While (y > 0)`
`{`
`x := wdTray - IcSz/2`
`While (x > 0)`
`{`
point := (y << 16) + x
PostMessage, %WM_MOUSEMOVE%, 0, %point%, %ControlNN%, %TrayTitle%
x -= IcSz/2
`}`
`y -= IcSz/2`
`}`
`TrayTitle := "AHK_class NotifyIconOverflowWindow"`
`ControlNN := "ToolbarWindow321"`
`IcSz := 32`
`}`
`DetectHiddenWindows, %HiddenWindows%`
`Return`
}
Sleep 1000
TrayIcon_Button("Probkp.exe", "R")
which so far right clicks on the required tray icon but i can't figure out how to click on the required item in that menu.
Menu items are:
-Backup Now
-Server Settings
-Transfer Transactions / Period
-Transfer Transactions
-Transfer Data
-Download Transactions
-Reset Orders
-Exit
Required Item is "Transfer Transactions"
Also Tray Refresh works on windows 10 yet not on windows 7 due to this line of code:
`ControlNN := "ToolbarWindow323"`
Where windows 7 the code is "ToolbarWindow322" not "ToolbarWindow323"
Is there a way to make this dynamic for both windows?

wxhaskell: Updating a statusField using "on click" of a panel

I would like some advice on how to update a "statusField" after
clicking on a "panel".
The following program demonstrates the problem. The program draws two
frames. You can imagine the left frame to be some kind of drawing area
and the right frame contains the buttons "Red" and "Green".
After clicking on the button labeled "Red" the text of the statusField is
updated to "Current color: Red". The button labeled "Green" updates the text to "Current color: Green".
How to change the text of the statusField after the user clicked on
the left panel? E.g. change it to "You successfully clicked on the
drawing panel."
Why can't I do it in "on click" the same way as in "on command" for
the buttons? (See annotation in the source below.)
Thank you very much.
module Main where
import Graphics.UI.WX
-- | NOP (= No Operation)
data Command = Nop
| Red
| Green
deriving (Eq)
main :: IO ()
main
= start hello
hello :: IO ()
hello
= do currentCommand <- varCreate $ Nop -- current command performed on next click on "pDrawingarea"
status <- statusField [text := "Welcome."]
-- Frames and Panels
f <- frame [ text := "Demo"
, bgcolor := lightgrey ]
pButtons <- panel f [ bgcolor := lightgrey]
pDrawingarea <- panel f [ on paint := draw
, bgcolor := lightgrey
]
set pDrawingarea [on click := do drawingAreaOnClick status currentCommand pDrawingarea
-- set status [text := "User clicked on the panel."]
-- Problem: uncommenting the line above shows the problem
]
bRed <- button pButtons [text := "Red", on command := do varSet currentCommand Red
set status [text := "Current color: Red"]
]
bGreen <- button pButtons [text := "Green", on command := do varSet currentCommand Green
set status [text := "Current color: Green"]
]
set pButtons [ layout := column 1 [ hstretch.expand $ widget bRed
, hstretch.expand $ widget bGreen
]
]
set f [ statusBar := [status]
, layout := row 3 [
minsize (sz 600 500) $ stretch.expand $ widget pDrawingarea
, vstretch.expand $ rule 3 500
, minsize (sz 200 500) $ vstretch.expand $ widget pButtons
]
]
return ()
draw :: DC a -> Rect -> IO ()
draw dc viewArea
= do putStrLn "Imagine some code to repaint the screen."
drawingAreaOnClick :: statusField -> Var Command -> Panel () -> Point -> IO ()
drawingAreaOnClick sf command panel pt
= do c <- varGet command
case c of
Red -> do putStrLn "Imagine some code to do red painting"
Green -> do putStrLn "Imagine some code to do green painting"
After spending lots of time on this problem I found a solution.
The solution is to change the definition of
drawingAreaOnClick :: statusField -> Var Command -> Panel () -> Point -> IO ()
to
drawingAreaOnClick :: Textual x => x -> Var Command -> Panel () -> Point -> IO ()
Because "statusField" itself is a member of the class "Textual" I don't understand the problem.
For the sake of completeness I will mention that I also switched GHC verions.The original problem occurred with GHC 7.8.4 and the solution I found works with GHC 7.10.3. I can't say if the GHC version affects the problem.
For reference the complete working code:
module Main where
import Graphics.UI.WX
-- | NOP (= No Operation)
data Command = Nop
| Red
| Green
deriving (Eq)
main :: IO ()
main
= start hello
hello :: IO ()
hello
= do currentCommand <- varCreate Nop -- current command performed on next click on "pDrawingarea"
status <- statusField [text := "Welcome."]
-- not needed: currentStatus <- varCreate status
-- Frames and Panels
f <- frame [ text := "Demo"
, bgcolor := lightgrey ]
pButtons <- panel f [ bgcolor := lightgrey]
pDrawingarea <- panel f [ on paint := draw
, bgcolor := lightgrey
]
set pDrawingarea [on click := do drawingAreaOnClick status currentCommand pDrawingarea
-- set status [text := "User clicked on the panel."]
-- Problem: uncommenting the line above shows the problem
]
bRed <- button pButtons [text := "Red", on command := do varSet currentCommand Red
set status [text := "Current color: Red"]
]
bGreen <- button pButtons [text := "Green", on command := do varSet currentCommand Green
set status [text := "Current color: Green"]
--sf <- varGet currentStatus
-- set sf [text := "yyy"]
]
set pButtons [ layout := column 1 [ hstretch.expand $ widget bRed
, hstretch.expand $ widget bGreen
]
]
set f [ statusBar := [status]
, layout := row 3 [
minsize (sz 600 500) $ stretch.expand $ widget pDrawingarea
, vstretch.expand $ rule 3 500
, minsize (sz 200 500) $ vstretch.expand $ widget pButtons
]
]
return ()
draw :: DC a -> Rect -> IO ()
draw dc viewArea
= do putStrLn "Imagine some code to repaint the screen."
drawingAreaOnClick :: Textual x => x -> Var Command -> Panel () -> Point -> IO ()
drawingAreaOnClick sf command panel pt
= do c <- varGet command
set sf [text := "Drawing on the screen."]
case c of
Red -> do putStrLn "Imagine some code to do red painting"
Green -> do putStrLn "Imagine some code to do green painting"

How can I set an action to occur on a key release in xmonad?

How can I set an action to occur on a key release in xmonad?
I don't like menu bars and panels.
Instead of a panel like xmobar I want to have a full screen page of info, (time, currently selected window and workspace etc) appear when I hold down a key combo and then vanish when I let the keys go.
I could code the info page application myself.
I can set the info page to spawn on a key press.
I can not set anything to happen on a key release.
How can I set an action to occur on a key release?
I am considering extending xmonad myself to do this.
I hope I don't have to though because it'd be really annoying.
XMonad passes all received events, including KeyPress events, to the handleEventHook, so this code would be able to react on keyRelease events:
module KeyUp where
import Data.Monoid
import qualified Data.Map as M
import XMonad
import Control.Monad
keyUpEventHook :: Event -> X All
keyUpEventHook e = handle e >> return (All True)
keyUpKeys (XConf{ config = XConfig {XMonad.modMask = modMask} }) = M.fromList $
[ ((modMask, xK_v), io (print "Hi")) ]
handle :: Event -> X ()
handle (KeyEvent {ev_event_type = t, ev_state = m, ev_keycode = code})
| t == keyRelease = withDisplay $ \dpy -> do
s <- io $ keycodeToKeysym dpy code 0
mClean <- cleanMask m
ks <- asks keyUpKeys
userCodeDef () $ whenJust (M.lookup (mClean, s) ks) id
handle _ = return ()
You would use it like that in your xmonad.hs file:
handleEventHook = handleEventHook defaultConfig `mappend`
keyUpEventHook `mappend`
fullscreenEventHook
Unfortunately, this does not work yet: It will only react on KeyRelease events that have a corresponding entry in the regular keys configuration. This is due to grayKeys in XMonad.Main, grabbing only keys mentioned in keys. You can work-around this by defining a dummy action for every combination that you want to handle in KeyUp:
myKeys conf#(XConfig {XMonad.modMask = modMask}) = M.fromList $
...
, ((modMask , xK_v ), return ())
myStartupHook :: X ()
myStartupHook = do
XConf { display = dpy, theRoot = rootw } <- ask
myKeyCode <- io $ (keysymToKeycode dpy xK_Super_R)
io $ grabKey dpy (myKeyCode) anyModifier rootw True grabModeAsync grabModeAsync
spawn "~/ScriptsVcs/hideTint2.sh"
myHook :: Event -> X All
myHook e = do
case e of
ke#(KeyEvent _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) -> do
if ev_keycode ke == 134
then if ev_state ke == 0
then do
-- key has been pressed
spawn "~/ScriptsVcs/showTint2.sh"
else do
spawn "~/ScriptsVcs/hideTint2.sh"
else pure ()
_ -> pure ()
pure $ All True
The above is an example. Do take note that a 'key release' could occur with a modifier key (ev_state).

Error: 'Procedure or function 'getfoo2' expects parameter '#x', which was not supplied.' when it is supplied

I'm getting the error Procedure or function 'getfoo2' expects parameter '#x', which was not supplied.
When I set a breakpoint on line 156 in File1.fs and examine the contents of foo2, which is my DbCommand object, the parameters collection contains both of my parameters #x and #y. They both have the correct DbType and value set. So I have no idea where to look to find my problem. Is this a bug, or am I missing something somewhere else in my code? I have posted the sql for the database, my f# File1.fs, Program.fs, and the app.config. File1.fs comes before Program.fs in the project.
My system is:
Microsoft SQL Server Developer Edition (64-bit) version 10.0.4000.0
Windows 7 Professional SP1
Visual Studio 2010 SP1
Below is the source code:
stored proc, table, and sample data:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[getfoo2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[getfoo2]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[getfoo2]
#x int,
#y varchar(15)
AS
BEGIN
SET NOCOUNT ON;
select x,y,z from foo
where
x = #x
and
y = #y
END
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[foo]') AND type in (N'U'))
DROP TABLE [dbo].[foo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[foo](
[x] [int] NOT NULL,
[y] [varchar](15) NOT NULL,
[z] [datetime] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
insert into foo (x,y,z) values (1,'a',NULL)
insert into foo (x,y,z) values (1,'b','Jan 1 2001 12:00AM')
insert into foo (x,y,z) values (1,'c','Jan 2 2002 12:00AM')
insert into foo (x,y,z) values (2,'a','Feb 1 2001 12:00AM')
insert into foo (x,y,z) values (2,'b',NULL)
insert into foo (x,y,z) values (2,'c','Feb 2 2001 12:00AM')
insert into foo (x,y,z) values (3,'a','Mar 1 2001 12:00AM')
insert into foo (x,y,z) values (3,'b','Mar 2 2001 12:00AM')
insert into foo (x,y,z) values (3,'c',NULL)
GO
File1.fs
module File1
open System.Configuration
open System.Data.Common
open System.Data
type Direction =
| In
| Out
| Ref
| Return
type DbType =
| AnsiString of int
| AnsiStringFixedLength of int
| Binary of int
| Boolean
| Byte
| Currency
| Date
| DateTime
| DateTime2
| DateTimeOffset
| Decimal
| Double
| Guid
| Int16
| Int32
| Int64
| Object of int
| SByte
| Single
| String of int
| StringFixedLength of int
| Time
| UInt16
| UInt32
| UInt64
| VarNumeric of int
| Xml of int
type Db(cnnName:string) =
let config = ConfigurationManager.ConnectionStrings.[cnnName]
let factory = System.Data.Common.DbProviderFactories.GetFactory(config.ProviderName)
let (|HasSize|NoSize|) p =
match p with
// no size
| Boolean -> NoSize(System.Data.DbType.Boolean)
| Byte -> NoSize(System.Data.DbType.Byte)
| Currency -> NoSize(System.Data.DbType.Currency)
| Date -> NoSize(System.Data.DbType.Date)
| DateTime -> NoSize(System.Data.DbType.DateTime)
| DateTime2 -> NoSize(System.Data.DbType.DateTime2)
| DateTimeOffset -> NoSize(System.Data.DbType.DateTimeOffset)
| Decimal -> NoSize(System.Data.DbType.Decimal)
| Double -> NoSize(System.Data.DbType.Double)
| Guid -> NoSize(System.Data.DbType.Guid)
| Int16 -> NoSize(System.Data.DbType.Int16)
| Int32 -> NoSize(System.Data.DbType.Int32)
| Int64 -> NoSize(System.Data.DbType.Int64)
| SByte -> NoSize(System.Data.DbType.SByte)
| Single -> NoSize(System.Data.DbType.Single)
| Time -> NoSize(System.Data.DbType.Time)
| UInt16 -> NoSize(System.Data.DbType.UInt16)
| UInt32 -> NoSize(System.Data.DbType.UInt32)
| UInt64 -> NoSize(System.Data.DbType.UInt64)
// has size
| AnsiString(x) -> HasSize(System.Data.DbType.AnsiString,x)
| AnsiStringFixedLength(x) -> HasSize(System.Data.DbType.AnsiStringFixedLength,x)
| Binary(x) -> HasSize(System.Data.DbType.Binary,x)
| Object(x) -> HasSize(System.Data.DbType.Object,x)
| String(x) -> HasSize(System.Data.DbType.String,x)
| StringFixedLength(x) -> HasSize(System.Data.DbType.StringFixedLength,x)
| VarNumeric(x) -> HasSize(System.Data.DbType.VarNumeric,x)
| Xml(x) -> HasSize(System.Data.DbType.Xml,x)
let dbDir (p:Direction) =
match p with
| In -> System.Data.ParameterDirection.Input
| Out -> System.Data.ParameterDirection.Output
| Ref -> System.Data.ParameterDirection.InputOutput
| Return -> System.Data.ParameterDirection.ReturnValue
member x.CreateProcedure(name) =
let cmd = factory.CreateCommand()
let cn = factory.CreateConnection()
cn.ConnectionString <- config.ConnectionString
cmd.Connection <- cn
cmd.CommandText <- name
cmd
member x.CreateParameter(name:string,typ:DbType,dir:Direction) =
let p = factory.CreateParameter()
if name.StartsWith("#") then
p.ParameterName <- name
else
p.ParameterName <- "#" + name
p.Direction <- dbDir dir
match typ with
| HasSize(t,s) ->
p.DbType <- t
p.Size <- s
| NoSize(t) -> p.DbType <- t
p
type Foo() =
let mutable x:int = 0
let mutable y:string = ""
let mutable z:option<System.DateTime> = None
member a.X with get() = x and set n = x <- n
member a.Y with get() = y and set n = y <- n
member a.Z with get() = z and set n = z <- n
let db = Db("db")
let proc name (parameters:list<string*DbType*Direction>) =
let cmd = db.CreateProcedure(name)
let param p =
db.CreateParameter p
|> cmd.Parameters.Add
|> ignore
List.iter param parameters
cmd
let (?<-) (cmd:DbCommand) (s:string) (value:'a) =
cmd.Parameters.["#" + s].Value <- value
let (<|>) (value:option<'a>) (replacement:'a) =
match value with
| Some(x) -> x
| _ -> replacement
let (?) (r:DbDataReader) (s:string) : option<'a> =
let index = r.GetOrdinal s
match r.IsDBNull index with
| true -> None
| _ -> r.GetValue index
:?> 'a
|> Some
let foo x y =
let foo2 = proc "getfoo2"
<| [ ("x",Int32,In);
("y",String(15),In) ]
foo2?x <- x
foo2?y <- y
try
foo2.Connection.Open()
use r = foo2.ExecuteReader()
[
while r.Read() do
let item = Foo()
item.X <- (r?x) <|> 1
item.Y <- (r?y) <|> ""
item.Z <- r?z
yield item
]
finally
foo2.Connection.Close()
Program.fs
open System
open System.Data
open System.Data.Common
open System.Configuration
open File1
let config = ConfigurationManager.ConnectionStrings.Item("db")
let factory = DbProviderFactories.GetFactory(config.ProviderName)
[<EntryPoint>]
let main (args : string[]) =
let foo1a = foo 1 "a"
let foo1b = foo 1 "b"
let foo1c = foo 1 "c"
for f in foo1a do
let mutable z = DateTime.Now
match f.Z with
| Some(x) -> z <- x
| None -> z <- DateTime.MinValue
printfn "%d : %s : %O" f.X f.Y z
// program exit code
0
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="db" providerName="System.Data.SqlClient" connectionString="server=(local);uid=;pwd=;Trusted_Connection=yes;database=scratchPad"/>
</connectionStrings>
</configuration>
(Reposting from comment)
Your code looks generally fine to me, although you may want to explicitly set cmd.CommandType to CommandType.StoredProcedure inside of CreateProcedure.

How to Winwait for two windows simultaneously in AutoIt?

I would like to know if its possible to WinWaitActive for WindowWithThisTitle and WindowWithThatTitle at the same time. I'm executing a command and there could be a window telling me that the connection failed or a user/pass dialog coming up.
Is there another way doing it as this?
WinWaitActive("Title1", "", 5)
If(WinExists("Title1")) Then
MsgBox(0, "", "Do something")
Else
If(WinExists("Title2")) Then
MsgBox(0, "", "Do something else")
EndIf
EndIf
Because I don't want to have the timeout which could be more than 15 seconds.
A simpler solution might be to use a REGEX title in your WinWaitActive as defined here
You would then have something like this:
$hWnd = WinWaitActive("[REGEXPTITLE:(WindowWithThisTitle|WindowWithThatTitle)]")
If WinGetTitle($hWnd) = "WindowWithThisTitle" then
DoSomething()
Else
DoSomethingElse()
EndIf
How about something like this.
$stillLooking = True
While $stillLooking
$activeWindowTitle = WinGetTitle(WinActive(""))
If $activeWindowTitle == "Title1" Then
MsgBox(0, "", "Do something")
$stillLooking = False
ElseIf $activeWindowTitle == "Title2" Then
MsgBox(0, "", "Do something else")
$stillLooking = False
EndIf
sleep(5)
WEnd
Because I don't want to have the
timeout which could be more than 15
seconds.
WinWaitActive() doesn't have a timeout unless you specify one. You gave it a five second timeout but you could leave that off and it would wait forever.
You can use this Functions for two windows ..
; #FUNCTION# ====================================================================================================================
; Name...........: _2WinWait
; Description ...: Wait For Tow Windows .
; Syntax.........: _2WinWait ($FirstTitle,$SecondTitle,[$FirstText = "" ,[$SecondText = ""]] )
; Parameters ....: $FirstTitle - Title Of First Wondow
; $SecondTitle - Title Of Second Wondow
; $FirstText - Text Of First Wondow
; $SecondText - Text Of Second Wondow
; Return values .: Success - None
; Failure - Returns a 0 => If Your Titles Is Wrong
; Author ........: Ashalshaikh : Ahmad Alshaikh
; Remarks .......:
; Related .......:
; Link ..........;
; Example .......; No
; ===============================================================================================================================
Func _2WinWait ($FirstTitle,$SecondTitle,$FirstText = "" ,$SecondText = "" )
If $FirstTitle = "" Or $SecondTitle = "" Then
Return 0
Else
Do
Until WinExists ($FirstTitle,$FirstText) Or WinExists ($SecondTitle,$SecondText)
EndIf
EndFunc
; #FUNCTION# ====================================================================================================================
; Name...........: _2WinWait_Any
; Description ...: Wait For Tow Windows And Return Any Window Id Exists .
; Syntax.........: _2WinWait_Any ($FirstTitle,$SecondTitle,[$FirstText = "" ,[$SecondText = ""]] )
; Parameters ....: $FirstTitle - Title Of First Wondow
; $SecondTitle - Title Of Second Wondow
; $FirstText - Text Of First Wondow
; $SecondText - Text Of Second Wondow
; Return values .: Success - Number Of Window ==> 1= First Window , 2= Second Window
; Failure - Returns a 0 => If Your Titles Is Wrong
; Author ........: Ashalshaikh : Ahmad Alshaikh
; Remarks .......:
; Related .......:
; Link ..........;
; Example .......; No
; ===============================================================================================================================
Func _2WinWait_Any ($FirstTitle,$SecondTitle,$FirstText = "" ,$SecondText = "" )
If $FirstTitle = "" Or $SecondTitle = "" Then
Return 0
Else
Do
Until WinExists ($FirstTitle,$FirstText) Or WinExists ($SecondTitle,$SecondText)
If WinExists ($FirstTitle,$FirstTexit) Then
Return 1
Else
Return 2
EndIf
EndIf
EndFunc
for more with examples
I'm fairly new to autoit and the programming world in general and I had this same dilemma. Luckily I figured out a straight fwd way to do it:
Do
$var1 = 0
If WinGetState("Document Reference","") Then
$var1 = 1
ElseIf WinGetState("Customer Search","") Then
$var1 = 1
EndIf
Until $var1 = 1
So it'll stay in the loop until it finds the window and sets $var1 to 1. There's probably easier ways (I'm sure developers are gasping at this) but this is straight fwd enough for me.
You can create an infinite while loop with if statements in there:
#include <MsgBoxConstants.au3>
Example()
Func Example()
While 1
; Test if the window exists and display the results.
If WinExists("Windows Security") Then
Local $hWnd = WinWaitActive("Windows Security", "", 2000)
ControlSetText($hWnd, "", "[CLASS:Edit; INSTANCE:1]", "hel233")
ControlClick("Windows Security","","[CLASS:Button; INSTANCE:2]")
Sleep(5000)
EndIf
; Test if the window exists and display the results.
If WinExists("Spread the Word") Then
'The line below will wait until the window is active, but we don't need that
'Local $hWnd = WinWaitActive("Spread the Word", "", 2000)
WinClose("Spread the Word")
Sleep(5000)
EndIf
wend
EndFunc

Resources