How to Print Text to DrawingArea in Gnome-Shell-Extension - gnome-shell-extensions

I'm doing my first gnome-shell extension (gnome shell 41.3) and I seem to encounter the most common problems, finding the right manual for that...
What I try to achive is...
A Widget shown (above everything) on the desktop...
Draw something into the widget...
Write some Text to the widget...
What I already acomplished is...
Using a DrawingArea and Cairo (I assume) I can use .moveTo (), .lineTo (), etc..., .stroke() to draw something into my widget...
Whe widget is displayed above everything else and stuff...
My extension has a settings widget to configure...
What I am missing is...
Any clue on how to put text in addition to the drawing stuff onto the Drawing area...
I did 1.5 days of duckduckgoing into it but, again, I'm running in circles with not a single Idea on how to proceed...
Could anyone point me into the correct direction, plz...???
Pseudo Code goes something like this
const {St, GLib} = imports.gi;
var area = new St.DrawingArea({
style_class : 'bg-color',
reactive : true,
can_focus : true,
track_hover : true,
width: myWidth,
height: myHeight
});
area.connect('repaint', (area) => drawMyStuff(area));
Main.layoutManager.addChrome(area, {
affectsInputRegion : false,
affectsStruts : false,
trackFullscreen : false,
});
timeout = GLib.timeout_add(0, 500, () => {
this.area.queue_repaint();
return true;
});
function drawMyStuff(area) {
let cr = area.get_context();
cr.translate(area.width / 2, area.height / 2);
cr.scale(area.width / 2, area.height / 2);
cr.setSourceRGBA (1, 1, 1, 1);
cr.arc(0.0, 0.0, 1.0 - 0.05, 0, 2 * Math.PI);
cr.fill();
/*
* Would like to print some text here but obviously I am to stupid to do so...
* Help me StackExchangeCommunity, you're my only hope...
*
* Obviously it is not that easy:
* cr.setSourceRGBA (1, 0, 0, 1);
* cr.write(0.0, 0.0, "Not a moon")
* cr.fill();
*
*/
cr.$dispose();
return true;
}

It's kinda hard to find out and I had no luck finding any documentation on that but after digging into the GJS Code here (https://gitlab.gnome.org/GNOME/gjs/-/blob/HEAD/modules/cairo-context.cpp) I was able to understand a lot more on how to do cairo stuff like this (https://www.cairographics.org/manual/) from GJS...
The solution for my question stated above goes like this:
function drawMyStuff(area) {
let cr = area.get_context();
cr.translate(area.width / 2, area.height / 2);
cr.scale(area.width / 2, area.height / 2);
cr.setSourceRGBA (1, 1, 1, 1);
cr.arc(0.0, 0.0, 1.0 - 0.05, 0, 2 * Math.PI);
cr.fill();
/*
* Thank me, I'm my only hope...
*
* Obviously it is that easy:
*
*/
cr.moveTo(-0.5,-0.5);
cr.setSourceRGBA (1, 0, 0, 1);
cr.setFontSize(0.125);
cr.showText('No Moon');
cr.$dispose();
return true;
}

Related

How to select a single Curve in a Path in Paper.js?

