XY positions of hyperlinks in Firefox plugin - dom

I want to build a FireFox addon that can capture a webpage as an image (which seems simple using a canvas object) and also preserve the XY postions of the hyperlinks present in the webpage.
I wanted to know if there are any DOM methods that can help me extract the geometry info (XY positions and the height and width) of all the hyperlinks in a webpage?
I am pretty much stuck here, hence any help or leads will be highly appreciated!
Thanks,
Kapil

It seems that you can "walk" through the offsetParent objects and add all the offsetLeft attributes alltogether and then get a absolute value.
Eg. for the dom tag link on this page :
A -> offsetLeft = 110
A -> offsetParent(HTMLTableCellElement) -> offsetLeft = 60
A -> offsetParent -> offsetParent(HTMLTableElement) -> offsetLeft = 195
A -> offsetParent -> offsetParent -> offsetParent(HTMLBodyElement) -> offsetLeft = 0
110 + 60 + 195 + 0 = 365px.
Since the page is centered the 2nd last attribute will change depending on your browser size.
Oh, and ofcourse the other value would be offsetTop.

Related

Circular layout with edge bundling and labels in graph-tool

I am very new to graph visualizations and software like graph-tool (gt). My main field is mathematics, but I am somewhat familiar with Python and programming in general. However, I'm not a programmer, so my code may be less than elegant; any suggestions of improvement will be gratefully appreciated.
Description:
I am very fond of the circular layout with edge bundling used to visualize very large graphs. As an example, I am trying to plot the C.Elegans connectome using the wonderful Python module graph-tool by Tiago Peixoto. For this I use the following:
import graph_tool.all as gt
g_celegans = gt.load_graph("c.elegans_neural.male_1.graphml")
v_prop = g_celegans.vertex_properties
celegans_state = gt.minimize_nested_blockmodel_dl(g_celegans)
celegans_state.draw(vertex_text = v_prop['name'], bg_color = 'w')
which produces:
Questions:
How could I (in gt) place the vertex labels on a line drawn from the center? Like this
Can I plot a similar layout, i.e. circular and edge bundling, but using a clustering (partition of the vertices) of my own, instead of the stochastic block model? In a sense, I guess I would just like to be able to use the circular + edge bundling feature on its own. Or am I missing the whole point somewhat?
(Would anyone recommend a good introductory treatment on graph visualizations including this type (connectogram)?)
Attempt at Question 1:
So, I managed to at least get somewhere with this:
def getAngle(vec):
norm_vec = vec / np.linalg.norm(vec)
one_vec = np.array([1,0])
dot_product = np.dot(norm_vec, one_vec)
return np.arccos(dot_product)
text_rot = [0]*len(list(text_pos))
for i, p in enumerate(text_pos):
if p[0]>=0 and p[1]>=0:
text_rot[i] = getAngle(p)
elif p[0]>=0 and p[1]<0:
text_rot[i] = -getAngle(p)
elif p[0]<0 and p[1]>=0:
text_rot[i] = getAngle(p)-np.pi
elif p[0]<0 and p[1]<0:
text_rot[i] = -getAngle(p)+np.pi
text_rot = np.asarray(text_rot)
t_rot = g_celegans.new_property('v','float', vals = text_rot)
options = {'pos': pos,
'vertex_text': v_prop['name'],
'vertex_text_rotation':t_rot,
'bg_color': 'w',
'vertex_shape': 'none',
'vertex_font_size': 5,
'edge_end_marker': 'none'
}
celegans_state.draw(**options)
which produces:
So, the rotation is fine, but I would like to offset the labels a bit further out. Now they're in the center of an invisible vertex. There are two vertex properties called 'text_position' and 'text_offset', which you may read about here.
Now, any value for 'vertex_text_position', such as -1 or 'centered' or if I pass a VertexPropertyMap object like for 'vertex_text_rotation' above, generates an IndexError:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-197-d529fcf5647e> in <module>
9 }
10
---> 11 celegans_state.draw(**options)
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/inference/nested_blockmodel.py in draw(self, **kwargs)
986 draws the hierarchical state."""
987 import graph_tool.draw
--> 988 return graph_tool.draw.draw_hierarchy(self, **kwargs)
989
990
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/draw/cairo_draw.py in draw_hierarchy(state, pos, layout, beta, node_weight, vprops, eprops, hvprops, heprops, subsample_edges, rel_order, deg_size, vsize_scale, hsize_scale, hshortcuts, hide, bip_aspect, empty_branches, **kwargs)
2121 kwargs[k] = u.own_property(v.copy())
2122
-> 2123 pos = graph_draw(u, pos, vprops=t_vprops, eprops=t_eprops, vorder=tvorder,
2124 **kwargs)
2125
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/draw/cairo_draw.py in graph_draw(g, pos, vprops, eprops, vorder, eorder, nodesfirst, output_size, fit_view, fit_view_ink, adjust_aspect, ink_scale, inline, inline_scale, mplfig, output, fmt, bg_color, **kwargs)
1074 vprops.get("fill_color", _vdefaults["fill_color"]),
1075 vcmap)
-> 1076 vprops["text_color"] = auto_colors(g, bg,
1077 vprops.get("text_position",
1078 _vdefaults["text_position"]),
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/draw/cairo_draw.py in auto_colors(g, bg, pos, back)
724 return color_contrast(back)
725 c = g.new_vertex_property("vector<double>")
--> 726 map_property_values(bgc_pos, c, conv)
727 return c
728
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/__init__.py in map_property_values(src_prop, tgt_prop, map_func)
1189 u = GraphView(g, directed=True, reversed=g.is_reversed(),
1190 skip_properties=True)
-> 1191 libcore.property_map_values(u._Graph__graph,
1192 _prop(k, g, src_prop),
1193 _prop(k, g, tgt_prop),
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/draw/cairo_draw.py in conv(x)
722 return color_contrast(bgc)
723 else:
--> 724 return color_contrast(back)
725 c = g.new_vertex_property("vector<double>")
726 map_property_values(bgc_pos, c, conv)
~/anaconda3/envs/gt/lib/python3.9/site-packages/graph_tool/draw/cairo_draw.py in color_contrast(color)
694 def color_contrast(color):
695 c = np.asarray(color)
--> 696 y = c[0] * .299 + c[1] * .587 + c[2] * .114
697 if y < .5:
698 c[:3] = 1
IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed
If I do 'vertex_text_offset = pos', this would mean that I offset each vertex by its own coordinates, and I could then just scale by say 0.1 to get them appropriately far out, which actually DID work great without rotation. Then I rotated the text, which yielded this (without scaling):
The problem seems to be that the center for rotation is the center of the vertex, which is not ideal if the text is moved out from the vertex. So, even if 'vertex_text_position' above would have worked, I'm guessing the rotation would have messed that up as well.
Weirdly enough, If I rotate the vertices using 'vertex_rotation' instead, the labels are rotated along with them (great!), but when I offset the text with vertex position (which should "push" outwards), I get the same faulty plot as above.
Next I tried 'vertex_shape = circle', and filling the vertices with white using 'vertex_fill_color = 'w''. Thus I would push the text out a bit from the edge by increasing the size of the vertex. For some reason this made all the edges of the graph white as well; so no colors at all in the plot. I guess the edges are thus colored based on the vertex colors.
What I ended up doing is to use the vertex properties 'text_out_color' and 'text_out_width', with a width of 0.003. This gives a nice bold style to the text, which makes it more readable against the colored background.
But, now I'm pretty much out of ideas.
Do anyone know a solution to my problem? i.e. placing the labels like I have them, but moving them further out (in the direction outwards from the center) or framing them in white so that they're more readable, but so that the plot still looks nice; as well as to question 2 above.
This is a couple months late so hopefully you figured it out but I'll leave this here for future reference:
To get those labels to look the way you want them to in this case is when you call the draw function you'll want to specify the position of the vertex text like so:
celegans_state.draw(vertex_text = v_prop['name'], bg_color = 'w', vertex_text_position='centered')
(as can be seen in the list of properties in the documentation 'centered' gives this exact effect: https://graph-tool.skewed.de/static/doc/draw.html#graph_tool.draw.graph_draw)
To get a circular graph I figure you want to use the radial tree layout (https://graph-tool.skewed.de/static/doc/draw.html?highlight=radial_tree_layout#graph_tool.draw.radial_tree_layout)
Hopefully this helps!

2D Unity: expand UI element based on text to the bottom

I've got a game object (InfoBox) with a..
Vertical Layout Group (Padding 20 on all sides, Control Child Size Height active)
an image
a Content Size Fitter (Vertical Fit set to Preferred Size, Horizontal Unconstrained)
Inside this InfoBox is a Text-Element and every time I update the text, I want the InfoBox to expand or collapse, but to the bottom only. Right now my InfoBox always expands or collapses to both top and bottom, but I don't want that to happen. How can I achieve that? I added some screenshots to better visualise this.
These are my settings for the InfoBox:
And these are my settings for the text:
And this is what happens when I use for example less text, the box collapses from bottom and top, but I want it to stay fixed at the top (on the same line as the green box next to it) and only collapse on the bottom:
Any help is really appreciate!
You main issues looks like you are using a ContentSizeFitter also on the parent object. So it depends how this parent object is aligned with its according parent.
This sentence sounds strange I know but what you did is basically shifting up the alignment responsibility to the parent.
=> Make your UI element aligned to the top and grow downwards.
All you need to do for this is either set
Anchors Min y -> 1
Anchors Max y -> 1
Pivot y -> 1
or simply go to the RectTransform Inspector, open the alignment tool and hold Shift + Alt and click on the top alignment:
For the second instead of using the ContentSizeFitter I prefer to have my own script that only does what it should and nothing more.
You can get the preferredHeight which is exactly the value you are looking for.
The following script simply always applies the preferred height to the text rect. Using [ExecuteAlways] this also works in edit mode. Simply attach it on the same GameObject as the UI.Text component
[ExecuteAlways]
[RequireComponent(typeof(Text))]
[RequireComponent(typeof(RectTransform))]
public class TextHeightFitter : MonoBehaviour
{
[SerializeField] private RectTransform _rectTransform;
[SerializeField] private Text _text;
private void Update()
{
if (!_text) _text = GetComponent<Text>();
if (!_rectTransform) _rectTransform = GetComponent<RectTransform>();
var desiredHeight = _text.preferredHeight;
var size = _rectTransform.sizeDelta;
size.y = desiredHeight;
_rectTransform.sizeDelta = size;
}
}

How to set a maxWidth for magnificpopup in typo3

I try to use magnificpopup (via jquery not as an extension) in typo3 (8.7.16)(textmediaelement) - no Problem, but :)
If the original image is smaller than the normal popup, the size of the image increases...
I tried this in constant.ts
styles.content.textmedia.linkWrap.width = 1110m
styles.content.textmedia.linkWrap.height = 800m
and also
styles.content.textmedia.linkWrap.maxWidth = 1110
styles.content.textmedia.linkWrap.maxHeight = 800
with m behind or not.
Does anyone has an idea for this problem - how I can change this behavior?
Thanks
Volker
Try without linkWrap and set this in TypoScript SETUP:
styles.content.imgtext.maxW = 1140
styles.content.imgtext.maxWInText = 1140
the problem is not magnificPopUp, but fluidStyledContent.
in file
fluid_styled_content/Resources/Private/Partials/Media/Type/Image.html the ce:link.clickEnlarge hasn't got a parameter maxWidth. So I changed this link (in an own copy) to
<a href="{f:uri.image(src: 'fileadmin/{file.originalFile.identifier}', maxHeight: '{settings.media.popup.height}', maxWidth: '{settings.media.popup.width}')}"
rel="{settings.detail.media.image.lightbox.rel}" class="fluidbox">...</a>
For this solution is fully ok - Large images are becoming smaller and other are still as they are...
cu
Volker

gwt firefox getAbsoluteLeft()

I'm seeing a truly weird behavior while trying to set a popup relative to another element in GWT. It seems like setting the popup position (an independent, floating element) changes the answer I get from calls like getAbsoluteRight() or getAbsoluteLeft() for a completely different element, which is static on the page and does not move visually.
I added some print statements to check what was going on, so here is the code:
System.out.println(item.td);
int position = item.td.getAbsoluteRight()-offsetWidth;
System.out.println("left/right:" + item.td.getAbsoluteLeft() + "/" + item.td.getAbsoluteRight() + ". sent:" + (item.td.getAbsoluteRight() - offsetWidth) + "=" + position);
popup.setPopupPosition(position, item.td.getAbsoluteBottom());
System.out.println("left/right:" + item.td.getAbsoluteLeft() + "/" + item.td.getAbsoluteRight() + ". sent:" + (item.td.getAbsoluteRight() - offsetWidth) + "=" + position);
popup.addStyleName("bigger");
System.out.println("left/right:" + item.td.getAbsoluteLeft() + "/" + item.td.getAbsoluteRight() + ". sent:" + (item.td.getAbsoluteRight() - offsetWidth) + "=" + position);
System.out.println(item.td);
Here is the result on Chrome
Menu displayed, widths: 81/340=340
<td class="hover">Daniel?</td>
left/right:1104/1185. sent:845=845
left/right:1121/1202. sent:862=845
left/right:1121/1202. sent:862=845
<td class="hover">Daniel?</td>
Here is the result on Firefox
Menu displayed, widths: 81/340=340
<td class="hover">Daniel?</td>
left/right:1254/1335. sent:995=995
left/right:1273/1354. sent:1014=995
left/right:1273/1354. sent:1014=995
<td class="hover">Daniel?</td>
so the left/right coordinates of the fixed element suddenly change (X coordinate goes from 1254 to 1273) after calling setPopupPosition(), while the relevant element actually stays in the same place (visually). I really have no idea how it happens as the popup doesn't even know of the existence of that element. Even more, while I can reproduce the error consistently, it does not happen if I switch the popup content...
... incidentally, I compared the coordinates given by firefox with a screenshot of the page, and the return values are not only wrong, but impossible given my screen size (1366x768) and no scrolling.
I could probably try setting the position twice, as the second value is actually the correct one, but I would really like to understand what is going on here...
Many thanks!
The differ is exactly 150 pixels. (May be total of 75 pix in left side)
Have you checked page against: http://validator.w3.org/
There's often differences within the margin/padding (also borders in IE).
As i get out of your getAbsoluteRight()-offsetWidth code, you using the td to get absolute right. But setting the position on the popup. This should mean that you have some borders/margins/padding between the popup and the td content.
The getAbsoluteLeft() and getAbsoluteRight() (as well as Top and Bottom) are all calculated based on their parental element's scroll and offset positions.
Also an empty object can often end up in a default width. But as soon as you enter a content, the size adapts to its content.

Itextsharp V 5.x:image cell height in pdfptable

I am creating table and adding cells to table with text or image content.
var pdfTable = new PdfPTable(2);
nCell = new PdfPCell(new Phrase("A")) {HorizontalAlignment = 1};
pdfTable.AddCell(nCell);
pdfTable.AddCell("B");
pdfTable.AddCell(qrImg);
pdfTable.AddCell(image39);
pdfTable.AddCell("C");
pdfTable.AddCell("D");
pdfTable.SpacingBefore = 20f;
pdfTable.SpacingAfter = 30f;
document.Add(pdfTable);
renders 3 rows and displays image in row2
if I add cells by creating pdfpcell object first:
var cell = new PdfPCell(qrImg};
pdfTable.AddCell(nCell);
only rows 1 and 3 are visible.
If I add height property to cell then the image gets diaplayed.
my questions ( 3 but related);
is it required for us to specify height when adding cell with image ( cells added with text content - phrase resenders correctly) ?
Is there something I am missing when creating a new cell, which prevents images to be rendered?
should I always be using Addcell(image) when adding image content?
Thank you all,
Mar
Its easier to understand what's going on if you browse the source. A table within iText keeps a property around called DefaultCell that gets reused over and over. This is done so that the basic cell properties are kept from cell to cell. When you call AddCell(Image) the DefaultCell's image is set to the image, then added to the table, and finally the image get's null'd out.
543 defaultCell.Image = image;
544 AddCell(defaultCell);
545 defaultCell.Image = null;
The PdfCell(Image) constructor actually internally calls an overload PdfPCell(Image, bool) and passes false as the second parameter, fit. Here's the constructor's conditional on fit:
152 if (fit) {
153 this.image = image;
154 Padding = borderWidth / 2;
155 }
156 else {
157 column.AddText(this.phrase = new Phrase(new Chunk(image, 0, 0, true)));
158 Padding = 0;
159 }
If you pass false to fit, which is the default, you'll see that the image is added in a much more complicated way.
So basically you can add an image in three main ways (okay, lots more actually if you use nested tables or chunks or phrases), the first below picks up the defaults and is probably what you want. The second is more raw but gets you closer to what you probably want. The third is the most raw and assumes that you know what you're doing.
var qrImg = iTextSharp.text.Image.GetInstance(sampleImage1);
//Use the DefaultCell, including any existing borders and padding
pdfTable.AddCell(qrImg);
//Brand new cell, includes some padding to get the image to fit
pdfTable.AddCell(new PdfPCell(qrImg, true));
//Brand new cell, image added as a Chunk within a Phrase
pdfTable.AddCell(new PdfPCell(qrImg));