DrawOnYourScreen/area.js

1280 lines
51 KiB
JavaScript
Raw Normal View History

2019-03-05 08:36:59 -03:00
/* jslint esversion: 6 */
/* exported Tools, DrawingArea */
2019-03-05 08:36:59 -03:00
/*
* Copyright 2019 Abakkk
*
* This file is part of DrawOnYourScreen, a drawing extension for GNOME Shell.
2019-03-05 08:36:59 -03:00
* https://framagit.org/abakkk/DrawOnYourScreen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
const Cairo = imports.cairo;
const Clutter = imports.gi.Clutter;
const Gio = imports.gi.Gio;
2019-03-05 08:36:59 -03:00
const GLib = imports.gi.GLib;
2019-03-26 18:28:24 -03:00
const GObject = imports.gi.GObject;
2019-03-05 08:36:59 -03:00
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;
const Pango = imports.gi.Pango;
2019-03-05 08:36:59 -03:00
const St = imports.gi.St;
const System = imports.system;
2019-03-26 18:28:24 -03:00
const ExtensionUtils = imports.misc.extensionUtils;
const Main = imports.ui.main;
2019-03-05 08:36:59 -03:00
const Screenshot = imports.ui.screenshot;
const Me = ExtensionUtils.getCurrentExtension();
const Convenience = ExtensionUtils.getSettings ? ExtensionUtils : Me.imports.convenience;
2020-07-03 18:37:09 -03:00
const Elements = Me.imports.elements;
const Files = Me.imports.files;
2020-07-03 17:51:23 -03:00
const Menu = Me.imports.menu;
2020-01-06 11:29:01 -03:00
const _ = imports.gettext.domain(Me.metadata['gettext-domain']).gettext;
const pgettext = imports.gettext.domain(Me.metadata['gettext-domain']).pgettext;
2019-03-05 08:36:59 -03:00
2020-06-17 10:43:23 -03:00
const CAIRO_DEBUG_EXTENDS = false;
const SVG_DEBUG_EXTENDS = false;
2020-06-18 20:35:25 -03:00
const TEXT_CURSOR_TIME = 600; // ms
const ELEMENT_GRABBER_TIME = 80; // ms, default is about 16 ms
const GRID_TILES_HORIZONTAL_NUMBER = 30;
const { Shapes, Transformations } = Elements;
const { DisplayStrings } = Menu;
const FontGenericFamilies = ['Sans-Serif', 'Serif', 'Monospace', 'Cursive', 'Fantasy'];
const Manipulations = { MOVE: 100, RESIZE: 101, MIRROR: 102 };
var Tools = Object.assign({
getNameOf: function(value) {
return Object.keys(this).find(key => this[key] == value);
}
}, Shapes, Manipulations);
Object.defineProperty(Tools, 'getNameOf', { enumerable: false });
2019-03-05 08:36:59 -03:00
const getClutterColorFromString = function(string, fallback) {
let [success, color] = Clutter.Color.from_string(string);
color.toString = () => string;
if (success)
return color;
log(`${Me.metadata.uuid}: "${string}" color cannot be parsed.`);
color = Clutter.Color.get_static(Clutter.StaticColor[fallback.toUpperCase()]);
color.toString = () => fallback.slice(0, 1).toUpperCase() + fallback.slice(1);
return color;
};
2019-03-05 08:36:59 -03:00
// DrawingArea is the widget in which we draw, thanks to Cairo.
// It creates and manages a DrawingElement for each "brushstroke".
// It handles pointer/mouse/(touch?) events and some keyboard events.
var DrawingArea = new Lang.Class({
Name: 'DrawOnYourScreenDrawingArea',
2019-03-05 08:36:59 -03:00
Extends: St.DrawingArea,
2020-09-10 10:19:17 -03:00
Signals: { 'show-osd': { param_types: [Gio.Icon.$gtype, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_DOUBLE, GObject.TYPE_BOOLEAN] },
'update-action-mode': {},
'leave-drawing-mode': {} },
2019-03-05 08:36:59 -03:00
_init: function(params, monitor, helper, loadPersistent) {
2020-03-01 13:33:41 -03:00
this.parent({ style_class: 'draw-on-your-screen', name: params.name});
2019-03-07 12:32:06 -03:00
this.monitor = monitor;
2019-03-05 08:36:59 -03:00
this.helper = helper;
this.elements = [];
this.undoneElements = [];
this.currentElement = null;
this.currentTool = Shapes.NONE;
this.currentImage = null;
this.currentTextRightAligned = Clutter.get_default_text_direction() == Clutter.TextDirection.RTL;
let fontName = St.Settings && St.Settings.get().font_name || Convenience.getSettings('org.gnome.desktop.interface').get_string('font-name');
this.currentFont = Pango.FontDescription.from_string(fontName);
this.currentFont.unset_fields(Pango.FontMask.SIZE);
this.defaultFontFamily = this.currentFont.get_family();
this.currentLineWidth = 5;
this.currentLineJoin = Cairo.LineJoin.ROUND;
this.currentLineCap = Cairo.LineCap.ROUND;
this.currentFillRule = Cairo.FillRule.WINDING;
2019-03-07 12:32:06 -03:00
this.isSquareArea = false;
2020-06-05 10:58:58 -03:00
this.hasGrid = false;
2019-03-05 08:36:59 -03:00
this.hasBackground = false;
this.textHasCursor = false;
this.dashedLine = false;
2019-03-26 18:28:24 -03:00
this.fill = false;
2019-03-11 13:53:35 -03:00
this.connect('destroy', this._onDestroy.bind(this));
this.connect('notify::reactive', this._onReactiveChanged.bind(this));
this.drawingSettingsChangedHandler = Me.drawingSettings.connect('changed', this._onDrawingSettingsChanged.bind(this));
this._onDrawingSettingsChanged();
if (loadPersistent)
this._loadPersistent();
2019-03-05 08:36:59 -03:00
},
2019-10-11 04:39:17 -03:00
get menu() {
if (!this._menu)
this._menu = new Menu.DrawingMenu(this, this.monitor, Tools);
2019-10-11 04:39:17 -03:00
return this._menu;
},
closeMenu: function() {
if (this._menu)
this._menu.close();
},
get isWriting() {
return this.textEntry ? true : false;
},
get currentTool() {
return this._currentTool;
},
set currentTool(tool) {
this._currentTool = tool;
2020-06-27 17:35:43 -03:00
if (this.hasManipulationTool)
2020-06-17 19:57:54 -03:00
this._startElementGrabber();
else
2020-06-17 19:57:54 -03:00
this._stopElementGrabber();
},
get currentPalette() {
return this._currentPalette;
},
set currentPalette(palette) {
this._currentPalette = palette;
this.colors = palette[1].map(colorString => getClutterColorFromString(colorString, 'white'));
if (!this.colors[0])
this.colors.push(Clutter.Color.get_static(Clutter.StaticColor.WHITE));
},
get currentImage() {
if (!this._currentImage)
this._currentImage = Files.Images.getNext(this._currentImage);
return this._currentImage;
},
set currentImage(image) {
this._currentImage = image;
},
get currentFontFamily() {
return this.currentFont.get_family();
},
set currentFontFamily(family) {
this.currentFont.set_family(family);
},
get currentFontStyle() {
return this.currentFont.get_style();
},
set currentFontStyle(style) {
this.currentFont.set_style(style);
},
get currentFontWeight() {
return this.currentFont.get_weight();
},
set currentFontWeight(weight) {
this.currentFont.set_weight(weight);
},
2020-06-27 17:35:43 -03:00
get hasManipulationTool() {
// No Object.values method in GS 3.24.
return Object.keys(Manipulations).map(key => Manipulations[key]).indexOf(this.currentTool) != -1;
},
// Boolean wrapper for switch menu item.
get currentEvenodd() {
return this.currentFillRule == Cairo.FillRule.EVEN_ODD;
},
set currentEvenodd(evenodd) {
this.currentFillRule = evenodd ? Cairo.FillRule.EVEN_ODD : Cairo.FillRule.WINDING;
},
get fontFamilies() {
if (!this._fontFamilies) {
2020-09-10 10:19:17 -03:00
let otherFontFamilies = Elements.getAllFontFamilies().filter(family => {
return family != this.defaultFontFamily && FontGenericFamilies.indexOf(family) == -1;
});
2020-09-10 10:19:17 -03:00
this._fontFamilies = [this.defaultFontFamily].concat(FontGenericFamilies, otherFontFamilies);
}
return this._fontFamilies;
},
vfunc_repaint: function() {
let cr = this.get_context();
try {
this._repaint(cr);
} catch(e) {
logError(e, "An error occured while painting");
}
cr.$dispose();
if (this.elements.some(element => element.shape == Shapes.IMAGE) || this.currentElement && this.currentElement.shape == Shapes.IMAGE)
System.gc();
},
2019-03-05 08:36:59 -03:00
_redisplay: function() {
// force area to emit 'repaint'
this.queue_repaint();
},
_onDrawingSettingsChanged: function() {
this.palettes = Me.drawingSettings.get_value('palettes').deep_unpack();
if (!this.colors) {
if (this.palettes[0])
this.currentPalette = this.palettes[0];
else
this.currentPalette = ['Palette', ['White']];
2019-03-05 08:36:59 -03:00
}
if (!this.currentColor)
this.currentColor = this.colors[0];
2019-03-05 08:36:59 -03:00
if (Me.drawingSettings.get_boolean('square-area-auto')) {
this.squareAreaSize = Math.pow(2, 6);
while (this.squareAreaSize * 2 < Math.min(this.monitor.width, this.monitor.height))
this.squareAreaSize *= 2;
} else {
this.squareAreaSize = Me.drawingSettings.get_uint('square-area-size');
2019-03-05 08:36:59 -03:00
}
this.areaBackgroundColor = getClutterColorFromString(Me.drawingSettings.get_string('background-color'), 'black');
this.gridColor = getClutterColorFromString(Me.drawingSettings.get_string('grid-color'), 'gray');
if (Me.drawingSettings.get_boolean('grid-line-auto')) {
this.gridLineSpacing = Math.round(this.monitor.width / (5 * GRID_TILES_HORIZONTAL_NUMBER));
this.gridLineWidth = this.gridLineSpacing / 20;
} else {
this.gridLineSpacing = Me.drawingSettings.get_uint('grid-line-spacing');
this.gridLineWidth = Math.round(Me.drawingSettings.get_double('grid-line-width') * 100) / 100;
}
this.dashOffset = Math.round(Me.drawingSettings.get_double('dash-offset') * 100) / 100;
if (Me.drawingSettings.get_boolean('dash-array-auto')) {
this.dashArray = [0, 0];
} else {
let on = Math.round(Me.drawingSettings.get_double('dash-array-on') * 100) / 100;
let off = Math.round(Me.drawingSettings.get_double('dash-array-off') * 100) / 100;
this.dashArray = [on, off];
}
2019-03-05 08:36:59 -03:00
},
_repaint: function(cr) {
2020-06-17 10:43:23 -03:00
if (CAIRO_DEBUG_EXTENDS) {
cr.scale(0.5, 0.5);
cr.translate(this.monitor.width, this.monitor.height);
}
2019-03-05 08:36:59 -03:00
for (let i = 0; i < this.elements.length; i++) {
cr.save();
2020-06-17 19:57:54 -03:00
this.elements[i].buildCairo(cr, { showTextRectangle: this.grabbedElement && this.grabbedElement == this.elements[i],
drawTextRectangle: this.grabPoint ? true : false });
2020-06-17 19:57:54 -03:00
if (this.grabPoint)
this._searchElementToGrab(cr, this.elements[i]);
2020-06-17 20:03:50 -03:00
if (this.elements[i].fill && !this.elements[i].isStraightLine) {
cr.fillPreserve();
if (this.elements[i].shape == Shapes.NONE || this.elements[i].shape == Shapes.LINE)
cr.closePath();
}
cr.stroke();
cr.restore();
2019-03-05 08:36:59 -03:00
}
if (this.currentElement) {
cr.save();
this.currentElement.buildCairo(cr, { showTextCursor: this.textHasCursor,
showTextRectangle: this.currentElement.shape != Shapes.TEXT || !this.isWriting,
dummyStroke: this.currentElement.fill && this.currentElement.line.lineWidth == 0 });
2019-03-05 08:36:59 -03:00
cr.stroke();
cr.restore();
2019-03-05 08:36:59 -03:00
}
if (this.reactive && this.hasGrid) {
cr.save();
2020-06-05 10:58:58 -03:00
Clutter.cairo_set_source_color(cr, this.gridColor);
2020-07-11 17:42:48 -03:00
let [gridX, gridY] = [0, 0];
while (gridX < this.monitor.width / 2) {
cr.setLineWidth((gridX / this.gridLineSpacing) % 5 ? this.gridLineWidth / 2 : this.gridLineWidth);
2020-07-11 17:42:48 -03:00
cr.moveTo(this.monitor.width / 2 + gridX, 0);
cr.lineTo(this.monitor.width / 2 + gridX, this.monitor.height);
cr.moveTo(this.monitor.width / 2 - gridX, 0);
cr.lineTo(this.monitor.width / 2 - gridX, this.monitor.height);
gridX += this.gridLineSpacing;
2020-06-05 10:58:58 -03:00
cr.stroke();
}
2020-07-11 17:42:48 -03:00
while (gridY < this.monitor.height / 2) {
cr.setLineWidth((gridY / this.gridLineSpacing) % 5 ? this.gridLineWidth / 2 : this.gridLineWidth);
2020-07-11 17:42:48 -03:00
cr.moveTo(0, this.monitor.height / 2 + gridY);
cr.lineTo(this.monitor.width, this.monitor.height / 2 + gridY);
cr.moveTo(0, this.monitor.height / 2 - gridY);
cr.lineTo(this.monitor.width, this.monitor.height / 2 - gridY);
gridY += this.gridLineSpacing;
2020-06-05 10:58:58 -03:00
cr.stroke();
}
cr.restore();
2020-06-05 10:58:58 -03:00
}
2019-03-05 08:36:59 -03:00
},
_onButtonPressed: function(actor, event) {
if (this.spaceKeyPressed)
return Clutter.EVENT_PROPAGATE;
2019-03-05 08:36:59 -03:00
let button = event.get_button();
let [x, y] = event.get_coords();
let controlPressed = event.has_control_modifier();
2019-03-05 08:36:59 -03:00
let shiftPressed = event.has_shift_modifier();
if (this.currentElement && this.currentElement.shape == Shapes.TEXT && this.isWriting)
// finish writing
2019-03-05 08:36:59 -03:00
this._stopWriting();
if (this.helper.visible) {
// hide helper
this.toggleHelp();
2019-03-05 08:36:59 -03:00
return Clutter.EVENT_STOP;
}
if (button == 1) {
2020-06-27 17:35:43 -03:00
if (this.hasManipulationTool) {
2020-06-17 19:57:54 -03:00
if (this.grabbedElement)
this._startTransforming(x, y, controlPressed, shiftPressed);
} else {
this._startDrawing(x, y, shiftPressed);
}
2019-03-05 08:36:59 -03:00
return Clutter.EVENT_STOP;
} else if (button == 2) {
2020-08-05 19:04:12 -03:00
this.switchFill();
2019-03-05 08:36:59 -03:00
} else if (button == 3) {
this._stopDrawing();
2019-03-26 18:28:24 -03:00
this.menu.open(x, y);
2019-03-05 08:36:59 -03:00
return Clutter.EVENT_STOP;
}
return Clutter.EVENT_PROPAGATE;
},
_onKeyboardPopupMenu: function() {
this._stopDrawing();
if (this.helper.visible)
this.toggleHelp();
this.menu.popup();
return Clutter.EVENT_STOP;
},
_onStageKeyPressed: function(actor, event) {
if (event.get_key_symbol() == Clutter.KEY_space)
this.spaceKeyPressed = true;
return Clutter.EVENT_PROPAGATE;
},
_onStageKeyReleased: function(actor, event) {
if (event.get_key_symbol() == Clutter.KEY_space)
this.spaceKeyPressed = false;
return Clutter.EVENT_PROPAGATE;
},
2019-03-05 08:36:59 -03:00
_onKeyPressed: function(actor, event) {
if (this.currentElement && this.currentElement.shape == Shapes.LINE) {
if (event.get_key_symbol() == Clutter.KEY_Return ||
event.get_key_symbol() == Clutter.KEY_KP_Enter ||
event.get_key_symbol() == Clutter.KEY_Control_L) {
2020-06-20 06:17:56 -03:00
if (this.currentElement.points.length == 2)
// Translators: %s is a key label
this.emit('show-osd', Files.Icons.ARC, _("Press <i>%s</i> to get\na fourth control point")
.format(Gtk.accelerator_get_label(Clutter.KEY_Return, 0)), "", -1, true);
this.currentElement.addPoint();
this.updatePointerCursor(true);
this._redisplay();
return Clutter.EVENT_STOP;
} else {
return Clutter.EVENT_PROPAGATE;
}
} else if (this.currentElement &&
(this.currentElement.shape == Shapes.POLYGON || this.currentElement.shape == Shapes.POLYLINE) &&
(event.get_key_symbol() == Clutter.KEY_Return || event.get_key_symbol() == Clutter.KEY_KP_Enter)) {
this.currentElement.addPoint();
return Clutter.EVENT_STOP;
} else if (event.get_key_symbol() == Clutter.KEY_Escape) {
if (this.helper.visible)
this.toggleHelp();
else
this.emit('leave-drawing-mode');
return Clutter.EVENT_STOP;
2019-03-11 15:07:01 -03:00
2019-03-05 08:36:59 -03:00
} else {
return Clutter.EVENT_PROPAGATE;
}
},
_onScroll: function(actor, event) {
if (this.helper.visible)
return Clutter.EVENT_PROPAGATE;
let direction = event.get_scroll_direction();
if (direction == Clutter.ScrollDirection.UP)
this.incrementLineWidth(1);
else if (direction == Clutter.ScrollDirection.DOWN)
this.incrementLineWidth(-1);
else
return Clutter.EVENT_PROPAGATE;
return Clutter.EVENT_STOP;
},
2020-06-17 19:57:54 -03:00
_searchElementToGrab: function(cr, element) {
if (element.getContainsPoint(cr, this.grabPoint[0], this.grabPoint[1]))
this.grabbedElement = element;
else if (this.grabbedElement == element)
this.grabbedElement = null;
if (element == this.elements[this.elements.length - 1])
// All elements have been tested, the winner is the last.
this.updatePointerCursor();
},
2020-06-17 19:57:54 -03:00
_startElementGrabber: function() {
if (this.elementGrabberHandler)
return;
2020-06-17 19:57:54 -03:00
this.elementGrabberHandler = this.connect('motion-event', (actor, event) => {
if (this.motionHandler || this.grabbedElementLocked) {
this.grabPoint = null;
return;
}
// Reduce computing without notable effect.
if (event.get_time() - (this.elementGrabberTimestamp || 0) < ELEMENT_GRABBER_TIME)
return;
this.elementGrabberTimestamp = event.get_time();
let coords = event.get_coords();
let [s, x, y] = this.transform_stage_point(coords[0], coords[1]);
if (!s)
return;
2020-06-17 19:57:54 -03:00
this.grabPoint = [x, y];
this.grabbedElement = null;
// this._redisplay calls this._searchElementToGrab.
this._redisplay();
});
},
2020-06-17 19:57:54 -03:00
_stopElementGrabber: function() {
if (this.elementGrabberHandler) {
this.disconnect(this.elementGrabberHandler);
this.grabPoint = null;
this.elementGrabberHandler = null;
}
},
_startTransforming: function(stageX, stageY, controlPressed, duplicate) {
let [success, startX, startY] = this.transform_stage_point(stageX, stageY);
if (!success)
return;
if (this.currentTool == Manipulations.MIRROR) {
2020-06-17 19:57:54 -03:00
this.grabbedElementLocked = !this.grabbedElementLocked;
if (this.grabbedElementLocked) {
this.updatePointerCursor();
2020-06-20 06:17:56 -03:00
let label = controlPressed ? _("Mark a point of symmetry") : _("Draw a line of symmetry");
this.emit('show-osd', Files.Icons.TOOL_MIRROR, label, "", -1, true);
return;
}
}
2020-06-17 19:57:54 -03:00
this.grabPoint = null;
this.buttonReleasedHandler = this.connect('button-release-event', (actor, event) => {
this._stopTransforming();
});
if (duplicate) {
// deep cloning
2020-07-08 06:47:51 -03:00
let copy = new this.grabbedElement.constructor(JSON.parse(JSON.stringify(this.grabbedElement)));
if (this.grabbedElement.color)
copy.color = this.grabbedElement.color;
if (this.grabbedElement.font)
copy.font = this.grabbedElement.font;
if (this.grabbedElement.image)
copy.image = this.grabbedElement.image;
this.elements.push(copy);
2020-06-17 19:57:54 -03:00
this.grabbedElement = copy;
}
if (this.currentTool == Manipulations.MOVE)
2020-06-17 19:57:54 -03:00
this.grabbedElement.startTransformation(startX, startY, controlPressed ? Transformations.ROTATION : Transformations.TRANSLATION);
else if (this.currentTool == Manipulations.RESIZE)
2020-06-18 20:24:42 -03:00
this.grabbedElement.startTransformation(startX, startY, controlPressed ? Transformations.STRETCH : Transformations.SCALE_PRESERVE);
else if (this.currentTool == Manipulations.MIRROR) {
2020-06-17 19:57:54 -03:00
this.grabbedElement.startTransformation(startX, startY, controlPressed ? Transformations.INVERSION : Transformations.REFLECTION);
this._redisplay();
}
this.motionHandler = this.connect('motion-event', (actor, event) => {
if (this.spaceKeyPressed)
return;
let coords = event.get_coords();
let [s, x, y] = this.transform_stage_point(coords[0], coords[1]);
if (!s)
return;
let controlPressed = event.has_control_modifier();
this._updateTransforming(x, y, controlPressed);
});
},
_updateTransforming: function(x, y, controlPressed) {
2020-06-17 19:57:54 -03:00
if (controlPressed && this.grabbedElement.lastTransformation.type == Transformations.TRANSLATION) {
this.grabbedElement.stopTransformation();
this.grabbedElement.startTransformation(x, y, Transformations.ROTATION);
} else if (!controlPressed && this.grabbedElement.lastTransformation.type == Transformations.ROTATION) {
this.grabbedElement.stopTransformation();
this.grabbedElement.startTransformation(x, y, Transformations.TRANSLATION);
}
2020-06-17 19:57:54 -03:00
if (controlPressed && this.grabbedElement.lastTransformation.type == Transformations.SCALE_PRESERVE) {
this.grabbedElement.stopTransformation();
2020-06-18 20:24:42 -03:00
this.grabbedElement.startTransformation(x, y, Transformations.STRETCH);
} else if (!controlPressed && this.grabbedElement.lastTransformation.type == Transformations.STRETCH) {
2020-06-17 19:57:54 -03:00
this.grabbedElement.stopTransformation();
this.grabbedElement.startTransformation(x, y, Transformations.SCALE_PRESERVE);
}
2020-06-17 19:57:54 -03:00
if (controlPressed && this.grabbedElement.lastTransformation.type == Transformations.REFLECTION) {
this.grabbedElement.transformations.pop();
this.grabbedElement.startTransformation(x, y, Transformations.INVERSION);
} else if (!controlPressed && this.grabbedElement.lastTransformation.type == Transformations.INVERSION) {
this.grabbedElement.transformations.pop();
this.grabbedElement.startTransformation(x, y, Transformations.REFLECTION);
}
2020-06-17 19:57:54 -03:00
this.grabbedElement.updateTransformation(x, y);
this._redisplay();
},
_stopTransforming: function() {
if (this.motionHandler) {
this.disconnect(this.motionHandler);
this.motionHandler = null;
}
if (this.buttonReleasedHandler) {
this.disconnect(this.buttonReleasedHandler);
this.buttonReleasedHandler = null;
}
2020-06-17 19:57:54 -03:00
this.grabbedElement.stopTransformation();
this.grabbedElement = null;
this.grabbedElementLocked = false;
this._redisplay();
},
_startDrawing: function(stageX, stageY, eraser) {
2019-03-05 08:36:59 -03:00
let [success, startX, startY] = this.transform_stage_point(stageX, stageY);
if (!success)
return;
this.buttonReleasedHandler = this.connect('button-release-event', (actor, event) => {
this._stopDrawing();
});
if (this.currentTool == Shapes.TEXT) {
2020-07-08 06:47:51 -03:00
this.currentElement = new Elements.DrawingElement({
shape: this.currentTool,
color: this.currentColor,
2020-07-08 06:47:51 -03:00
eraser: eraser,
font: this.currentFont.copy(),
// Translators: initial content of the text area
text: pgettext("text-area-content", "Text"),
2020-07-08 06:47:51 -03:00
textRightAligned: this.currentTextRightAligned,
points: []
});
} else if (this.currentTool == Shapes.IMAGE) {
this.currentElement = new Elements.DrawingElement({
shape: this.currentTool,
color: this.currentColor,
eraser: eraser,
image: this.currentImage,
operator: this.currentOperator,
points: []
});
2020-07-08 06:47:51 -03:00
} else {
this.currentElement = new Elements.DrawingElement({
shape: this.currentTool,
color: this.currentColor,
2020-07-08 06:47:51 -03:00
eraser: eraser,
fill: this.fill,
fillRule: this.currentFillRule,
line: { lineWidth: this.currentLineWidth, lineJoin: this.currentLineJoin, lineCap: this.currentLineCap },
dash: { active: this.dashedLine, array: this.dashedLine ? [this.dashArray[0] || this.currentLineWidth, this.dashArray[1] || this.currentLineWidth * 3] : [0, 0] , offset: this.dashOffset },
points: []
});
2019-03-27 22:00:57 -03:00
}
this.currentElement.startDrawing(startX, startY);
if (this.currentTool == Shapes.POLYGON || this.currentTool == Shapes.POLYLINE) {
let icon = Files.Icons[this.currentTool == Shapes.POLYGON ? 'TOOL_POLYGON' : 'TOOL_POLYLINE'];
// Translators: %s is a key label
this.emit('show-osd', icon, _("Press <i>%s</i> to mark vertices")
.format(Gtk.accelerator_get_label(Clutter.KEY_Return, 0)), "", -1, true);
}
2019-03-05 08:36:59 -03:00
this.motionHandler = this.connect('motion-event', (actor, event) => {
if (this.spaceKeyPressed)
return;
2019-03-05 08:36:59 -03:00
let coords = event.get_coords();
let [s, x, y] = this.transform_stage_point(coords[0], coords[1]);
if (!s)
return;
let controlPressed = event.has_control_modifier();
this._updateDrawing(x, y, controlPressed);
2019-03-05 08:36:59 -03:00
});
},
_updateDrawing: function(x, y, controlPressed) {
if (!this.currentElement)
return;
this.currentElement.updateDrawing(x, y, controlPressed);
this._redisplay();
this.updatePointerCursor(controlPressed);
},
2019-03-05 08:36:59 -03:00
_stopDrawing: function() {
if (this.motionHandler) {
this.disconnect(this.motionHandler);
this.motionHandler = null;
}
if (this.buttonReleasedHandler) {
this.disconnect(this.buttonReleasedHandler);
this.buttonReleasedHandler = null;
}
// skip when a polygon has not at least 3 points
if (this.currentElement && this.currentElement.shape == Shapes.POLYGON && this.currentElement.points.length < 3)
this.currentElement = null;
if (this.currentElement)
this.currentElement.stopDrawing();
if (this.currentElement && this.currentElement.points.length >= 2) {
if (this.currentElement.shape == Shapes.TEXT && !this.isWriting) {
this._startWriting();
return;
}
2019-03-05 08:36:59 -03:00
this.elements.push(this.currentElement);
}
2019-03-05 08:36:59 -03:00
this.currentElement = null;
this._redisplay();
this.updatePointerCursor();
2019-03-05 08:36:59 -03:00
},
_startWriting: function() {
let [x, y] = [this.currentElement.x, this.currentElement.y];
this.currentElement.text = '';
this.currentElement.cursorPosition = 0;
// Translators: %s is a key label
this.emit('show-osd', Files.Icons.TOOL_TEXT, _("Type your text and press <i>%s</i>")
.format(Gtk.accelerator_get_label(Clutter.KEY_Escape, 0)), "", -1, true);
this._updateTextCursorTimeout();
this.textHasCursor = true;
this._redisplay();
this.textEntry = new St.Entry({ visible: false, x, y });
this.get_parent().add_child(this.textEntry);
this.textEntry.grab_key_focus();
this.updateActionMode();
2020-06-28 13:37:42 -03:00
this.updatePointerCursor();
let ibusCandidatePopup = Main.layoutManager.uiGroup.get_children().filter(child =>
child.has_style_class_name && child.has_style_class_name('candidate-popup-boxpointer'))[0] || null;
if (ibusCandidatePopup) {
this.ibusHandler = ibusCandidatePopup.connect('notify::visible', popup => popup.visible && (this.textEntry.visible = true));
this.textEntry.connect('destroy', () => ibusCandidatePopup.disconnect(this.ibusHandler));
}
this.textEntry.clutterText.connect('activate', (clutterText) => {
let startNewLine = true;
this._stopWriting(startNewLine);
clutterText.text = "";
});
this.textEntry.clutterText.connect('text-changed', (clutterText) => {
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
this.currentElement.text = clutterText.text;
this.currentElement.cursorPosition = clutterText.cursorPosition;
this._updateTextCursorTimeout();
this._redisplay();
});
});
this.textEntry.clutterText.connect('key-press-event', (clutterText, event) => {
if (event.get_key_symbol() == Clutter.KEY_Escape) {
this._stopWriting();
return Clutter.EVENT_STOP;
}
// 'cursor-changed' signal is not emitted if the text entry is not visible.
// So key events related to the cursor must be listened.
if (event.get_key_symbol() == Clutter.KEY_Left || event.get_key_symbol() == Clutter.KEY_Right ||
event.get_key_symbol() == Clutter.KEY_Home || event.get_key_symbol() == Clutter.KEY_End) {
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
this.currentElement.cursorPosition = clutterText.cursorPosition;
this._updateTextCursorTimeout();
this.textHasCursor = true;
this._redisplay();
});
}
return Clutter.EVENT_PROPAGATE;
});
},
_stopWriting: function(startNewLine) {
if (this.currentElement.text.length > 0)
this.elements.push(this.currentElement);
if (startNewLine && this.currentElement.points.length == 2) {
this.currentElement.lineIndex = this.currentElement.lineIndex || 0;
// copy object, the original keep existing in this.elements
this.currentElement = Object.create(this.currentElement);
this.currentElement.lineIndex ++;
// define a new 'points' array, the original keep existing in this.elements
this.currentElement.points = [
[this.currentElement.points[0][0], this.currentElement.points[0][1] + this.currentElement.height],
[this.currentElement.points[1][0], this.currentElement.points[1][1] + this.currentElement.height]
];
this.currentElement.text = "";
this.textEntry.set_y(this.currentElement.y);
} else {
this.currentElement = null;
this._stopTextCursorTimeout();
this.textEntry.destroy();
delete this.textEntry;
this.grab_key_focus();
this.updateActionMode();
2020-06-28 13:37:42 -03:00
this.updatePointerCursor();
}
2019-03-05 08:36:59 -03:00
this._redisplay();
},
setPointerCursor: function(pointerCursorName) {
if (!this.currentPointerCursorName || this.currentPointerCursorName != pointerCursorName) {
this.currentPointerCursorName = pointerCursorName;
2020-08-31 08:05:41 -03:00
Me.stateObj.areaManager.setCursor(pointerCursorName);
}
},
updatePointerCursor: function(controlPressed) {
2020-06-17 19:57:54 -03:00
if (this.currentTool == Manipulations.MIRROR && this.grabbedElementLocked)
this.setPointerCursor('CROSSHAIR');
2020-06-27 17:35:43 -03:00
else if (this.hasManipulationTool)
2020-06-17 19:57:54 -03:00
this.setPointerCursor(this.grabbedElement ? 'MOVE_OR_RESIZE_WINDOW' : 'DEFAULT');
2020-06-28 13:37:42 -03:00
else if (this.currentElement && this.currentElement.shape == Shapes.TEXT && this.isWriting)
this.setPointerCursor('IBEAM');
else if (!this.currentElement)
this.setPointerCursor(this.currentTool == Shapes.NONE ? 'POINTING_HAND' : 'CROSSHAIR');
else if (this.currentElement.shape != Shapes.NONE && controlPressed)
this.setPointerCursor('MOVE_OR_RESIZE_WINDOW');
},
initPointerCursor: function() {
this.currentPointerCursorName = null;
this.updatePointerCursor();
},
_stopTextCursorTimeout: function() {
if (this.textCursorTimeoutId) {
2020-06-18 20:35:25 -03:00
GLib.source_remove(this.textCursorTimeoutId);
this.textCursorTimeoutId = null;
2019-03-05 08:36:59 -03:00
}
this.textHasCursor = false;
},
_updateTextCursorTimeout: function() {
this._stopTextCursorTimeout();
2020-06-18 20:35:25 -03:00
this.textCursorTimeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, TEXT_CURSOR_TIME, () => {
2019-03-05 08:36:59 -03:00
this.textHasCursor = !this.textHasCursor;
this._redisplay();
2020-01-01 21:44:08 -03:00
return GLib.SOURCE_CONTINUE;
2019-03-05 08:36:59 -03:00
});
},
erase: function() {
this.deleteLastElement();
2019-03-05 08:36:59 -03:00
this.elements = [];
this.undoneElements = [];
this._redisplay();
},
deleteLastElement: function() {
if (this.currentElement) {
if (this.motionHandler) {
this.disconnect(this.motionHandler);
this.motionHandler = null;
}
if (this.buttonReleasedHandler) {
this.disconnect(this.buttonReleasedHandler);
this.buttonReleasedHandler = null;
}
if (this.isWriting)
this._stopWriting();
2019-03-05 08:36:59 -03:00
this.currentElement = null;
} else {
this.elements.pop();
}
this._redisplay();
},
undo: function() {
if (this.elements.length > 0)
this.undoneElements.push(this.elements.pop());
this._redisplay();
},
redo: function() {
if (this.undoneElements.length > 0)
this.elements.push(this.undoneElements.pop());
this._redisplay();
},
2019-03-05 17:08:43 -03:00
smoothLastElement: function() {
if (this.elements.length > 0 && this.elements[this.elements.length - 1].shape == Shapes.NONE) {
this.elements[this.elements.length - 1].smoothAll();
this._redisplay();
}
},
2019-03-05 08:36:59 -03:00
toggleBackground: function() {
this.hasBackground = !this.hasBackground;
this.get_parent().set_background_color(this.hasBackground ? this.areaBackgroundColor : null);
2019-03-05 08:36:59 -03:00
},
2020-06-05 10:58:58 -03:00
toggleGrid: function() {
this.hasGrid = !this.hasGrid;
this._redisplay();
},
2019-03-07 12:32:06 -03:00
toggleSquareArea: function() {
this.isSquareArea = !this.isSquareArea;
if (this.isSquareArea) {
this.set_position((this.monitor.width - this.squareAreaSize) / 2, (this.monitor.height - this.squareAreaSize) / 2);
this.set_size(this.squareAreaSize, this.squareAreaSize);
2019-03-07 12:32:06 -03:00
this.add_style_class_name('draw-on-your-screen-square-area');
} else {
2019-03-11 14:08:19 -03:00
this.set_position(0, 0);
2019-03-07 12:32:06 -03:00
this.set_size(this.monitor.width, this.monitor.height);
this.remove_style_class_name('draw-on-your-screen-square-area');
}
},
2019-03-05 08:36:59 -03:00
selectColor: function(index) {
if (!this.colors[index])
return;
2019-03-05 08:36:59 -03:00
this.currentColor = this.colors[index];
if (this.currentElement) {
this.currentElement.color = this.currentColor;
2019-03-05 08:36:59 -03:00
this._redisplay();
}
// Foreground color markup is not displayed since 3.36, use style instead but the transparency is lost.
this.emit('show-osd', Files.Icons.COLOR, String(this.currentColor), this.currentColor.to_string().slice(0, 7), -1, false);
2019-03-05 08:36:59 -03:00
},
selectTool: function(tool) {
this.currentTool = tool;
this.emit('show-osd', Files.Icons[`TOOL_${Tools.getNameOf(tool)}`] || null, DisplayStrings.Tool[tool], "", -1, false);
this.updatePointerCursor();
2019-03-05 08:36:59 -03:00
},
2020-08-05 19:04:12 -03:00
switchFill: function() {
this.fill = !this.fill;
let icon = Files.Icons[this.fill ? 'FILL' : 'STROKE'];
this.emit('show-osd', icon, DisplayStrings.getFill(this.fill), "", -1, false);
},
switchFillRule: function() {
this.currentFillRule = this.currentFillRule == 1 ? 0 : this.currentFillRule + 1;
let icon = Files.Icons[this.currentEvenodd ? 'FILLRULE_EVENODD' : 'FILLRULE_NONZERO'];
this.emit('show-osd', icon, DisplayStrings.FillRule[this.currentFillRule], "", -1, false);
},
switchColorPalette: function(reverse) {
let index = this.palettes.indexOf(this.currentPalette);
if (reverse)
this.currentPalette = index <= 0 ? this.palettes[this.palettes.length - 1] : this.palettes[index - 1];
else
this.currentPalette = index == this.palettes.length - 1 ? this.palettes[0] : this.palettes[index + 1];
this.emit('show-osd', Files.Icons.PALETTE, this.currentPalette[0], "", -1, false);
},
2020-08-05 19:04:12 -03:00
switchDash: function() {
2019-03-05 08:36:59 -03:00
this.dashedLine = !this.dashedLine;
let icon = Files.Icons[this.dashedLine ? 'DASHED_LINE' : 'FULL_LINE'];
this.emit('show-osd', icon, DisplayStrings.getDashedLine(this.dashedLine), "", -1, false);
2019-03-05 08:36:59 -03:00
},
incrementLineWidth: function(increment) {
this.currentLineWidth = Math.max(this.currentLineWidth + increment, 0);
this.emit('show-osd', null, DisplayStrings.getPixels(this.currentLineWidth), "", 2 * this.currentLineWidth, false);
2019-03-05 08:36:59 -03:00
},
2020-08-05 19:04:12 -03:00
switchLineJoin: function() {
2019-03-05 08:36:59 -03:00
this.currentLineJoin = this.currentLineJoin == 2 ? 0 : this.currentLineJoin + 1;
this.emit('show-osd', Files.Icons.LINEJOIN, DisplayStrings.LineJoin[this.currentLineJoin], "", -1, false);
2019-03-05 08:36:59 -03:00
},
2020-08-05 19:04:12 -03:00
switchLineCap: function() {
2019-03-05 08:36:59 -03:00
this.currentLineCap = this.currentLineCap == 2 ? 0 : this.currentLineCap + 1;
this.emit('show-osd', Files.Icons.LINECAP, DisplayStrings.LineCap[this.currentLineCap], "", -1, false);
2019-03-05 08:36:59 -03:00
},
2020-08-05 19:04:12 -03:00
switchFontWeight: function() {
let fontWeights = Object.keys(DisplayStrings.FontWeight).map(key => Number(key));
let index = fontWeights.indexOf(this.currentFontWeight);
this.currentFontWeight = index == fontWeights.length - 1 ? fontWeights[0] : fontWeights[index + 1];
if (this.currentElement && this.currentElement.font) {
this.currentElement.font.set_weight(this.currentFontWeight);
2019-03-05 08:36:59 -03:00
this._redisplay();
}
this.emit('show-osd', Files.Icons.FONT_WEIGHT, `<span font_weight="${this.currentFontWeight}">` +
`${DisplayStrings.FontWeight[this.currentFontWeight]}</span>`, "", -1, false);
2019-03-05 08:36:59 -03:00
},
2020-08-05 19:04:12 -03:00
switchFontStyle: function() {
2019-03-05 08:36:59 -03:00
this.currentFontStyle = this.currentFontStyle == 2 ? 0 : this.currentFontStyle + 1;
if (this.currentElement && this.currentElement.font) {
this.currentElement.font.set_style(this.currentFontStyle);
2019-03-05 08:36:59 -03:00
this._redisplay();
}
this.emit('show-osd', Files.Icons.FONT_STYLE, `<span font_style="${DisplayStrings.FontStyleMarkup[this.currentFontStyle]}">` +
`${DisplayStrings.FontStyle[this.currentFontStyle]}</span>`, "", -1, false);
2019-03-05 08:36:59 -03:00
},
2020-08-05 19:26:10 -03:00
switchFontFamily: function(reverse) {
let index = Math.max(0, this.fontFamilies.indexOf(this.currentFontFamily));
2020-08-05 19:26:10 -03:00
if (reverse)
this.currentFontFamily = (index == 0) ? this.fontFamilies[this.fontFamilies.length - 1] : this.fontFamilies[index - 1];
else
this.currentFontFamily = (index == this.fontFamilies.length - 1) ? this.fontFamilies[0] : this.fontFamilies[index + 1];
if (this.currentElement && this.currentElement.font) {
this.currentElement.font.set_family(this.currentFontFamily);
2019-03-05 08:36:59 -03:00
this._redisplay();
}
this.emit('show-osd', Files.Icons.FONT_FAMILY, `<span font_family="${this.currentFontFamily}">${DisplayStrings.getFontFamily(this.currentFontFamily)}</span>`, "", -1, false);
2019-03-05 08:36:59 -03:00
},
2020-08-05 19:04:12 -03:00
switchTextAlignment: function() {
this.currentTextRightAligned = !this.currentTextRightAligned;
if (this.currentElement && this.currentElement.textRightAligned !== undefined) {
this.currentElement.textRightAligned = this.currentTextRightAligned;
this._redisplay();
}
let icon = Files.Icons[this.currentTextRightAligned ? 'RIGHT_ALIGNED' : 'LEFT_ALIGNED'];
this.emit('show-osd', icon, DisplayStrings.getTextAlignment(this.currentTextRightAligned), "", -1, false);
},
switchImageFile: function(reverse) {
this.currentImage = Files.Images[reverse ? 'getPrevious' : 'getNext'](this.currentImage);
if (this.currentImage)
this.emit('show-osd', this.currentImage.gicon, this.currentImage.toString(), "", -1, false);
},
2020-09-09 17:25:56 -03:00
pasteImageFiles: function() {
Files.Images.addImagesFromClipboard(lastImage => {
this.currentImage = lastImage;
2020-09-09 17:25:56 -03:00
this.currentTool = Shapes.IMAGE;
this.updatePointerCursor();
this.emit('show-osd', this.currentImage.gicon, this.currentImage.toString(), "", -1, false);
2020-09-09 17:25:56 -03:00
});
},
2019-03-05 08:36:59 -03:00
toggleHelp: function() {
if (this.helper.visible) {
2019-03-05 08:36:59 -03:00
this.helper.hideHelp();
if (this.textEntry)
this.textEntry.grab_key_focus();
} else {
2019-03-05 08:36:59 -03:00
this.helper.showHelp();
this.grab_key_focus();
}
2019-03-05 08:36:59 -03:00
},
// The area is reactive when it is modal.
_onReactiveChanged: function() {
if (this.hasGrid)
this._redisplay();
if (this.helper.visible)
this.toggleHelp();
if (this.textEntry && this.reactive)
this.textEntry.grab_key_focus();
},
_onDestroy: function() {
Me.drawingSettings.disconnect(this.drawingSettingsChangedHandler);
this.erase();
if (this._menu)
this._menu.disable();
},
updateActionMode: function() {
this.emit('update-action-mode');
},
2019-03-05 08:36:59 -03:00
enterDrawingMode: function() {
this.stageKeyPressedHandler = global.stage.connect('key-press-event', this._onStageKeyPressed.bind(this));
this.stageKeyReleasedHandler = global.stage.connect('key-release-event', this._onStageKeyReleased.bind(this));
this.keyPressedHandler = this.connect('key-press-event', this._onKeyPressed.bind(this));
2019-03-05 08:36:59 -03:00
this.buttonPressedHandler = this.connect('button-press-event', this._onButtonPressed.bind(this));
this.keyboardPopupMenuHandler = this.connect('popup-menu', this._onKeyboardPopupMenu.bind(this));
2019-03-05 08:36:59 -03:00
this.scrollHandler = this.connect('scroll-event', this._onScroll.bind(this));
this.get_parent().set_background_color(this.reactive && this.hasBackground ? this.areaBackgroundColor : null);
2019-03-05 08:36:59 -03:00
},
2019-03-11 13:53:35 -03:00
leaveDrawingMode: function(save) {
if (this.stageKeyPressedHandler) {
global.stage.disconnect(this.stageKeyPressedHandler);
this.stageKeyPressedHandler = null;
}
if (this.stageKeyReleasedHandler) {
global.stage.disconnect(this.stageKeyReleasedHandler);
this.stageKeyReleasedHandler = null;
}
2019-03-05 08:36:59 -03:00
if (this.keyPressedHandler) {
this.disconnect(this.keyPressedHandler);
this.keyPressedHandler = null;
}
if (this.buttonPressedHandler) {
this.disconnect(this.buttonPressedHandler);
this.buttonPressedHandler = null;
}
if (this.keyboardPopupMenuHandler) {
this.disconnect(this.keyboardPopupMenuHandler);
this.keyboardPopupMenuHandler = null;
}
2019-03-05 08:36:59 -03:00
if (this.motionHandler) {
this.disconnect(this.motionHandler);
this.motionHandler = null;
}
if (this.buttonReleasedHandler) {
this.disconnect(this.buttonReleasedHandler);
this.buttonReleasedHandler = null;
}
if (this.scrollHandler) {
this.disconnect(this.scrollHandler);
this.scrollHandler = null;
}
this.currentElement = null;
this._stopTextCursorTimeout();
2019-03-05 08:36:59 -03:00
this._redisplay();
this.closeMenu();
2019-03-05 08:36:59 -03:00
this.get_parent().set_background_color(null);
Files.Images.reset();
2019-03-11 13:53:35 -03:00
if (save)
this.savePersistent();
2019-03-05 08:36:59 -03:00
},
// Used by the menu.
getSvgContentsForJson(json) {
let elements = [];
let elementsContent = '';
elements.push(...JSON.parse(json.contents).map(object => {
if (object.color)
object.color = getClutterColorFromString(object.color, 'white');
if (object.font && typeof object.font == 'string')
object.font = Pango.FontDescription.from_string(object.font);
if (object.image)
object.image = new Files.Image(object.image);
return new Elements.DrawingElement(object);
}));
elements.forEach(element => elementsContent += element.buildSVG('transparent'));
let prefixes = 'xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"';
let getGiconSvgContent = () => {
let size = Math.min(this.monitor.width, this.monitor.height);
let [x, y] = [(this.monitor.width - size) / 2, (this.monitor.height - size) / 2];
return `<svg viewBox="${x} ${y} ${size} ${size}" ${prefixes}>${elementsContent}\n</svg>`;
};
let getImageSvgContent = () => {
return `<svg viewBox="0 0 ${this.width} ${this.height}" ${prefixes}>${elementsContent}\n</svg>`;
};
return [getGiconSvgContent, getImageSvgContent];
},
2019-03-11 13:53:35 -03:00
saveAsSvg: function() {
2019-03-05 08:36:59 -03:00
// stop drawing or writing
if (this.currentElement && this.currentElement.shape == Shapes.TEXT && this.isWriting) {
2019-03-05 08:36:59 -03:00
this._stopWriting();
2019-03-27 22:00:57 -03:00
} else if (this.currentElement && this.currentElement.shape != Shapes.TEXT) {
2019-03-05 08:36:59 -03:00
this._stopDrawing();
}
let prefixes = 'xmlns="http://www.w3.org/2000/svg"';
if (this.elements.some(element => element.shape == Shapes.IMAGE))
prefixes += ' xmlns:xlink="http://www.w3.org/1999/xlink"';
let content = `<svg viewBox="0 0 ${this.width} ${this.height}" ${prefixes}>`;
2020-06-17 10:43:23 -03:00
if (SVG_DEBUG_EXTENDS)
content = `<svg viewBox="${-this.width} ${-this.height} ${2 * this.width} ${2 * this.height}" xmlns="http://www.w3.org/2000/svg">`;
let backgroundColorString = this.hasBackground ? String(this.areaBackgroundColor) : 'transparent';
2019-03-05 08:36:59 -03:00
if (backgroundColorString != 'transparent') {
content += `\n <rect id="background" width="100%" height="100%" fill="${backgroundColorString}"/>`;
}
2020-06-17 10:43:23 -03:00
if (SVG_DEBUG_EXTENDS) {
content += `\n <line stroke="black" x1="0" y1="${-this.height}" x2="0" y2="${this.height}"/>`;
content += `\n <line stroke="black" x1="${-this.width}" y1="0" x2="${this.width}" y2="0"/>`;
}
this.elements.forEach(element => content += element.buildSVG(backgroundColorString));
2019-03-05 08:36:59 -03:00
content += "\n</svg>";
if (Files.saveSvg(content)) {
2019-03-05 08:36:59 -03:00
// pass the parent (bgContainer) to Flashspot because coords of this are relative
let flashspot = new Screenshot.Flashspot(this.get_parent());
flashspot.fire();
if (global.play_theme_sound) {
global.play_theme_sound(0, 'screen-capture', "Save as SVG", null);
} else if (global.display && global.display.get_sound_player) {
let player = global.display.get_sound_player();
player.play_from_theme('screen-capture', "Save as SVG", null);
}
2019-03-05 08:36:59 -03:00
}
},
_saveAsJson: function(json, notify, callback) {
// stop drawing or writing
if (this.currentElement && this.currentElement.shape == Shapes.TEXT && this.isWriting) {
this._stopWriting();
} else if (this.currentElement && this.currentElement.shape != Shapes.TEXT) {
this._stopDrawing();
}
2019-03-11 13:53:35 -03:00
// do not use "content = JSON.stringify(this.elements, null, 2);", neither "content = JSON.stringify(this.elements);"
// do compromise between disk usage and human readability
let contents = this.elements.length ? `[\n ` + new Array(...this.elements.map(element => JSON.stringify(element))).join(`,\n\n `) + `\n]` : '[]';
2020-06-22 07:16:17 -03:00
GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
json.contents = contents;
2020-06-22 07:16:17 -03:00
if (notify)
this.emit('show-osd', Files.Icons.SAVE, json.name, "", -1, false);
if (!json.isPersistent)
this.currentJson = json;
if (callback)
callback();
2020-06-22 07:16:17 -03:00
});
},
saveAsJsonWithName: function(name, callback) {
this._saveAsJson(Files.Jsons.getNamed(name), false, callback);
},
saveAsJson: function() {
this._saveAsJson(Files.Jsons.getDated(), true);
},
savePersistent: function() {
this._saveAsJson(Files.Jsons.getPersistent());
2019-03-11 13:53:35 -03:00
},
syncPersistent: function() {
// do not override peristent.json with an empty drawing when changing persistency setting
if (!this.elements.length)
this._loadPersistent();
else
this.savePersistent();
},
_loadJson: function(json, notify) {
// stop drawing or writing
if (this.currentElement && this.currentElement.shape == Shapes.TEXT && this.isWriting) {
this._stopWriting();
} else if (this.currentElement && this.currentElement.shape != Shapes.TEXT) {
this._stopDrawing();
}
this.elements = [];
this.currentElement = null;
if (!json.contents)
2019-03-11 13:53:35 -03:00
return;
this.elements.push(...JSON.parse(json.contents).map(object => {
if (object.color)
object.color = getClutterColorFromString(object.color, 'white');
if (object.font && typeof object.font == 'string')
object.font = Pango.FontDescription.from_string(object.font);
if (object.image)
object.image = new Files.Image(object.image);
return new Elements.DrawingElement(object);
}));
if (notify)
this.emit('show-osd', Files.Icons.OPEN, json.name, "", -1, false);
if (!json.isPersistent)
this.currentJson = json;
},
_loadPersistent: function() {
this._loadJson(Files.Jsons.getPersistent());
},
loadJson: function(json, notify) {
this._loadJson(json, notify);
this._redisplay();
},
2020-09-10 10:19:17 -03:00
loadPreviousJson: function() {
let json = Files.Jsons.getPrevious(this.currentJson || null);
if (json)
this.loadJson(json, true);
},
2020-09-10 10:19:17 -03:00
loadNextJson: function() {
let json = Files.Jsons.getNext(this.currentJson || null);
if (json)
this.loadJson(json, true);
2019-03-11 13:53:35 -03:00
},
get drawingContentsHasChanged() {
let contents = `[\n ` + new Array(...this.elements.map(element => JSON.stringify(element))).join(`,\n\n `) + `\n]`;
return contents != (this.currentJson && this.currentJson.contents);
2019-03-05 08:36:59 -03:00
}
});