I need to distinctly select a single Curve of a clicked Path, how can I do that?
For example, in this sketch we can select a whole path when clicked on it:
Currently I can detect the curve (not sure if it is the appropriate approach, anyway):
..onMouseDown = (event) ~>
hit = scope.project.hitTest event.point
if hit?item
# select only that specific segment
curves = hit.item.getCurves!
nearest = null
dist = null
for i, curve of curves
_dist = curve.getNearestPoint(event.point).getDistance(event.point)
if _dist < dist or not nearest?
nearest = i
dist = _dist
selected-curve = curves[nearest]
..selected = yes
But whole path is selected anyway:
What I want to achieve is something like this:
There is an easier way to achieve what you want.
You can know if hit was on a curve by checking its location property.
If it is set, you can easily get the curve points and manually draw your selection.
Here is a sketch demonstrating it.
var myline = new Path(new Point(100, 100));
myline.strokeColor = 'red';
myline.strokeWidth = 6;
myline.add(new Point(200, 100));
myline.add(new Point(260, 170));
myline.add(new Point(360, 170));
myline.add(new Point(420, 250));
function onMouseDown(event) {
hit = paper.project.hitTest(event.point);
// check if hit is on curve
if (hit && hit.location) {
// get curve
var curve = hit.location.curve;
// draw selection
var selection = new Group(
new Path.Line({
from: curve.point1,
to: curve.point2,
strokeColor: 'blue',
strokeWidth: 3
}),
new Path.Rectangle({
from: curve.point1 - 5,
to: curve.point1 + 5,
fillColor: 'blue'
}),
new Path.Rectangle({
from: curve.point2 - 5,
to: curve.point2 + 5,
fillColor: 'blue'
})
);
// make it automatically be removed on next down event
selection.removeOnDown();
}
}
Update
As an alternative, to avoid messing up with the exported drawing, you can simply select the line instead of applying it a stroke style.
See this sketch.
var selection = new Path.Line({
from: curve.point1,
to: curve.point2,
selected: true
});
There is no built-in way to do what you'd like AFAIK.
You basically need to walk through the segments, construct a line, and see if the hit is on that particular line. The line cannot be transparent or it's not considered a hit which is why I give it color and width to match the visible line; it's also why it's deleted after the test.
Here's the sketch solution that implements a bit more around this:
function onMouseDown(event){
if (!myline.hitTest(event.point)) {
return
}
c1.remove()
c2.remove()
// there's a hit so this should find it
let p = event.point
let segs = myline.segments
for (let i = 1; i < segs.length; i++) {
let line = new Path.Line(segs[i - 1].point, segs[i].point)
line.strokeWidth = 6
line.strokeColor = 'black'
if (line.hitTest(p)) {
c1 = new Path.Circle(segs[i-1].point, 6)
c2 = new Path.Circle(segs[i].point, 6)
c1.fillColor = 'black'
c2.fillColor = 'black'
line.remove()
return
}
line.remove()
}
throw new Error("could not find hit")
}
Here's what I draw:

recursion in typescript gets undefined

I'm using a canvas object inside my component to generate a chart. In order for it animate i'm calling the method recursively. I keep getting an error saying that the method is not defined. Not sure how I need to structure it.
any assistance appreciated.
// Animate function
protected animate(draw_to) {
// Clear off the canvas
this.ctx.clearRect(0, 0, this.width, this.height);
// Start over
this.ctx.beginPath();
// arc(x, y, radius, startAngle, endAngle, anticlockwise)
// Re-draw from the very beginning each time so there isn't tiny line spaces between each section (the browser paint rendering will probably be smoother too)
this.ctx.arc(this.x, this.y, this.radius, this.start, draw_to, false);
// Draw
this.ctx.stroke();
// Increment percent
this.curr++;
// Animate until end
if (this.curr < this.finish + 1) {
// Recursive repeat this function until the end is reached
requestAnimationFrame(function () {
error happens here >>> this.animate(this.circum * this.curr / 100 + this.start);
});
}
}
You need to use an arrow function to keep the same context in the function you give to requestAnimationFrame.
requestAnimationFrame(() => {
error happens here >>> this.animate(this.circum * this.curr / 100 + this.start);
});
Another option is:
requestAnimationFrame(this.animate.bind(this, this.circum * this.curr / 100 + this.start));
You are passing a reference to this.animate which is already bound to the correct this along with the parameters.

Matter.js Gravity Point

