Search in sources :

Example 1 with CellPreviewEvent

use of com.google.gwt.view.client.CellPreviewEvent in project pentaho-platform by pentaho.

the class SchedulesPanel method createUI.

private void createUI(boolean isAdmin, final boolean isScheduler) {
    table.getElement().setId("schedule-table");
    table.setStylePrimaryName("pentaho-table");
    table.setWidth("100%", true);
    // BISERVER-9331 Column sort indicators should be to the right of header text in the Manage Schedules table.
    if (table.getHeaderBuilder() instanceof AbstractHeaderOrFooterBuilder) {
        ((AbstractHeaderOrFooterBuilder<JsJob>) table.getHeaderBuilder()).setSortIconStartOfLine(false);
    }
    final MultiSelectionModel<JsJob> selectionModel = new MultiSelectionModel<JsJob>(new ProvidesKey<JsJob>() {

        public Object getKey(JsJob item) {
            return item.getJobId();
        }
    });
    table.setSelectionModel(selectionModel);
    Label noDataLabel = new Label(Messages.getString("noSchedules"));
    noDataLabel.setStyleName("noDataForScheduleTable");
    table.setEmptyTableWidget(noDataLabel);
    TextColumn<JsJob> idColumn = new TextColumn<JsJob>() {

        public String getValue(JsJob job) {
            return job.getJobId();
        }
    };
    idColumn.setSortable(true);
    TextColumn<JsJob> nameColumn = new TextColumn<JsJob>() {

        public String getValue(JsJob job) {
            return job.getJobName();
        }
    };
    nameColumn.setSortable(true);
    HtmlColumn<JsJob> resourceColumn = new HtmlColumn<JsJob>() {

        @Override
        public String getStringValue(JsJob job) {
            String name = job.getFullResourceName().split("\\.")[0];
            return name.replaceAll("/", "/<wbr/>");
        }
    };
    resourceColumn.setSortable(true);
    HtmlColumn<JsJob> outputPathColumn = new HtmlColumn<JsJob>(new ClickableSafeHtmlCell()) {

        @Override
        public String getStringValue(JsJob jsJob) {
            try {
                String outputPath = jsJob.getOutputPath();
                if (StringUtils.isEmpty(outputPath)) {
                    return "-";
                } else {
                    outputPath = new SafeHtmlBuilder().appendEscaped(outputPath).toSafeHtml().asString();
                    return MessageFormat.format("<span class=''workspace-resource-link'' title=''{0}''>{0}</span>", outputPath);
                }
            } catch (Throwable t) {
                return "-";
            }
        }
    };
    outputPathColumn.setFieldUpdater(new FieldUpdater<JsJob, SafeHtml>() {

        @Override
        public void update(final int index, final JsJob jsJob, final SafeHtml value) {
            if (!value.equals("-")) {
                final Command errorCallback = new Command() {

                    @Override
                    public void execute() {
                        showValidateOutputLocationError();
                    }
                };
                final Command successCallback = new Command() {

                    @Override
                    public void execute() {
                        openOutputLocation(jsJob.getOutputPath());
                    }
                };
                OutputLocationUtils.validateOutputLocation(jsJob.getOutputPath(), successCallback, errorCallback);
            }
        }
    });
    outputPathColumn.setSortable(true);
    TextColumn<JsJob> scheduleColumn = new TextColumn<JsJob>() {

        public String getValue(JsJob job) {
            try {
                return job.getJobTrigger().getDescription();
            } catch (Throwable t) {
                return "-";
            }
        }
    };
    scheduleColumn.setSortable(true);
    TextColumn<JsJob> userNameColumn = new TextColumn<JsJob>() {

        public String getValue(JsJob job) {
            try {
                return job.getUserName();
            } catch (Throwable t) {
                return "-";
            }
        }
    };
    userNameColumn.setSortable(true);
    TextColumn<JsJob> stateColumn = new TextColumn<JsJob>() {

        public String getValue(JsJob job) {
            try {
                // BISERVER-9965
                final String jobState = "COMPLETE".equalsIgnoreCase(job.getState()) ? "FINISHED" : job.getState();
                // not css text-transform because tooltip will use pure text from the cell
                return jobState.substring(0, 1).toUpperCase() + jobState.substring(1).toLowerCase();
            } catch (Throwable t) {
                return "-";
            }
        }
    };
    stateColumn.setSortable(true);
    TextColumn<JsJob> nextFireColumn = new TextColumn<JsJob>() {

        public String getValue(JsJob job) {
            try {
                Date date = job.getNextRun();
                if (date == null) {
                    return "-";
                }
                DateTimeFormat format = DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_MEDIUM);
                return format.format(date);
            } catch (Throwable t) {
                return "-";
            }
        }
    };
    nextFireColumn.setSortable(true);
    TextColumn<JsJob> lastFireColumn = new TextColumn<JsJob>() {

        public String getValue(JsJob job) {
            try {
                Date date = job.getLastRun();
                if (date == null) {
                    return "-";
                }
                DateTimeFormat format = DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_MEDIUM);
                return format.format(date);
            } catch (Throwable t) {
                return "-";
            }
        }
    };
    lastFireColumn.setSortable(true);
    // table.addColumn(idColumn, "ID");
    table.addColumn(nameColumn, Messages.getString("scheduleName"));
    table.addColumn(scheduleColumn, Messages.getString("recurrence"));
    table.addColumn(resourceColumn, Messages.getString("sourceFile"));
    table.addColumn(outputPathColumn, Messages.getString("outputPath"));
    table.addColumn(lastFireColumn, Messages.getString("lastFire"));
    table.addColumn(nextFireColumn, Messages.getString("nextFire"));
    if (isAdmin) {
        table.addColumn(userNameColumn, Messages.getString("user"));
    }
    table.addColumn(stateColumn, Messages.getString("state"));
    table.addColumnStyleName(0, "backgroundContentHeaderTableCell");
    table.addColumnStyleName(1, "backgroundContentHeaderTableCell");
    table.addColumnStyleName(2, "backgroundContentHeaderTableCell");
    table.addColumnStyleName(3, "backgroundContentHeaderTableCell");
    table.addColumnStyleName(4, "backgroundContentHeaderTableCell");
    table.addColumnStyleName(5, "backgroundContentHeaderTableCell");
    if (isAdmin) {
        table.addColumnStyleName(6, "backgroundContentHeaderTableCell");
    }
    table.addColumnStyleName(isAdmin ? 7 : 6, "backgroundContentHeaderTableCell");
    table.setColumnWidth(nameColumn, 160, Unit.PX);
    table.setColumnWidth(resourceColumn, 200, Unit.PX);
    table.setColumnWidth(outputPathColumn, 180, Unit.PX);
    table.setColumnWidth(scheduleColumn, 170, Unit.PX);
    table.setColumnWidth(lastFireColumn, 120, Unit.PX);
    table.setColumnWidth(nextFireColumn, 120, Unit.PX);
    if (isAdmin) {
        table.setColumnWidth(userNameColumn, 100, Unit.PX);
    }
    table.setColumnWidth(stateColumn, 90, Unit.PX);
    dataProvider.addDataDisplay(table);
    List<JsJob> list = dataProvider.getList();
    ListHandler<JsJob> columnSortHandler = new ListHandler<JsJob>(list);
    columnSortHandler.setComparator(idColumn, new Comparator<JsJob>() {

        public int compare(JsJob o1, JsJob o2) {
            if (o1 == o2) {
                return 0;
            }
            if (o1 != null) {
                return (o2 != null) ? o1.getJobId().compareTo(o2.getJobId()) : 1;
            }
            return -1;
        }
    });
    columnSortHandler.setComparator(nameColumn, new Comparator<JsJob>() {

        public int compare(JsJob o1, JsJob o2) {
            if (o1 == o2) {
                return 0;
            }
            if (o1 != null) {
                return (o2 != null) ? o1.getJobName().compareTo(o2.getJobName()) : 1;
            }
            return -1;
        }
    });
    columnSortHandler.setComparator(resourceColumn, new Comparator<JsJob>() {

        public int compare(JsJob o1, JsJob o2) {
            if (o1 == o2) {
                return 0;
            }
            if (o1 != null) {
                String r1 = o1.getShortResourceName();
                String r2 = null;
                if (o2 != null) {
                    r2 = o2.getShortResourceName();
                }
                return (o2 != null) ? r1.compareTo(r2) : 1;
            }
            return -1;
        }
    });
    columnSortHandler.setComparator(outputPathColumn, new Comparator<JsJob>() {

        public int compare(JsJob o1, JsJob o2) {
            if (o1 == o2) {
                return 0;
            }
            if (o1 != null) {
                String r1 = o1.getOutputPath();
                String r2 = null;
                if (o2 != null) {
                    r2 = o2.getOutputPath();
                }
                return (o2 != null) ? r1.compareTo(r2) : 1;
            }
            return -1;
        }
    });
    columnSortHandler.setComparator(scheduleColumn, new Comparator<JsJob>() {

        public int compare(JsJob o1, JsJob o2) {
            String s1 = o1.getJobTrigger().getDescription();
            String s2 = o2.getJobTrigger().getDescription();
            return s1.compareTo(s2);
        }
    });
    columnSortHandler.setComparator(userNameColumn, new Comparator<JsJob>() {

        public int compare(JsJob o1, JsJob o2) {
            if (o1 == o2) {
                return 0;
            }
            if (o1 != null) {
                return (o2 != null) ? o1.getUserName().compareTo(o2.getUserName()) : 1;
            }
            return -1;
        }
    });
    columnSortHandler.setComparator(stateColumn, new Comparator<JsJob>() {

        public int compare(JsJob o1, JsJob o2) {
            if (o1 == o2) {
                return 0;
            }
            if (o1 != null) {
                return (o2 != null) ? o1.getState().compareTo(o2.getState()) : 1;
            }
            return -1;
        }
    });
    columnSortHandler.setComparator(nextFireColumn, new Comparator<JsJob>() {

        public int compare(JsJob o1, JsJob o2) {
            if (o1 == o2) {
                return 0;
            }
            if (o1 == null || o1.getNextRun() == null) {
                return -1;
            }
            if (o2 == null || o2.getNextRun() == null) {
                return 1;
            }
            if (o1.getNextRun() == o2.getNextRun()) {
                return 0;
            }
            return o1.getNextRun().compareTo(o2.getNextRun());
        }
    });
    columnSortHandler.setComparator(lastFireColumn, new Comparator<JsJob>() {

        public int compare(JsJob o1, JsJob o2) {
            if (o1 == o2) {
                return 0;
            }
            if (o1 == null || o1.getLastRun() == null) {
                return -1;
            }
            if (o2 == null || o2.getLastRun() == null) {
                return 1;
            }
            if (o1.getLastRun() == o2.getLastRun()) {
                return 0;
            }
            return o1.getLastRun().compareTo(o2.getLastRun());
        }
    });
    table.addColumnSortHandler(columnSortHandler);
    table.getColumnSortList().push(idColumn);
    table.getColumnSortList().push(resourceColumn);
    table.getColumnSortList().push(outputPathColumn);
    table.getColumnSortList().push(nameColumn);
    table.getSelectionModel().addSelectionChangeHandler(new Handler() {

        public void onSelectionChange(SelectionChangeEvent event) {
            Set<JsJob> selectedJobs = getSelectedJobs();
            if (selectedJobs != null && selectedJobs.size() > 0) {
                JsJob[] jobs = selectedJobs.toArray(new JsJob[selectedJobs.size()]);
                editButton.setEnabled(isScheduler);
                if ("NORMAL".equalsIgnoreCase(jobs[0].getState())) {
                    controlScheduleButton.setImage(ImageUtil.getThemeableImage("icon-small", "icon-stop"));
                } else {
                    controlScheduleButton.setImage(ImageUtil.getThemeableImage("icon-small", "icon-run"));
                }
                controlScheduleButton.setEnabled(isScheduler);
                boolean isRunning = "NORMAL".equalsIgnoreCase(jobs[0].getState());
                controlScheduleButton.setToolTip(isRunning ? Messages.getString("stop") : Messages.getString("start"));
                scheduleRemoveButton.setEnabled(isScheduler);
                triggerNowButton.setEnabled(isScheduler);
            } else {
                editButton.setEnabled(false);
                controlScheduleButton.setEnabled(false);
                scheduleRemoveButton.setEnabled(false);
                triggerNowButton.setEnabled(false);
            }
        }
    });
    // BISERVER-9965
    table.addCellPreviewHandler(new CellPreviewEvent.Handler<JsJob>() {

        @Override
        public void onCellPreview(CellPreviewEvent<JsJob> event) {
            if ("mouseover".equals(event.getNativeEvent().getType())) {
                final TableCellElement cell = table.getRowElement(event.getIndex()).getCells().getItem(event.getColumn());
                cell.setTitle(cell.getInnerText());
            }
        }
    });
    SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
    pager = new SimplePager(TextLocation.CENTER, pagerResources, false, 0, true) {

        @Override
        public void setPageStart(int index) {
            if (getDisplay() != null) {
                Range range = getDisplay().getVisibleRange();
                int pageSize = range.getLength();
                // Removed the min to show fixed ranges
                // if (isRangeLimited && display.isRowCountExact()) {
                // index = Math.min(index, display.getRowCount() - pageSize);
                // }
                index = Math.max(0, index);
                if (index != range.getStart()) {
                    getDisplay().setVisibleRange(index, pageSize);
                }
            }
        }
    };
    pager.setDisplay(table);
    // pager.setRangeLimited(false);
    VerticalPanel tableAndPager = new VerticalPanel();
    tableAndPager.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
    Toolbar bar = new Toolbar();
    bar.addSpacer(10);
    bar.add(Toolbar.GLUE);
    // Add control scheduler button
    if (isAdmin) {
        final ToolbarButton controlSchedulerButton = new ToolbarButton(ImageUtil.getThemeableImage("icon-small", "icon-start-scheduler"));
        controlSchedulerButton.setCommand(new Command() {

            public void execute() {
                toggleSchedulerOnOff(controlSchedulerButton, isScheduler);
            }
        });
        updateControlSchedulerButtonState(controlSchedulerButton, isScheduler);
        bar.add(controlSchedulerButton);
        bar.addSpacer(20);
    }
    // Add filter button
    filterButton.setCommand(new Command() {

        public void execute() {
            if (filterDialog == null) {
                filterDialog = new FilterDialog(allJobs, filterDialogCallback);
            } else {
                filterDialog.initUI(allJobs);
            }
            filterDialog.center();
        }
    });
    filterButton.setToolTip(Messages.getString("filterSchedules"));
    if (isAdmin) {
        bar.add(filterButton);
    }
    // Add remove filters button
    filterRemoveButton.setCommand(new Command() {

        public void execute() {
            filterDialog = null;
            filters.clear();
            filterAndShowData();
            filterRemoveButton.setEnabled(false);
            filterButton.setImage(ImageUtil.getThemeableImage("icon-small", "icon-filter-add"));
        }
    });
    filterRemoveButton.setToolTip(Messages.getString("removeFilters"));
    filterRemoveButton.setEnabled(filters.size() > 0);
    if (isAdmin) {
        bar.add(filterRemoveButton);
    }
    // Add refresh button
    ToolbarButton refresh = new ToolbarButton(ImageUtil.getThemeableImage("icon-small", "icon-refresh"));
    refresh.setToolTip(Messages.getString("refreshTooltip"));
    refresh.setCommand(new Command() {

        public void execute() {
            RefreshSchedulesCommand cmd = new RefreshSchedulesCommand();
            cmd.execute();
        }
    });
    bar.add(refresh);
    bar.addSpacer(20);
    // Add execute now button
    triggerNowButton.setToolTip(Messages.getString("executeNow"));
    triggerNowButton.setCommand(new Command() {

        public void execute() {
            Set<JsJob> selectedJobs = getSelectedJobs();
            if (selectedJobs != null && selectedJobs.size() > 0) {
                MessageDialogBox messageDialog = new MessageDialogBox(Messages.getString("executeNow"), Messages.getString("executeNowStarted"), false, true, true);
                messageDialog.setCallback(new IDialogCallback() {

                    public void okPressed() {
                        // wait a little to refresh to give schedule time to update the last run
                        Timer t = new Timer() {

                            public void run() {
                                refresh();
                            }
                        };
                        t.schedule(2000);
                    }

                    public void cancelPressed() {
                    }
                });
                messageDialog.center();
                controlJobs(selectedJobs, "triggerNow", RequestBuilder.POST, false);
            }
        }
    });
    triggerNowButton.setEnabled(false);
    bar.add(triggerNowButton);
    // Add control schedule button
    controlScheduleButton.setCommand(new Command() {

        public void execute() {
            Set<JsJob> selectedJobs = getSelectedJobs();
            if (selectedJobs != null && selectedJobs.size() > 0) {
                JsJob[] jobs = selectedJobs.toArray(new JsJob[selectedJobs.size()]);
                if ("NORMAL".equals(jobs[0].getState())) {
                    controlJobs(selectedJobs, "pauseJob", RequestBuilder.POST, false);
                } else {
                    controlJobs(selectedJobs, "resumeJob", RequestBuilder.POST, false);
                }
            }
        }
    });
    controlScheduleButton.setEnabled(false);
    bar.add(controlScheduleButton);
    bar.addSpacer(20);
    // Add edit button
    editButton.setCommand(new Command() {

        public void execute() {
            Set<JsJob> selectedJobs = getSelectedJobs();
            if (selectedJobs != null && selectedJobs.size() > 0) {
                JsJob[] jobs = selectedJobs.toArray(new JsJob[selectedJobs.size()]);
                final JsJob editJob = jobs[0];
                final String url = GWT.getHostPageBaseURL() + "api/repo/files/" + SolutionBrowserPanel.pathToId(editJob.getFullResourceName()) + "/canAccess?cb=" + System.currentTimeMillis() + "&permissions=" + READ_PERMISSION;
                RequestBuilder executableTypesRequestBuilder = new RequestBuilder(RequestBuilder.GET, url);
                try {
                    executableTypesRequestBuilder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
                    executableTypesRequestBuilder.sendRequest(null, new RequestCallback() {

                        public void onError(Request request, Throwable exception) {
                            promptForScheduleResourceError(editJob);
                        }

                        public void onResponseReceived(Request request, Response response) {
                            if ("true".equalsIgnoreCase(response.getText())) {
                                editJob(editJob);
                            } else {
                                promptForScheduleResourceError(editJob);
                            }
                        }
                    });
                } catch (RequestException e) {
                // showError(e);
                }
            }
        }
    });
    editButton.setEnabled(false);
    editButton.setToolTip(Messages.getString("editTooltip"));
    bar.add(editButton);
    // Add remove button
    scheduleRemoveButton.setCommand(new Command() {

        public void execute() {
            Set<JsJob> selectedJobs = getSelectedJobs();
            if (selectedJobs != null && selectedJobs.size() > 0) {
                final PromptDialogBox prompt = new PromptDialogBox(Messages.getString("warning"), Messages.getString("yes"), Messages.getString("no"), false, true);
                prompt.setContent(new Label(Messages.getString("deleteConfirmSchedles", "" + selectedJobs.size())));
                prompt.setCallback(new IDialogCallback() {

                    public void okPressed() {
                        controlJobs(getSelectedJobs(), "removeJob", RequestBuilder.DELETE, true);
                        prompt.hide();
                    }

                    public void cancelPressed() {
                        prompt.hide();
                    }
                });
                prompt.center();
            }
        }
    });
    scheduleRemoveButton.setToolTip(Messages.getString("remove"));
    scheduleRemoveButton.setEnabled(false);
    bar.add(scheduleRemoveButton);
    tableAndPager.add(bar);
    tableAndPager.add(table);
    tableAndPager.add(pager);
    // Add it to the root panel.
    setWidget(tableAndPager);
}
Also used : RefreshSchedulesCommand(org.pentaho.mantle.client.commands.RefreshSchedulesCommand) SafeHtml(com.google.gwt.safehtml.shared.SafeHtml) Label(com.google.gwt.user.client.ui.Label) JSONString(com.google.gwt.json.client.JSONString) ToolbarButton(org.pentaho.gwt.widgets.client.toolbar.ToolbarButton) AbstractHeaderOrFooterBuilder(com.google.gwt.user.cellview.client.AbstractHeaderOrFooterBuilder) TextColumn(com.google.gwt.user.cellview.client.TextColumn) Toolbar(org.pentaho.gwt.widgets.client.toolbar.Toolbar) MessageDialogBox(org.pentaho.gwt.widgets.client.dialogs.MessageDialogBox) ListHandler(com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler) Handler(com.google.gwt.view.client.SelectionChangeEvent.Handler) SafeHtmlBuilder(com.google.gwt.safehtml.shared.SafeHtmlBuilder) Range(com.google.gwt.view.client.Range) IDialogCallback(org.pentaho.gwt.widgets.client.dialogs.IDialogCallback) SelectionChangeEvent(com.google.gwt.view.client.SelectionChangeEvent) JSONObject(com.google.gwt.json.client.JSONObject) TableCellElement(com.google.gwt.dom.client.TableCellElement) Set(java.util.Set) HashSet(java.util.HashSet) RequestBuilder(com.google.gwt.http.client.RequestBuilder) PromptDialogBox(org.pentaho.gwt.widgets.client.dialogs.PromptDialogBox) MultiSelectionModel(com.google.gwt.view.client.MultiSelectionModel) RequestException(com.google.gwt.http.client.RequestException) HtmlColumn(org.pentaho.mantle.client.ui.column.HtmlColumn) ListHandler(com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler) Request(com.google.gwt.http.client.Request) SimplePager(com.google.gwt.user.cellview.client.SimplePager) Date(java.util.Date) CellPreviewEvent(com.google.gwt.view.client.CellPreviewEvent) Response(com.google.gwt.http.client.Response) VerticalPanel(com.google.gwt.user.client.ui.VerticalPanel) Timer(com.google.gwt.user.client.Timer) RequestCallback(com.google.gwt.http.client.RequestCallback) Command(com.google.gwt.user.client.Command) RefreshSchedulesCommand(org.pentaho.mantle.client.commands.RefreshSchedulesCommand) DateTimeFormat(com.google.gwt.i18n.client.DateTimeFormat)

