);
    },

    _applyLabel(label, action, idx, dir, str) {
        if (str != null) {
            label.set_text(str);

            let [found, x, y, arrangement] = this.getLabelCoords(action, idx, dir);
            this._allocateChild(label, x, y, arrangement);
        }
        label.show();
    },

    stopEdition(continues, str) {
        this._editorActor.hide();

        if (this._prevEdited) {
            let [label, action, idx, dir] = this._prevEdited;
            this._applyLabel(label, action, idx, dir, str);
            this._prevEdited = null;
        }

        if (this._curEdited) {
            let [label, action, idx, dir] = this._curEdited;
            this._applyLabel(label, action, idx, dir, str);
            if (continues)
                this._prevEdited = this._curEdited;
            this._curEdited = null;
        }
    },

    startEdition(action, idx, dir) {
        let editedLabel;

        if (this._curEdited)
            return;

        for (let i = 0; i < this._labels.length; i++) {
            let [label, itemAction, itemIdx, itemDir] = this._labels[i];
            if (action == itemAction && idx == itemIdx && dir == itemDir) {
                this._curEdited = this._labels[i];
                editedLabel = label;
                break;
            }
        }

        if (this._curEdited == null)
            return;
        let [found] = this.getLabelCoords(action, idx, dir);
        if (!found)
            return;
        this._editorActor.show();
        editedLabel.hide();
    }
});

