Search code examples
smalltalkpharo

How to handle the event / detect hold SHIFT key in Spec 2 toolbars?


I have a toolbar (SpToolbarPresenter) as an instance var toolbar and I have an #updatePresenter implementation as:

updatePresenter

    cmds isEmpty ifTrue: [ ^ self ].

    btnHandlers := cmds collect: [ :cmd | 
                          | btn |
                          btn := SpToolbarButtonPresenter new
                                     label: cmd name;
                                     action: [];
                                     help: cmd help.
                          toolbar addItem: btn.
                          (SpEventHandler for: btn) whenMouseDownDo: [ :ev | 
                              self onCmd: cmd name event: ev ] ]

I use SpEventHandler instead of #action: because I want to detect hold SHIFT key while the toolbar's button is clicked. However, I still need the #action: because without it I get a strange error like "#cull: was sent to nil".

This code works for the second toolbar's button (I have two of them on the toolbar), but not for the first one! The first toolbar's button never gets the event, so onCmd is never called.

So, how to either 1) to detect hold SHIFT while toolbar's button is clicked or 2) to fix this code, so all buttons will get this event ? Any help will be useful.

PS. Windows 10, Spec 2, Pharo-9.0.0+build.940.sha.deeec198ef752789431ee24667709a4a3ff87bda (64 Bit)


Solution

  • as @RandomB says, but also adding a shiftPressed test :

    updatePresenter
    
        commands do: [ :aCommand | 
            | button |
            button := self newToolbarButton
                       label: aCommand name;
                       action: [  ];
                       help: aCommand help.
            toolbar addItem: button.
            button eventHandler whenMouseDownDo: [ :event | 
                event shiftPressed ifTrue: [
                    self onCmd: aCommand name event: event ] ] ]
    

    also, even not being directly related, I cannot avoid to say : use complete variable/method names! it will make your code a lot more readable :)