Is it possible to create a single gravity / force point in matter.js that is at the center of x/y coordinates?
I have managed to do it with d3.js but wanted to enquire about matter.js as it has the ability to use multiple polyshapes.
http://bl.ocks.org/mbostock/1021841
The illustrious answer has arisen:
not sure if there is any interest in this. I'm a fan of what you have created. In my latest project, I used matter-js but I needed elements to gravitate to a specific point, rather than into a general direction. That was very easily accomplished. I was wondering if you are interested in that feature as well, it would not break anything.
All one has to do is setting engine.world.gravity.isPoint = true and then the gravity vector is used as point, rather than a direction. One might set:
engine.world.gravity.x = 355;
engine.world.gravity.y = 125;
engine.world.gravity.isPoint = true;
and all objects will gravitate to that point.
If this is not within the scope of this engine, I understand. Either way, thanks for the great work.
You can do this with the matter-attractors plugin. Here's their basic example:
Matter.use(
'matter-attractors' // PLUGIN_NAME
);
var Engine = Matter.Engine,
Events = Matter.Events,
Runner = Matter.Runner,
Render = Matter.Render,
World = Matter.World,
Body = Matter.Body,
Mouse = Matter.Mouse,
Common = Matter.Common,
Bodies = Matter.Bodies;
// create engine
var engine = Engine.create();
// create renderer
var render = Render.create({
element: document.body,
engine: engine,
options: {
width: Math.min(document.documentElement.clientWidth, 1024),
height: Math.min(document.documentElement.clientHeight, 1024),
wireframes: false
}
});
// create runner
var runner = Runner.create();
Runner.run(runner, engine);
Render.run(render);
// create demo scene
var world = engine.world;
world.gravity.scale = 0;
// create a body with an attractor
var attractiveBody = Bodies.circle(
render.options.width / 2,
render.options.height / 2,
50,
{
isStatic: true,
// example of an attractor function that
// returns a force vector that applies to bodyB
plugin: {
attractors: [
function(bodyA, bodyB) {
return {
x: (bodyA.position.x - bodyB.position.x) * 1e-6,
y: (bodyA.position.y - bodyB.position.y) * 1e-6,
};
}
]
}
});
World.add(world, attractiveBody);
// add some bodies that to be attracted
for (var i = 0; i < 150; i += 1) {
var body = Bodies.polygon(
Common.random(0, render.options.width),
Common.random(0, render.options.height),
Common.random(1, 5),
Common.random() > 0.9 ? Common.random(15, 25) : Common.random(5, 10)
);
World.add(world, body);
}
// add mouse control
var mouse = Mouse.create(render.canvas);
Events.on(engine, 'afterUpdate', function() {
if (!mouse.position.x) {
return;
}
// smoothly move the attractor body towards the mouse
Body.translate(attractiveBody, {
x: (mouse.position.x - attractiveBody.position.x) * 0.25,
y: (mouse.position.y - attractiveBody.position.y) * 0.25
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.12.0/matter.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/matter-attractors#0.1.6/build/matter-attractors.min.js"></script>
Historical note: the "gravity point" functionality was proposed as a feature in MJS as PR #132 but it was closed, with the author of MJS (liabru) offering the matter-attractors plugin as an alternate. At the time of writing, this answer misleadingly seems to indicate that functionality from the PR was in fact merged.
Unfortunately, the attractors library is 6 years outdated at the time of writing and raises a warning when using a newer version of MJS than 0.12.0. From discussion in issue #11, it sounds like it's OK to ignore the warning and use this plugin with, for example, 0.18.0. Here's the warning:
matter-js: Plugin.use: matter-attractors#0.1.4 is for matter-js#^0.12.0 but installed on matter-js#0.18.0.
Behavior seemed fine on cursory glance, but I'll keep 0.12.0 in the above example to silence it anyway. If you do update to a recent version, note that Matter.World is deprecated and should be replaced with Matter.Composite and engine.gravity.

Less mixin scope problems

I built a parametric mixin that finds the children of an element based on a "node-value" system that I created. What happens is the children are found by a loop function ".extractArrays" with ".deliverChild" inside it. Then the children (up to 4 of them) are put into ".calculateWidth", which returns the width of the child in a variable (ex. "calculatedWidth1").
The problem is: when there are no third and fourth children, #child3 and #child4 are unset, which creates an error. I set #child3 and #child4 to zero before the mixins, hoping that this would give them default values of 0 before the mixins are called. For some reason, however, when there is a third child, the mixin's returned value of #child3 won't override the #child3 that is set to 0. I am unsure why this is happening, but I feel like there are a couple things that throw me off about Less when it comes to mixins and scope.
#child3: none, 0 0, 0, 0;
#child4: none, 0 0, 0, 0;
.extractArrays(#index, #node, #node-value, #elements-array) when (#index <= #length-elements-array) {
#element-array: extract(#elements-array, #index);
#found-node: extract(#element-array, 2);
.deliverChild(#element-array, #found-node) when (#found-node = #child-node-value1) {
#child1: extract(#element-array, 1);
}
.deliverChild(#element-array, #found-node) when (#found-node = #child-node-value2) {
#child2: extract(#element-array, 1);
}
.deliverChild(#element-array, #found-node) when (#found-node = #child-node-value3) {
#child3: extract(#element-array, 1);
}
.deliverChild(#element-array, #found-node) when (#found-node = #child-node-value4) {
#child4: extract(#element-array, 1);
}
.deliverChild(#element-array, #found-node);
.extractArrays(#index + 1, #node, #node-value, #elements-array);
}
.extractArrays(1, #node, #node-value, #elements-array);
.calculateWidth(#child1, 1);
.calculateWidth(#child2, 2);
.calculateWidth(#child3, 3);
width: #calculatedWidth1 + #calculatedWidth2 + #calculatedWidth3 + #calculatedWidth4;
(Not an exact answer to the "scope" question above but an algorithm to use as a starting point in an alternative approach suggested in comments above):
A generic array filtering mixin would look like this (Less 1.7.5 or higher):
#array: // key value
a 1,
b 2,
c 3,
a 4,
d 5,
a 6,
c 7;
// usage:
usage {
.filter-array(#array, a);
result: #filter-array;
}
// impl.:
.filter-array(#array, #key, #key-index: 1) {
.-(length(#array));
.-(#i, #r...) when (#i > 0)
and not(#key = extract(extract(#array, #i), #key-index)) {
// skip item since key does not match
.-((#i - 1), #r);
}
.-(#i, #r...) when (length(#r) > 0)
and (#key = extract(extract(#array, #i), #key-index)) {
// key matches and #r is not empty so concat current item to #r
.-((#i - 1); extract(#array, #i), #r);
}
.-(#i, #r...) when (length(#r) = 0)
and (#key = extract(extract(#array, #i), #key-index)) {
// key matches and #r is empty so this is our first item
.-((#i - 1), extract(#array, #i));
}
.-(#i, #r...) when (#i = 0) {
// define "return" variable:
#filter-array: #r;
}
}
With resulting array being equal to:
#filter-array:
a 1,
a 4,
a 6;
This looks quite scary and verbose but still more clean and more controllable than the original approach.
Additionally it would make sense to provide a dedicated mixin to return a sum (or any other "transformation" with result in a single value) of certain values of the array items (that way the implementation can be simplified to a certain point since you won't need to concatenate anything and some of above conditions and/or mixin specializations become unnecessary).

How do I get the visual width and height of a rotated component?

I'm playing around with code like this:
<s:Button id="test" label="test" transformX="{Math.floor(test.width/2)}" rotationY="20" x="20" y="20" />
The button is rotated on the Y axis and the rotate pivot is in the middle of the button.
This will create a button that looks something like this:
(source: jeffryhouser.com)
The rotated button is, visually, filling a different space than the x, y, height, and width values would you have believe.
The "A" value in my image is the height of the button. But, what I want to use for calculation and placement purposes is the B value.
Additionally, I'd like to perform similar calculations with the width; getting the width from the top right corner to the bottom left corner.
How do I do this?
I put together a sample to show off the various approaches for calculating this that people are suggesting. The source code is also available. Nothing is quite working like I'd expect. For example, turn the rotationSlider to 85. The button is effectively invisible, yet all approaches are still giving it height and width.
My math may be a bit rusty, but this is how I would find the answer :
You would extend a right-triangle from the right edge of the button to the bottom-most point of the diagram you have (A-B). You can then use the Law of Sines to get three angles : 90', 20' and 70' (90 will always be there, and then your variable - 180 for the third angle).
You can then use the following formula to find your answer :
B = ((button.width * sin(button.rotationY)) / (sin(90 -button.rotationY)) + (button.height)
getBounds(..) and getRect(..) are supposed to be the methods for getting the width and height of transformed objects.
Not tried them in Flex 4 yet, but they always worked for me in Flex 3.
The answer was in one of the comments from James Ward on this question and is located at this blog post.
The one thing the blog post doesn't say is that in many cases, the perspectiveProjection property of the transform property on the class in question will be null. The linked to example took care of this by setting the maintainProjectionCenter property to true. But, you could also create a new perspectiveProjection object like this:
object.transform.perspectiveProjection = new PerspectiveProjection();
I wrapped up the function from evtimmy into a class:
/**
* DotComIt/Flextras
* Utils3D.as
* Utils3D
* jhouser
* Aug 5, 2010
*/
package com.flextras.coverflow
{
import flash.geom.Matrix3D;
import flash.geom.PerspectiveProjection;
import flash.geom.Rectangle;
import flash.geom.Utils3D;
import flash.geom.Vector3D;
public class TransformUtilities
{
public function TransformUtilities()
{
}
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
//----------------------------------
// projectBounds
//----------------------------------
// info from
// http://evtimmy.com/2009/12/calculating-the-projected-bounds-using-utils3dprojectvector/
/**
* Method retrieved from
* http://evtimmy.com/2009/12/calculating-the-projected-bounds-using-utils3dprojectvector/
*
* #param bounds: The rectangle that makes up the object
* #param matrix The 3D Matrix of the item
* #param the projection of the item's parent.
*/
public static function projectBounds(bounds:Rectangle,
matrix:Matrix3D,
projection:PerspectiveProjection):Rectangle
{
// Setup the matrix
var centerX:Number = projection.projectionCenter.x;
var centerY:Number = projection.projectionCenter.y;
matrix.appendTranslation(-centerX, -centerY, projection.focalLength);
matrix.append(projection.toMatrix3D());
// Project the corner points
var pt1:Vector3D = new Vector3D(bounds.left, bounds.top, 0);
var pt2:Vector3D = new Vector3D(bounds.right, bounds.top, 0)
var pt3:Vector3D = new Vector3D(bounds.left, bounds.bottom, 0);
var pt4:Vector3D = new Vector3D(bounds.right, bounds.bottom, 0);
pt1 = Utils3D.projectVector(matrix, pt1);
pt2 = Utils3D.projectVector(matrix, pt2);
pt3 = Utils3D.projectVector(matrix, pt3);
pt4 = Utils3D.projectVector(matrix, pt4);
// Find the bounding box in 2D
var maxX:Number = Math.max(Math.max(pt1.x, pt2.x), Math.max(pt3.x, pt4.x));
var minX:Number = Math.min(Math.min(pt1.x, pt2.x), Math.min(pt3.x, pt4.x));
var maxY:Number = Math.max(Math.max(pt1.y, pt2.y), Math.max(pt3.y, pt4.y));
var minY:Number = Math.min(Math.min(pt1.y, pt2.y), Math.min(pt3.y, pt4.y));
// Add back the projection center
bounds.x = minX + centerX;
bounds.y = minY + centerY;
bounds.width = maxX - minX;
bounds.height = maxY - minY;
return bounds;
}
}
}
Although that is the answer to my question, I'm not sure if it was the solution to my problem. Thanks everyone!

Resources