var PadOsd = new Lang.Class({
    Name: 'PadOsd',

    _init(padDevice, settings, imagePath, editionMode, monitorIndex) {
        this.padDevice = padDevice;
        this._groupPads = [ padDevice ];
        this._settings = settings;
        this._imagePath = imagePath;
        this._editionMode = editionMode;
        this._capturedEventId = global.stage.connect('captured-event', this._onCapturedEvent.bind(this));
        this._padChooser = null;

        let deviceManager = Clutter.DeviceManager.get_default();
        this._deviceAddedId = deviceManager.connect('device-added', (manager, device) => {
            if (device.get_device_type() == Clutter.InputDeviceType.PAD_DEVICE &&
                this.padDevice.is_grouped(device)) {
                this._groupPads.push(device);
                this._updatePadChooser();
            }
        });
        this._deviceRemovedId = deviceManager.connect('device-removed', (manager, device) => {
            // If the device is being removed, destroy the padOsd.
            if (device == this.padDevice) {
                this.destroy();
            } else if (this._groupPads.indexOf(device) != -1) {
                // Or update the pad chooser if the device belongs to
                // the same group.
                this._groupPads.splice(this._groupPads.indexOf(device), 1);
                this._updatePadChooser();

            }
        });

        deviceManager.list_devices().forEach(device => {
            if (device != this.padDevice &&
                device.get_device_type() == Clutter.InputDeviceType.PAD_DEVICE &&
                this.padDevice.is_grouped(device))
                this._groupPads.push(device);
        });

        this.actor = new St.BoxLayout({ style_class: 'pad-osd-window',
                                        x_expand: true,
                                        y_expand: true,
                                        vertical: true,
                                        reactive: true });
        this.actor.connect('destroy', this._onDestroy.bind(this));
        Main.uiGroup.add_actor(this.actor);

        this._monitorIndex = monitorIndex;
        let constraint = new Layout.MonitorConstraint({ index: monitorIndex });
        this.actor.add_constraint(constraint);

        this._titleBox = new St.BoxLayout({ style_class: 'pad-osd-title-box',
                                            vertical: false,
                                            x_expand: false,
                                            x_align: Clutter.ActorAlign.CENTER });
        this.actor.add_actor(this._titleBox);

        let labelBox = new St.BoxLayout({ style_class: 'pad-osd-title-menu-box',
                                          vertical: true });
        this._titleBox.add_actor(labelBox);

        this._titleLabel = new St.Label({ style: 'font-side: larger; font-weight: bold;',
                                          x_align: Clutter.ActorAlign.CENTER });
        this._titleLabel.clutter_text.set_text(padDevice.get_device_name());
        labelBox.add_actor(this._titleLabel);

        this._tipLabel = new St.Label({ x_align: Clutter.ActorAlign.CENTER });
        labelBox.add_actor(this._tipLabel);

        this._updatePadChooser();

        this._actionEditor = new ActionEditor();
        this._actionEditor.connect('done', this._endActionEdition.bind(this));

        this._padDiagram = new PadDiagram({ image: this._imagePath,
                                            left_handed: settings.get_boolean('left-handed'),
                                            editor_actor: this._actionEditor.actor,
                                            x_expand: true,
                                            y_expand: true });
        this.actor.add_actor(this._padDiagram);

        // FIXME: Fix num buttons.
        let i = 0;
        for (i = 0; i < 50; i++) {
            let [found] = this._padDiagram.getButtonLabelCoords(i);
            if (!found)
                break;
            this._createLabel(Meta.PadActionType.BUTTON, i);
        }

        for (i = 0; i < padDevice.get_n_rings(); i++) {
            let [found] = this._padDiagram.getRingLabelCoords(i, CW);
            if (!found)
                break;
            this._createLabel(Meta.PadActionType.RING, i, CW);
            this._createLabel(Meta.PadActionType.RING, i, CCW);
        }

        for (i = 0; i < padDevice.get_n_strips(); i++) {
            let [found] = this._padDiagram.getStripLabelCoords(i, UP);
            if (!found)
                break;
            this._createLabel(Meta.PadActionType.STRIP, i, UP);
            this._createLabel(Meta.PadActionType.STRIP, i, DOWN);
        }

        let buttonBox = new St.Widget({ layout_manager: new Clutter.BinLayout(),
                                         x_expand: true,
                                         x_align: Clutter.ActorAlign.CENTER,
                                         y_align: Clutter.ActorAlign.CENTER });
        this.actor.add_actor(buttonBox);
        this._editButton = new St.Button({ label: _("Edit…"),
                                           style_class: 'button',
                                           x_align: Clutter.ActorAlign.CENTER,
                                           can_focus: true });
        this._editButton.connect('clicked', () => {
            this.setEditionMode(true);
        });
        buttonBox.add_actor(this._editButton);

        this._syncEditionMode();
        Main.pushModal(this.actor);
    },

    _updatePadChooser() {
        if (this._groupPads.length > 1) {
            if (this._padChooser == null) {
                this._padChooser = new PadChooser(this.padDevice, this._groupPads)
                this._padChooser.connect('pad-selected', (chooser, pad) => {
                    this._requestForOtherPad(pad);
                });
                this._titleBox.add_child(this._padChooser.actor);
            } else {
                this._padChooser.update(this._groupPads);
            }
        } else if (this._padChooser != null) {
            this._padChooser.destroy();
            this._padChooser = null;
        }
    },

    _requestForOtherPad(pad) {
        if (pad == this.padDevice ||
            this._groupPads.indexOf(pad) == -1)
            return;

        let editionMode = this._editionMode;
        this.destroy();
        global.display.request_pad_osd(pad, editionMode);
    },

    _createLabel(type, number, dir) {
        let str = global.display.get_pad_action_label(this.padDevice, type, number);
        let label = new St.Label({ text: str ? str : _("None") });
        this._padDiagram.addLabel(label, type, number, dir);
    },

    _onCapturedEvent(actor, event) {
        if (event.type() == Clutter.EventType.PAD_BUTTON_PRESS &&
            event.get_source_device() == this.padDevice) {
            this._padDiagram.activateButton(event.get_button());
            let isModeSwitch = this.padDevice.get_mode_switch_button_group(event.get_button()) >= 0;

            /* Buttons that switch between modes cannot be edited */
            if (this._editionMode && !isModeSwitch)
                this._startButtonActionEdition(event.get_button());
            return Clutter.EVENT_STOP;
        } else if (event.type() == Clutter.EventType.PAD_BUTTON_RELEASE &&
                   event.get_source_device() == this.padDevice) {
            this._padDiagram.deactivateButton(event.get_button());
            return Clutter.EVENT_STOP;
        } else if (event.type() == Clutter.EventType.KEY_PRESS &&
                   (!this._editionMode || event.get_key_symbol() == Clutter.Escape)) {
            if (this._editedAction != null)
                this._endActionEdition();
            else
                this.destroy();
            return Clutter.EVENT_STOP;
        } else if (event.get_source_device() == this.padDevice &&
                   event.type() == Clutter.EventType.PAD_STRIP) {
            if (this._editionMode) {
                let [retval, number, mode] = event.get_pad_event_details();
                this._startStripActionEdition(number, UP, mode);
            }
        } else if (event.get_source_device() == this.padDevice &&
                   event.type() == Clutter.EventType.PAD_RING) {
            if (this._editionMode) {
                let [retval, number, mode] = event.get_pad_event_details();
                this._startRingActionEdition(number, CCW, mode);
            }
        }

        // If the event comes from another pad in the same group,
        // show the OSD for it.
        if (this._groupPads.indexOf(event.get_source_device()) != -1) {
            this._requestForOtherPad(event.get_source_device());
            return Clutter.EVENT_STOP;
        }

        return Clutter.EVENT_PROPAGATE;
    },

    _syncEditionMode() {
        this._editButton.set_reactive(!this._editionMode);
        this._editButton.save_easing_state();
        this._editButton.set_easing_duration(200);
        this._editButton.set_opacity(this._editionMode ? 128 : 255);
        this._editButton.restore_easing_state();

        let title;

        if (this._editionMode) {
            title = _("Press a button to configure");
            this._tipLabel.set_text(_("Press Esc to exit"));
        } else {
            title = this.padDevice.get_device_name();
            this._tipLabel.set_text(_("Press any key to exit"));
        }

        this._titleLabel.clutter_text.set_markup('<span size="larger"><b>' + title + '</b></span>');
    },

    _isEditedAction(type, number, dir) {
        if (!this._editedAction)
            return false;

        return (this._editedAction.type == type &&
                this._editedAction.number == number &&
                this._editedAction.dir == dir);
    },

    _followUpActionEdition(str) {
        let { type, dir, number, mode } = this._editedAction;
        let hasNextAction = (type == Meta.PadActionType.RING && dir == CCW ||
                             type == Meta.PadActionType.STRIP && dir == UP);
        if (!hasNextAction)
            return false;

        this._padDiagram.stopEdition(true, str);
        this._editedAction = null;
        if (type == Meta.PadActionType.RING)
            this._startRingActionEdition(number, CW, mode);
        else
            this._startStripActionEdition(number, DOWN, mode);

        return true;
    },

    _endActionEdition() {
        this._actionEditor.close();

        if (this._editedAction != null) {
            let str = global.display.get_pad_action_label(this.padDevice,
                                                          this._editedAction.type,
                                                          this._editedAction.number);
            if (this._followUpActionEdition(str))
                return;

            this._padDiagram.stopEdition(false, str ? str : _("None"))
            this._editedAction = null;
        }

        this._editedActionSettings = null;
    },

    _startActionEdition(key, type, number, dir, mode) {
        if (this._isEditedAction(type, number, dir))
            return;

        this._endActionEdition();
        this._editedAction = { type, number, dir, mode };

        let settingsPath = this._settings.path + key + '/';
        this._editedActionSettings = Gio.Settings.new_with_path('org.gnome.desktop.peripherals.tablet.pad-button',
                                                                settingsPath);
        this._actionEditor.setSettings(this._editedActionSettings, type);
        this._padDiagram.startEdition(type, number, dir);
    },

    _startButtonActionEdition(button) {
        let ch = String.fromCharCode('A'.charCodeAt() + button);
        let key = 'button' + ch;
        this._startActionEdition(key, Meta.PadActionType.BUTTON, button);
    },

    _startRingActionEdition(ring, dir, mode) {
        let ch = String.fromCharCode('A'.charCodeAt() + ring);
        let key = 'ring%s-%s-mode-%d'.format(ch, dir == CCW ? 'ccw' : 'cw', mode);
        this._startActionEdition(key, Meta.PadActionType.RING, ring, dir, mode);
    },

    _startStripActionEdition(strip, dir, mode) {
        let ch = String.fromCharCode('A'.charCodeAt() + strip);
        let key = 'strip%s-%s-mode-%d'.format(ch, dir == UP ? 'up' : 'down', mode);
        this._startActionEdition(key, Meta.PadActionType.STRIP, strip, dir, mode);
    },

    setEditionMode(editionMode) {
        if (this._editionMode == editionMode)
            return;

        this._editionMode = editionMode;
        this._syncEditionMode();
    },

    destroy() {
        this.actor.destroy();
    },

    _onDestroy() {
        Main.popModal(this.actor);
        this._actionEditor.close();

        let deviceManager = Clutter.DeviceManager.get_default();
        if (this._deviceRemovedId != 0) {
            deviceManager.disconnect(this._deviceRemovedId);
            this._deviceRemovedId = 0;
        }
        if (this._deviceAddedId != 0) {
            deviceManager.disconnect(this._deviceAddedId);
            this._deviceAddedId = 0;
        }

        if (this._capturedEventId != 0) {
            global.stage.disconnect(this._capturedEventId);
            this._capturedEventId = 0;
        }

        this.actor = null;
        this.emit('closed');
    }
});
Signals.addSignalMethods(PadOsd.prototype);

