<commit_before>/*
 * This file is part of Cockpit.
 *
 * Copyright (C) 2019 Red Hat, Inc.
 *
 * Cockpit is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Cockpit is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react';
import cockpit from 'cockpit';
import {
    Alert, Button, Form, FormGroup, Modal, Popover, Radio,
} from '@patternfly/react-core';
import { InfoAltIcon } from '@patternfly/react-icons';

import * as Select from 'cockpit-components-select.jsx';
import { ModalError } from 'cockpit-components-inline-notification.jsx';

import { updateDiskAttributes } from '../libvirt-dbus.js';
import { getDiskPrettyName, getDiskFullName } from '../helpers.js';

import 'form-layout.scss';

const _ = cockpit.gettext;

const NameRow = ({ idPrefix, name, diskType }) => {
    let label = _("ID");
    if (["file", "block", "dir"].includes(diskType))
        label = _("Path");
    else if (diskType === "network")
        label = _("Url");
    else if (diskType === "volume")
        label = _("Storage volume");

    return (
        <FormGroup fieldId={`${idPrefix}-name`} label={label}>
            <samp id={`${idPrefix}-name`}>
                {name}
            </samp>
        </FormGroup>
    );
};

const BusRow = ({ onValueChanged, dialogValues, idPrefix, shutoff }) => {
    const busTypes = ['sata', 'scsi', 'usb', 'virtio'];

    return (
        <FormGroup fieldId={`${idPrefix}-bus-type`} label={_("Bus")}
                   labelIcon={!shutoff &&
                       <Popover bodyContent={_("Machine must be shut off before changing bus type")}>
                           <button onClick={e => e.preventDefault()} className="pf-c-form__group-label-help">
                               <InfoAltIcon noVerticalAlign />
                           </button>
                       </Popover>}>
            <Select.Select id={`${idPrefix}-bus-type`}
                onChange={value => onValueChanged('busType', value)}
                initial={dialogValues.busType}
                extraClass='pf-c-form-control'
                enabled={shutoff}>
                {busTypes.map(busType => {
                    return (
                        <Select.SelectEntry data={busType} key={busType}>
                            {busType}
                        </Select.SelectEntry>
                    );
                })}
            </Select.Select>
        </FormGroup>
    );
};

const AccessRow = ({ onValueChanged, dialogValues, driverType, idPrefix }) => {
    return (
        <FormGroup fieldId={`${idPrefix}-access`} label={_("Access")} isInline>
            <Radio id={`${idPrefix}-readonly`}
                   name="access"
                   isChecked={dialogValues.readonly}
                   onChange={e => {
                       onValueChanged('readonly', true);
                       onValueChanged('shareable', false);
                   }}
                   label={_("Read-only")} />
            <Radio id={`${idPrefix}-writable`}
                   name="access"
                   isChecked={!dialogValues.readonly && !dialogValues.shareable}
                   onChange={e => {
                       onValueChanged('readonly', false);
                       onValueChanged('shareable', false);
                   }}
                   label={_("Writeable")} />
            {(driverType === "raw") &&
            <Radio id={`${idPrefix}-writable-shareable`}
                   name="access"
                   isChecked={dialogValues.shareable}
                   onChange={e => {
                       onValueChanged('readonly', false);
                       onValueChanged('shareable', true);
                   }}
                   label={_("Writeable and shared")} />}
        </FormGroup>
    );
};

class EditDiskModalBody extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            readonly: props.disk.readonly,
            shareable: props.disk.shareable,
            busType: props.disk.bus,
        };
        this.onValueChanged = this.onValueChanged.bind(this);
        this.dialogErrorSet = this.dialogErrorSet.bind(this);
        this.onSaveClicked = this.onSaveClicked.bind(this);
    }

    onValueChanged(key, value) {
        this.setState({ [key]: value });
    }

    dialogErrorSet(text, detail) {
        this.setState({ dialogError: text, dialogErrorDetail: detail });
    }

    onSaveClicked() {
        const { disk, vm } = this.props;
        const existingTargets = Object.getOwnPropertyNames(vm.disks);

        updateDiskAttributes({ connectionName: vm.connectionName, objPath: vm.id, target: disk.target, readonly: this.state.readonly, shareable: this.state.shareable, busType: this.state.busType, existingTargets })
                .then(() => this.props.close())
                .fail((exc) => {
                    this.dialogErrorSet(_("Disk settings could not be saved"), exc.message);
                });
    }

    render() {
        const { vm, disk } = this.props;
        const idPrefix = `${this.props.idPrefix}-edit`;
<commit_msg>machines: when changing the disk's access mode do it in a deterministic way<commit_after>/*
 * This file is part of Cockpit.
 *
 * Copyright (C) 2019 Red Hat, Inc.
 *
 * Cockpit is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Cockpit is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react';
import cockpit from 'cockpit';
import {
    Alert, Button, Form, FormGroup, Modal, Popover, Radio,
} from '@patternfly/react-core';
import { InfoAltIcon } from '@patternfly/react-icons';

import * as Select from 'cockpit-components-select.jsx';
import { ModalError } from 'cockpit-components-inline-notification.jsx';

import { updateDiskAttributes } from '../libvirt-dbus.js';
import { getDiskPrettyName, getDiskFullName } from '../helpers.js';

import 'form-layout.scss';

const _ = cockpit.gettext;

const NameRow = ({ idPrefix, name, diskType }) => {
    let label = _("ID");
    if (["file", "block", "dir"].includes(diskType))
        label = _("Path");
    else if (diskType === "network")
        label = _("Url");
    else if (diskType === "volume")
        label = _("Storage volume");

    return (
        <FormGroup fieldId={`${idPrefix}-name`} label={label}>
            <samp id={`${idPrefix}-name`}>
                {name}
            </samp>
        </FormGroup>
    );
};

const BusRow = ({ onValueChanged, dialogValues, idPrefix, shutoff }) => {
    const busTypes = ['sata', 'scsi', 'usb', 'virtio'];

    return (
        <FormGroup fieldId={`${idPrefix}-bus-type`} label={_("Bus")}
                   labelIcon={!shutoff &&
                       <Popover bodyContent={_("Machine must be shut off before changing bus type")}>
                           <button onClick={e => e.preventDefault()} className="pf-c-form__group-label-help">
                               <InfoAltIcon noVerticalAlign />
                           </button>
                       </Popover>}>
            <Select.Select id={`${idPrefix}-bus-type`}
                onChange={value => onValueChanged('busType', value)}
                initial={dialogValues.busType}
                extraClass='pf-c-form-control'
                enabled={shutoff}>
                {busTypes.map(busType => {
                    return (
                        <Select.SelectEntry data={busType} key={busType}>
                            {busType}
                        </Select.SelectEntry>
                    );
                })}
            </Select.Select>
        </FormGroup>
    );
};

const AccessRow = ({ onValueChanged, dialogValues, driverType, idPrefix }) => {
    return (
        <FormGroup fieldId={`${idPrefix}-access`} label={_("Access")} isInline>
            <Radio id={`${idPrefix}-readonly`}
                   name="access"
                   value="readonly"
                   isChecked={dialogValues.access == "readonly" }
                   onChange={(_, event) => {
                       onValueChanged("access", event.currentTarget.value);
                   }}
                   label={_("Read-only")} />
            <Radio id={`${idPrefix}-writable`}
                   name="access"
                   value="writable"
                   isChecked={dialogValues.access == "writable" }
                   onChange={(_, event) => {
                       onValueChanged("access", event.currentTarget.value);
                   }}
                   label={_("Writeable")} />
            {(driverType === "raw") &&
            <Radio id={`${idPrefix}-writable-shareable`}
                   name="access"
                   value="shareable"
                   isChecked={dialogValues.access == "shareable" }
                   onChange={(_, event) => {
                       onValueChanged("access", event.currentTarget.value);
                   }}
                   label={_("Writeable and shared")} />}
        </FormGroup>
    );
};

class EditDiskModalBody extends React.Component {
    constructor(props) {
        super(props);
        let access;
        if (props.disk.readonly)
            access = "readonly";
        else if (props.disk.shareable)
            access = "shareable";
        else
            access = "writable";

        this.state = {
            access,
            busType: props.disk.bus,
        };
        this.onValueChanged = this.onValueChanged.bind(this);
        this.dialogErrorSet = this.dialogErrorSet.bind(this);
        this.onSaveClicked = this.onSaveClicked.bind(this);
    }

    onValueChanged(key, value) {
        this.setState({ [key]: value });
    }

    dialogErrorSet(text, detail) {
        this.setState({ dialogError: text, dialogErrorDetail: detail });
    }

    onSaveClicked() {
        const { disk, vm } = this.props;
        const existingTargets = Object.getOwnPropertyNames(vm.disks);

        updateDiskAttributes({
            connectionName: vm.connectionName,
            objPath: vm.id, target: disk.target,
            readonly: this.state.access == "readonly",
            shareable: this.state.access == "shareable",
            busType: this.state.busType,
            existingTargets
        })
                .then(() => this.props.close())
                .fail((exc) => {
                    this.dialogErrorSet(_("Disk settings could not be saved"), exc.message);
                });
    }

    render() {
        const { vm, disk } = this.props;
        const idPrefix = `${this.props.idPrefix}-edit`;

{'fraction_non_alphanumeric': 0.13147444751381215, 'fraction_numerical': 0.0010359116022099447, 'mean_word_length': 1.9269833249115715, 'pattern_counts': {'":': 0, '<': 45, '<?xml version=': 0, '>': 67, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4315521', 'n_tokens_mistral': 3157, 'n_tokens_neox': 3034, 'n_words': 751}