Example 2 with CellPreviewEvent

use of com.google.gwt.view.client.CellPreviewEvent in project rstudio by rstudio.

the class ModifyKeyboardShortcutsWidget method addHandlers.

private void addHandlers() {
    table_.addCellPreviewHandler(new CellPreviewEvent.Handler<KeyboardShortcutEntry>() {

        @Override
        public void onCellPreview(CellPreviewEvent<KeyboardShortcutEntry> preview) {
            Handle shortcutsHandler = shortcuts_.disable();
            int column = preview.getColumn();
            if (column == 0)
                onNameCellPreview(preview);
            else if (column == 1)
                onShortcutCellPreview(preview);
            else if (column == 2)
                onNameCellPreview(preview);
            shortcutsHandler.close();
        }
    });
    table_.addColumnSortHandler(new ColumnSortEvent.Handler() {

        @Override
        public void onColumnSort(ColumnSortEvent event) {
            List<KeyboardShortcutEntry> data = dataProvider_.getList();
            if (event.getColumn().equals(nameColumn_))
                sort(data, 0, event.isSortAscending());
            else if (event.getColumn().equals(shortcutColumn_))
                sort(data, 1, event.isSortAscending());
            else if (event.getColumn().equals(typeColumn_))
                sort(data, 2, event.isSortAscending());
            updateData(data);
        }
    });
    // Fix a bug where clicking on a table header would also
    // select the cell at position [0, 0]. It seems that GWT's
    // DataGrid over-aggressively selects the first cell on the
    // _first_ mouse down event seen; after the first click,
    // cell selection occurs only after full mouse clicks.
    table_.addDomHandler(new MouseDownHandler() {

        @Override
        public void onMouseDown(MouseDownEvent event) {
            Element target = event.getNativeEvent().getEventTarget().cast();
            if (target.hasAttribute("__gwt_header")) {
                event.stopPropagation();
                event.preventDefault();
            }
        }
    }, MouseDownEvent.getType());
}
Also used : Element(com.google.gwt.dom.client.Element) TableRowElement(com.google.gwt.dom.client.TableRowElement) MouseDownEvent(com.google.gwt.event.dom.client.MouseDownEvent) AddinsMRUList(org.rstudio.studio.client.workbench.AddinsMRUList) List(java.util.List) ArrayList(java.util.ArrayList) ColumnSortEvent(com.google.gwt.user.cellview.client.ColumnSortEvent) MouseDownHandler(com.google.gwt.event.dom.client.MouseDownHandler) CellPreviewEvent(com.google.gwt.view.client.CellPreviewEvent) Handle(org.rstudio.core.client.command.ShortcutManager.Handle)