const PadOsdIface = loadInterfaceXML('org.gnome.Shell.Wacom.PadOsd');

var PadOsdService = new Lang.Class({
    Name: 'PadOsdService',

    _init() {
        this._dbusImpl = Gio.DBusExportedObject.wrapJSObject(PadOsdIface, this);
        this._dbusImpl.export(Gio.DBus.session, '/org/gnome/Shell/Wacom');
        Gio.DBus.session.own_name('org.gnome.Shell.Wacom.PadOsd', Gio.BusNameOwnerFlags.REPLACE, null, null);
    },

    ShowAsync(params, invocation) {
        let [deviceNode, editionMode] = params;
        let deviceManager = Clutter.DeviceManager.get_default();
        let devices = deviceManager.list_devices();
        let padDevice = null;

        devices.forEach(device => {
            if (deviceNode == device.get_device_node() &&
                device.get_device_type() == Clutter.InputDeviceType.PAD_DEVICE)
                padDevice = device;
        });

        if (padDevice == null) {
            invocation.return_error_literal(Gio.IOErrorEnum,
                                            Gio.IOErrorEnum.CANCELLED,
                                            "Invalid params");
            return;
        }

        global.display.request_pad_osd(padDevice, editionMode);
        invocation.return_value(null);
    }
});
Signals.addSignalMethods(PadOsdService.prototype);
