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 java.util.function.Supplier;
33  import javafx.beans.property.ReadOnlyObjectProperty;
34  import javafx.beans.value.ChangeListener;
35  import javafx.collections.ObservableList;
36  import javafx.event.ActionEvent;
37  import javafx.scene.control.ComboBox;
38  import javafx.scene.control.ListCell;
39  import javafx.scene.control.ListView;
40  import javafx.stage.Window;
41  import javafx.util.Callback;
42  import it.tidalwave.ui.core.role.PresentationModel;
43  import it.tidalwave.ui.core.role.UserAction;
44  import it.tidalwave.ui.core.role.UserActionProvider;
45  import it.tidalwave.ui.javafx.impl.common.AsObjectListCell;
46  import it.tidalwave.ui.javafx.impl.common.CellBinder;
47  import it.tidalwave.ui.javafx.impl.common.ChangeListenerSelectableAdapter;
48  import it.tidalwave.ui.javafx.impl.common.DelegateSupport;
49  import it.tidalwave.ui.javafx.impl.common.JavaFXWorker;
50  import lombok.extern.slf4j.Slf4j;
51  import static it.tidalwave.ui.core.role.UserActionProvider._UserActionProvider_;
52  import static it.tidalwave.ui.javafx.impl.DefaultJavaFXBinder.enforceFxApplicationThread;
53  import static it.tidalwave.ui.javafx.impl.common.JavaFXWorker.childrenPm;
54  import static javafx.scene.input.KeyCode.*;
55  
56  /***************************************************************************************************************************************************************
57   *
58   * This class takes care of bindings related to {@link ComboBox}.
59   *
60   * @author  Fabrizio Giudici
61   *
62   **************************************************************************************************************************************************************/
63  @Slf4j
64  public class ComboBoxBindings extends DelegateSupport
65    {
66      @Nonnull
67      private final CellBinder cellBinder;
68  
69      private final Callback<ListView<PresentationModel>, ListCell<PresentationModel>> cellFactory;
70  
71      private final ChangeListener<PresentationModel> changeListener = new ChangeListenerSelectableAdapter(executor);
72  
73      /***********************************************************************************************************************************************************
74       *
75       **********************************************************************************************************************************************************/
76      public ComboBoxBindings (@Nonnull final Executor executor, @Nonnull final CellBinder cellBinder, @Nonnull final Supplier<Window> mainWindow)
77        {
78          super(executor, mainWindow);
79          this.cellBinder = cellBinder;
80          cellFactory = comboBox -> new AsObjectListCell<>(cellBinder);
81        }
82  
83      /***********************************************************************************************************************************************************
84       * Binds a combobox.
85       * @param   comboBox            the {@link ComboBox}
86       * @param   pm                  the {@link PresentationModel}
87       * @param   callback            an optional callback to invoke at the end of the binding
88       **********************************************************************************************************************************************************/
89      public void bind (@Nonnull final ComboBox<PresentationModel> comboBox, @Nonnull final PresentationModel pm, @Nonnull final Optional<Runnable> callback)
90        {
91          enforceFxApplicationThread();
92          log.debug("bind({}, {}, {})", comboBox, pm, callback);
93          comboBox.setCellFactory(cellFactory);
94          comboBox.setButtonCell(new AsObjectListCell<>(cellBinder));
95          comboBox.setOnAction(this::onActionEvent);
96          comboBox.setOnKeyPressed(event ->
97            {
98              if (List.of(SPACE, ENTER).contains(event.getCode()))
99                {
100                 comboBox.show();
101               }
102           });
103 
104         final var selectedProperty = comboBox.getSelectionModel().selectedItemProperty();
105         selectedProperty.removeListener(changeListener);
106         JavaFXWorker.run(executor,
107                          () -> childrenPm(pm),
108                          items -> finalizeBinding(comboBox, items, selectedProperty, callback));
109       }
110 
111     /***********************************************************************************************************************************************************
112      * Event handler that calls back the default action bound to the given combobox item.
113      **********************************************************************************************************************************************************/
114     @SuppressWarnings("unchecked")
115     private void onActionEvent (@Nonnull final ActionEvent event)
116       {
117         final var comboBox = (ComboBox<PresentationModel>)event.getSource();
118         final var selectedPm = comboBox.getSelectionModel().getSelectedItem();
119         selectedPm.maybeAs(_UserActionProvider_)
120                   .flatMap(UserActionProvider::getOptionalDefaultAction)
121                   .ifPresent(UserAction::actionPerformed);
122       }
123 
124     /***********************************************************************************************************************************************************
125      * Finalizes binding in the JavaFX thread and eventually invokes a callback.
126      * @param   comboBox            the {@link ComboBox}
127      * @param   items               the items of the combo box
128      * @param   selectedProperty    the 'selected' property
129      * @param   callback            an optional callback to invoke at the end
130      **********************************************************************************************************************************************************/
131     private void finalizeBinding (@Nonnull final ComboBox<PresentationModel> comboBox,
132                                   @Nonnull final ObservableList<PresentationModel> items,
133                                   @Nonnull final ReadOnlyObjectProperty<PresentationModel> selectedProperty,
134                                   @Nonnull final Optional<Runnable> callback)
135       {
136         comboBox.setItems(items);
137 
138         if (!items.isEmpty())
139           {
140             comboBox.getSelectionModel().select(items.get(0));
141           }
142 
143         selectedProperty.addListener(changeListener);
144         callback.ifPresent(Runnable::run);
145       }
146   }