View Javadoc
1   /*
2    * *************************************************************************************************************************************************************
3    *
4    * SteelBlue: DCI User Interfaces
5    * http://tidalwave.it/projects/steelblue
6    *
7    * Copyright (C) 2015 - 2025 by Tidalwave s.a.s. (http://tidalwave.it)
8    *
9    * *************************************************************************************************************************************************************
10   *
11   * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
12   * You may obtain a copy of the License at
13   *
14   *     http://www.apache.org/licenses/LICENSE-2.0
15   *
16   * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
17   * CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and limitations under the License.
18   *
19   * *************************************************************************************************************************************************************
20   *
21   * git clone https://bitbucket.org/tidalwave/steelblue-src
22   * git clone https://github.com/tidalwave-it/steelblue-src
23   *
24   * *************************************************************************************************************************************************************
25   */
26  package it.tidalwave.ui.javafx.impl.combobox;
27  
28  import jakarta.annotation.Nonnull;
29  import java.util.List;
30  import java.util.Optional;
31  import java.util.concurrent.Executor;
32  import javafx.beans.property.ReadOnlyObjectProperty;
33  import javafx.beans.value.ChangeListener;
34  import javafx.collections.ObservableList;
35  import javafx.event.ActionEvent;
36  import javafx.scene.control.ComboBox;
37  import javafx.scene.control.ListCell;
38  import javafx.scene.control.ListView;
39  import javafx.util.Callback;
40  import it.tidalwave.ui.core.role.PresentationModel;
41  import it.tidalwave.ui.core.role.UserAction;
42  import it.tidalwave.ui.core.role.UserActionProvider;
43  import it.tidalwave.ui.javafx.impl.common.CellBinder;
44  import it.tidalwave.ui.javafx.impl.common.ChangeListenerSelectableAdapter;
45  import it.tidalwave.ui.javafx.impl.common.DelegateSupport;
46  import it.tidalwave.ui.javafx.impl.common.JavaFXWorker;
47  import it.tidalwave.ui.javafx.impl.common.AsObjectListCell;
48  import lombok.extern.slf4j.Slf4j;
49  import static javafx.scene.input.KeyCode.*;
50  import static it.tidalwave.ui.core.role.UserActionProvider._UserActionProvider_;
51  import static it.tidalwave.ui.javafx.impl.DefaultJavaFXBinder.enforceFxApplicationThread;
52  import static it.tidalwave.ui.javafx.impl.common.JavaFXWorker.childrenPm;
53  
54  /***************************************************************************************************************************************************************
55   *
56   * This class takes care of bindings related to {@link ComboBox}.
57   *
58   * @author  Fabrizio Giudici
59   *
60   **************************************************************************************************************************************************************/
61  @Slf4j
62  public class ComboBoxBindings extends DelegateSupport
63    {
64      @Nonnull
65      private final CellBinder cellBinder;
66  
67      private final Callback<ListView<PresentationModel>, ListCell<PresentationModel>> cellFactory;
68  
69      private final ChangeListener<PresentationModel> changeListener = new ChangeListenerSelectableAdapter(executor);
70  
71      /***********************************************************************************************************************************************************
72       *
73       **********************************************************************************************************************************************************/
74      public ComboBoxBindings (@Nonnull final Executor executor, @Nonnull final CellBinder cellBinder)
75        {
76          super(executor);
77          this.cellBinder = cellBinder;
78          cellFactory = comboBox -> new AsObjectListCell<>(cellBinder);
79        }
80  
81      /***********************************************************************************************************************************************************
82       * Binds a combobox.
83       * @param   comboBox            the {@link ComboBox}
84       * @param   pm                  the {@link PresentationModel}
85       * @param   callback            an optional callback to invoke at the end of the binding
86       **********************************************************************************************************************************************************/
87      public void bind (@Nonnull final ComboBox<PresentationModel> comboBox, @Nonnull final PresentationModel pm, @Nonnull final Optional<Runnable> callback)
88        {
89          enforceFxApplicationThread();
90          log.debug("bind({}, {}, {})", comboBox, pm, callback);
91          comboBox.setCellFactory(cellFactory);
92          comboBox.setButtonCell(new AsObjectListCell<>(cellBinder));
93          comboBox.setOnAction(this::onActionEvent);
94          comboBox.setOnKeyPressed(event ->
95            {
96              if (List.of(SPACE, ENTER).contains(event.getCode()))
97                {
98                  comboBox.show();
99                }
100           });
101 
102         final var selectedProperty = comboBox.getSelectionModel().selectedItemProperty();
103         selectedProperty.removeListener(changeListener);
104         JavaFXWorker.run(executor,
105                          () -> childrenPm(pm),
106                          items -> finalizeBinding(comboBox, items, selectedProperty, callback));
107       }
108 
109     /***********************************************************************************************************************************************************
110      * Event handler that calls back the default action bound to the given combobox item.
111      **********************************************************************************************************************************************************/
112     @SuppressWarnings("unchecked")
113     private void onActionEvent (@Nonnull final ActionEvent event)
114       {
115         final var comboBox = (ComboBox<PresentationModel>)event.getSource();
116         final var selectedPm = comboBox.getSelectionModel().getSelectedItem();
117         selectedPm.maybeAs(_UserActionProvider_)
118                   .flatMap(UserActionProvider::getOptionalDefaultAction)
119                   .ifPresent(UserAction::actionPerformed);
120       }
121 
122     /***********************************************************************************************************************************************************
123      * Finalizes binding in the JavaFX thread and eventually invokes a callback.
124      * @param   comboBox            the {@link ComboBox}
125      * @param   items               the items of the combo box
126      * @param   selectedProperty    the 'selected' property
127      * @param   callback            an optional callback to invoke at the end
128      **********************************************************************************************************************************************************/
129     private void finalizeBinding (@Nonnull final ComboBox<PresentationModel> comboBox,
130                                   @Nonnull final ObservableList<PresentationModel> items,
131                                   @Nonnull final ReadOnlyObjectProperty<PresentationModel> selectedProperty,
132                                   @Nonnull final Optional<Runnable> callback)
133       {
134         comboBox.setItems(items);
135 
136         if (!items.isEmpty())
137           {
138             comboBox.getSelectionModel().select(items.get(0));
139           }
140 
141         selectedProperty.addListener(changeListener);
142         callback.ifPresent(Runnable::run);
143       }
144   }