Example 3 with CellPreviewEvent

use of com.google.gwt.view.client.CellPreviewEvent in project ovirt-engine by oVirt.

the class VmSnapshotCustomPreviewPopupWidget method createPreviewTable.

private void createPreviewTable() {
    previewTable.addColumn(new AbstractFullDateTimeColumn<SnapshotModel>() {

        @Override
        protected Date getRawValue(SnapshotModel snapshotModel) {
            return snapshotModel.getEntity().getCreationDate();
        }
    }, constants.dateSnapshot(), // $NON-NLS-1$
    "140px");
    previewTable.addColumn(new AbstractTextColumn<SnapshotModel>() {

        @Override
        public String getValue(SnapshotModel snapshotModel) {
            return snapshotModel.getEntity().getDescription();
        }
    }, constants.descriptionSnapshot(), // $NON-NLS-1$
    "100px");
    previewTable.setSelectionModel(new NoSelectionModel());
    Column<SnapshotModel, Boolean> vmConfColumn = new Column<SnapshotModel, Boolean>(new RadioboxCell()) {

        @Override
        public Boolean getValue(SnapshotModel model) {
            Snapshot snapshotVmConf = model.getEntity();
            Snapshot toPreviewVmConf = previewSnapshotModel.getSnapshotModel().getEntity();
            if (snapshotVmConf == null && toPreviewVmConf == null) {
                return true;
            }
            return snapshotVmConf != null && snapshotVmConf.equals(toPreviewVmConf);
        }

        @Override
        public void render(Context context, SnapshotModel snapshotModel, SafeHtmlBuilder sb) {
            if (!snapshotModel.getEntity().isVmConfigurationBroken()) {
                super.render(context, snapshotModel, sb);
            } else {
                sb.appendEscaped(constants.notAvailableLabel());
            }
        }
    };
    vmConfColumn.setFieldUpdater((index, snapshotModel, value) -> {
        previewSnapshotModel.setSnapshotModel(snapshotModel);
        previewSnapshotModel.clearMemorySelection();
        updateWarnings();
        refreshTable(previewTable);
        if (snapshotModel.getVm() == null) {
            snapshotModel.updateVmConfiguration(returnValue -> updateInfoPanel());
        } else {
            updateInfoPanel();
        }
    });
    previewTable.addColumn(vmConfColumn, new ImageResourceHeader(resources.vmConfIcon(), SafeHtmlUtils.fromTrustedString(constants.vmConfiguration())), // $NON-NLS-1$
    "30px");
    AbstractCheckboxColumn<SnapshotModel> memoryColumn = new AbstractCheckboxColumn<SnapshotModel>((index, snapshotModel, value) -> {
        previewSnapshotModel.getSnapshotModel().getMemory().setEntity(value);
        refreshTable(previewTable);
        updateWarnings();
    }) {

        @Override
        public Boolean getValue(SnapshotModel snapshotModel) {
            return snapshotModel.getMemory().getEntity();
        }

        @Override
        protected boolean canEdit(SnapshotModel snapshotModel) {
            boolean containsMemory = snapshotModel.getEntity().containsMemory();
            SnapshotModel selectedSnapshotModel = previewSnapshotModel.getSnapshotModel();
            return containsMemory && snapshotModel == selectedSnapshotModel;
        }

        @Override
        public void render(Context context, SnapshotModel snapshotModel, SafeHtmlBuilder sb) {
            if (snapshotModel.getEntity().containsMemory()) {
                super.render(context, snapshotModel, sb);
            } else {
                sb.appendEscaped(constants.notAvailableLabel());
            }
        }
    };
    previewTable.addColumn(memoryColumn, templates.iconWithText(imageResourceToSafeHtml(resources.memorySmallIcon()), constants.memorySnapshot()), // $NON-NLS-1$
    "100px");
    AbstractCheckboxColumn<SnapshotModel> vmLeaseColumn = new AbstractCheckboxColumn<SnapshotModel>((index, snapshotModel, value) -> {
        snapshotModel.getLeaseExists().setEntity(value);
        refreshTable(previewTable);
        updateWarnings();
    }) {

        @Override
        public Boolean getValue(SnapshotModel model) {
            if (model.getLeaseExists() != null) {
                return model.getLeaseExists().getEntity();
            }
            return false;
        }

        @Override
        protected boolean canEdit(SnapshotModel snapshotModel) {
            // prevent from selecting more then one leases in case many snapshots have leases
            if (snapshotModel.getLeaseExists() != null) {
                SnapshotModel result = previewSnapshotModel.getSnapshots().getItems().stream().filter(model -> model.getEntity().getId() != snapshotModel.getEntity().getId()).filter(model -> model.getLeaseExists().getEntity() != null).filter(model -> model.getLeaseExists().getEntity()).findFirst().orElse(null);
                return result == null;
            }
            return false;
        }

        @Override
        public void render(Context context, SnapshotModel snapshotModel, SafeHtmlBuilder sb) {
            if (snapshotModel.getLeaseExists().getEntity() != null) {
                super.render(context, snapshotModel, sb);
            } else {
                sb.appendEscaped(constants.notAvailableLabel());
            }
        }
    };
    // $NON-NLS-1$
    previewTable.addColumn(vmLeaseColumn, constants.leaseSnapshot(), "80px");
    List<DiskImage> disks = previewSnapshotModel.getAllDisks();
    Collections.sort(disks, new DiskByDiskAliasComparator());
    for (final DiskImage disk : disks) {
        previewTable.addColumn(new AbstractCheckboxColumn<SnapshotModel>((index, snapshotModel, value) -> {
            ListModel diskListModel = previewSnapshotModel.getDiskSnapshotsMap().get(disk.getId());
            DiskImage image = snapshotModel.getImageByDiskId(disk.getId());
            diskListModel.setSelectedItem(Boolean.TRUE.equals(value) ? image : null);
            refreshTable(previewTable);
            updateWarnings();
            updateInfoPanel();
        }) {

            @Override
            public Boolean getValue(SnapshotModel snapshotModel) {
                ListModel diskListModel = previewSnapshotModel.getDiskSnapshotsMap().get(disk.getId());
                DiskImage image = snapshotModel.getImageByDiskId(disk.getId());
                return image != null ? image.equals(diskListModel.getSelectedItem()) : false;
            }

            @Override
            protected boolean canEdit(SnapshotModel model) {
                return true;
            }

            @Override
            public void render(Context context, SnapshotModel snapshotModel, SafeHtmlBuilder sb) {
                DiskImage image = snapshotModel.getImageByDiskId(disk.getId());
                if (image == null) {
                    sb.appendEscaped(constants.notAvailableLabel());
                } else if (image.getImageStatus() == ImageStatus.ILLEGAL) {
                    sb.append(templates.text(constants.notAvailableLabel()));
                } else {
                    super.render(context, snapshotModel, sb);
                }
            }

            @Override
            public SafeHtml getTooltip(SnapshotModel model) {
                if (disk != null && disk.getId() != null) {
                    DiskImage image = model.getImageByDiskId(disk.getId());
                    if (image != null && image.getImageStatus() == ImageStatus.ILLEGAL) {
                        return SafeHtmlUtils.fromSafeConstant(constants.illegalStatus());
                    }
                }
                return null;
            }
        }, new SafeHtmlHeader(templates.iconWithText(imageResourceToSafeHtml(resources.diskIcon()), disk.getDiskAlias()), SafeHtmlUtils.fromString(disk.getId().toString())), // $NON-NLS-1$
        "120px");
        // Edit preview table
        previewTable.asEditor().edit(previewSnapshotModel.getSnapshots());
    }
    previewTable.addCellPreviewHandler(new CellPreviewEvent.Handler<EntityModel>() {

        long lastClick = -1000;

        @Override
        public void onCellPreview(CellPreviewEvent<EntityModel> event) {
            NativeEvent nativeEvent = event.getNativeEvent();
            long clickAt = System.currentTimeMillis();
            if (BrowserEvents.CLICK.equals(nativeEvent.getType())) {
                if (clickAt - lastClick < 300) {
                    // double click: 2 clicks detected within 300 ms
                    SnapshotModel selectedSnapshotModel = (SnapshotModel) event.getValue();
                    if (!selectedSnapshotModel.getEntity().isVmConfigurationBroken()) {
                        previewSnapshotModel.clearSelection(selectedSnapshotModel.getEntity().getId());
                        previewSnapshotModel.selectSnapshot(selectedSnapshotModel.getEntity().getId());
                        updateWarnings();
                        refreshTable(previewTable);
                    }
                }
                lastClick = System.currentTimeMillis();
            }
        }
    });
}
Also used : CommonApplicationConstants(org.ovirt.engine.ui.common.CommonApplicationConstants) PreviewSnapshotModel(org.ovirt.engine.ui.uicommonweb.models.vms.PreviewSnapshotModel) AbstractCheckboxColumn(org.ovirt.engine.ui.common.widget.table.column.AbstractCheckboxColumn) BrowserEvents(com.google.gwt.dom.client.BrowserEvents) ImageResource(com.google.gwt.resources.client.ImageResource) EntityModelCellTable(org.ovirt.engine.ui.common.widget.editor.EntityModelCellTable) Date(java.util.Date) DiskByDiskAliasComparator(org.ovirt.engine.core.common.businessentities.comparators.DiskByDiskAliasComparator) GWT(com.google.gwt.core.client.GWT) DiskImage(org.ovirt.engine.core.common.businessentities.storage.DiskImage) HTML(com.google.gwt.user.client.ui.HTML) NativeEvent(com.google.gwt.dom.client.NativeEvent) ArrayList(java.util.ArrayList) ImageStatus(org.ovirt.engine.core.common.businessentities.storage.ImageStatus) EntityModel(org.ovirt.engine.ui.uicommonweb.models.EntityModel) UiBinder(com.google.gwt.uibinder.client.UiBinder) CellPreviewEvent(com.google.gwt.view.client.CellPreviewEvent) Label(com.google.gwt.user.client.ui.Label) Snapshot(org.ovirt.engine.core.common.businessentities.Snapshot) AssetProvider(org.ovirt.engine.ui.common.gin.AssetProvider) NoSelectionModel(com.google.gwt.view.client.NoSelectionModel) Context(com.google.gwt.cell.client.Cell.Context) SafeHtmlBuilder(com.google.gwt.safehtml.shared.SafeHtmlBuilder) AbstractImagePrototype(com.google.gwt.user.client.ui.AbstractImagePrototype) SafeHtmlUtils(com.google.gwt.safehtml.shared.SafeHtmlUtils) SplitLayoutPanel(com.google.gwt.user.client.ui.SplitLayoutPanel) CommonApplicationTemplates(org.ovirt.engine.ui.common.CommonApplicationTemplates) SimplePanel(com.google.gwt.user.client.ui.SimplePanel) CommonApplicationResources(org.ovirt.engine.ui.common.CommonApplicationResources) AbstractFullDateTimeColumn(org.ovirt.engine.ui.common.widget.table.column.AbstractFullDateTimeColumn) ElementIdHandler(org.ovirt.engine.ui.common.idhandler.ElementIdHandler) AbstractModelBoundPopupWidget(org.ovirt.engine.ui.common.widget.uicommon.popup.AbstractModelBoundPopupWidget) UiCommonEditorDriver(org.ovirt.engine.ui.common.editor.UiCommonEditorDriver) ListModel(org.ovirt.engine.ui.uicommonweb.models.ListModel) SnapshotModel(org.ovirt.engine.ui.uicommonweb.models.vms.SnapshotModel) RadioboxCell(org.ovirt.engine.ui.common.widget.table.cell.RadioboxCell) List(java.util.List) FlowPanel(com.google.gwt.user.client.ui.FlowPanel) Column(com.google.gwt.user.cellview.client.Column) UiField(com.google.gwt.uibinder.client.UiField) AbstractTextColumn(org.ovirt.engine.ui.common.widget.table.column.AbstractTextColumn) VmSnapshotInfoPanel(org.ovirt.engine.ui.common.widget.uicommon.vm.VmSnapshotInfoPanel) SafeHtmlHeader(org.ovirt.engine.ui.common.widget.table.header.SafeHtmlHeader) SafeHtml(com.google.gwt.safehtml.shared.SafeHtml) Collections(java.util.Collections) ImageResourceHeader(org.ovirt.engine.ui.common.widget.table.header.ImageResourceHeader) ImageResourceHeader(org.ovirt.engine.ui.common.widget.table.header.ImageResourceHeader) SafeHtml(com.google.gwt.safehtml.shared.SafeHtml) AbstractCheckboxColumn(org.ovirt.engine.ui.common.widget.table.column.AbstractCheckboxColumn) AbstractFullDateTimeColumn(org.ovirt.engine.ui.common.widget.table.column.AbstractFullDateTimeColumn) Column(com.google.gwt.user.cellview.client.Column) AbstractTextColumn(org.ovirt.engine.ui.common.widget.table.column.AbstractTextColumn) DiskImage(org.ovirt.engine.core.common.businessentities.storage.DiskImage) Context(com.google.gwt.cell.client.Cell.Context) NoSelectionModel(com.google.gwt.view.client.NoSelectionModel) RadioboxCell(org.ovirt.engine.ui.common.widget.table.cell.RadioboxCell) EntityModel(org.ovirt.engine.ui.uicommonweb.models.EntityModel) SafeHtmlBuilder(com.google.gwt.safehtml.shared.SafeHtmlBuilder) AbstractCheckboxColumn(org.ovirt.engine.ui.common.widget.table.column.AbstractCheckboxColumn) PreviewSnapshotModel(org.ovirt.engine.ui.uicommonweb.models.vms.PreviewSnapshotModel) SnapshotModel(org.ovirt.engine.ui.uicommonweb.models.vms.SnapshotModel) Date(java.util.Date) CellPreviewEvent(com.google.gwt.view.client.CellPreviewEvent) DiskByDiskAliasComparator(org.ovirt.engine.core.common.businessentities.comparators.DiskByDiskAliasComparator) SafeHtmlHeader(org.ovirt.engine.ui.common.widget.table.header.SafeHtmlHeader) Snapshot(org.ovirt.engine.core.common.businessentities.Snapshot) ListModel(org.ovirt.engine.ui.uicommonweb.models.ListModel) NativeEvent(com.google.gwt.dom.client.NativeEvent)

Aggregations

CellPreviewEvent (com.google.gwt.view.client.CellPreviewEvent)3 SafeHtml (com.google.gwt.safehtml.shared.SafeHtml)2 SafeHtmlBuilder (com.google.gwt.safehtml.shared.SafeHtmlBuilder)2 Label (com.google.gwt.user.client.ui.Label)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 List (java.util.List)2 Context (com.google.gwt.cell.client.Cell.Context)1 GWT (com.google.gwt.core.client.GWT)1 BrowserEvents (com.google.gwt.dom.client.BrowserEvents)1 Element (com.google.gwt.dom.client.Element)1 NativeEvent (com.google.gwt.dom.client.NativeEvent)1 TableCellElement (com.google.gwt.dom.client.TableCellElement)1 TableRowElement (com.google.gwt.dom.client.TableRowElement)1 MouseDownEvent (com.google.gwt.event.dom.client.MouseDownEvent)1 MouseDownHandler (com.google.gwt.event.dom.client.MouseDownHandler)1 Request (com.google.gwt.http.client.Request)1 RequestBuilder (com.google.gwt.http.client.RequestBuilder)1 RequestCallback (com.google.gwt.http.client.RequestCallback)1 RequestException (com.google.gwt.http.client.RequestException)1