xul/xpcom copy image from string to clipboard - javascript

I'm stuck with no clues how to copy image to clipboard.
My code looks like this:
var image = "data:image/png;base64,..."
var io = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var channel = io.newChannel(image, null, null);
var input = channel.open();
var trans = Components.classes["#mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
trans.addDataFlavor("image/png");
trans.setTransferData("image/png", input, input.available());
var clipid = Components.interfaces.nsIClipboard;
var clip = Components.classes["#mozilla.org/widget/clipboard;1"].getService(clipid);
clip.setData(trans, null, clipid.kGlobalClipboard);

As Neil already noted in the newsgroup, the data expected for an image is an nsIContainer instance rather than a stream. I couldn't find any examples of doing that on the web so I modified your code:
var image = "data:image/png;base64,...";
var io = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var channel = io.newChannel(image, null, null);
var input = channel.open();
var imgTools = Components.classes["#mozilla.org/image/tools;1"].getService(Components.interfaces.imgITools);
var container = {};
imgTools.decodeImageData(input, channel.contentType, container);
var trans = Components.classes["#mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
trans.addDataFlavor("image/png");
trans.setTransferData("image/png", container.value, -1);
var clipid = Components.interfaces.nsIClipboard;
var clip = Components.classes["#mozilla.org/widget/clipboard;1"].getService(clipid);
clip.setData(trans, null, clipid.kGlobalClipboard);
For me this copies the image to clipboard correctly.

Related

Leaflet geoJSON doesn't stringify TurfCircle

I have fixed an issue with the drawing circles by the Leaflet draw plugin, where the Turf library has been provided.
Everything works fine, apart from the data, which I passed earlier by the prompt function. They come out only in the point created as the circle by standard code. Unfortunately, it is nothing for TurfCircle the same as NewTurfBuffer.
My code (used in Python folium) looks as follows:
map.on(L.Draw.Event.CREATED, function(e) {
var layer = e.layer,
type = e.layerType;
feature = layer.feature = layer.feature || {}; // Initialize feature
let x = 1
var title = prompt("Please provide the name", "default");
var value = prompt("Please provide the value", "undefined");
var id = x++;
feature.type = feature.type || "Feature"; // Initialize feature type
if (type === 'circle') {
var theCenterPt = layer.getLatLng();
var center = [theCenterPt.lng,theCenterPt.lat];
console.log(center);
console.log(title);
var theRadius = layer.getRadius();
var turfCircle;
var options = {steps: 256, units: 'meters'};
var turfCirle = turf.circle(center, theRadius, options);
var NewTurfCircle = new L.GeoJSON(turfCircle)
drawnItems.addLayer(NewTurfCircle);
var thepoint = turf.point(center);
var buffered = turf.buffer(thepoint, theRadius, {units: 'meters'});
var NewTurfBuffer = new L.GeoJSON(buffered)
drawnItems.addLayer(NewTurfBuffer);
}
var props = feature.properties = feature.properties || {}; // Initialize feature properties
props.Id = id;
props.Title = title;
props.Value = value;
var coords = JSON.stringify(layer.toGeoJSON(), NewTurfBuffer);
{%- if this.show_geometry_on_click %}
layer.on('click', function() {
alert(coords);
console.log(coords);
});
{%- endif %}
drawnItems.addLayer(layer);
});
I still get empty properties for my FeatureCollection
I think the issue can be similar to this one:
Why doesn't JSON.stringify display object properties that are functions?
https://gis.stackexchange.com/questions/332908/overlay-with-the-feature-collection-properties
but it looks like I am wrong in placing my properties inside of the FeatureCollection
https://gis.stackexchange.com/questions/25279/is-it-valid-to-have-a-properties-element-in-an-geojson-featurecollection
anyway, I am looking for a solution that will allow me to pass the data to these properties boxes.
UPDATE II:
I tried
var buffered = turf.buffer(thepoint, theRadius, {units: 'meters'});
buffered.push(layer.feature);
var NewTurfBuffer = new L.GeoJSON(buffered)
drawnItems.addLayer(NewTurfBuffer);
but an error occurs:
buffered.push is not a function
Hint taken from here:
https://gis.stackexchange.com/questions/285352/how-to-get-the-exact-circle-that-user-has-drawn-using-leaflet-draw-circle

Google Form creates Google Slides from template Script

I have a script that on Form submit takes the data from the spreadsheet and creates a copy of a template and populates the google docs. I am trying to accomplish the same thing from google form to google slides.
First script I use for the google forms to google docs. The second script is my attempt of using the same principles and applying to google slides. My issue is I'm getting an error saying TypeError: values.forEach is not a function (line 109, file "Code") in relation to values.forEach(function(page). Any suggestions on how I could go about solving this?
Google Form to Google Sheets
function autoFillGoogleDocFromForm(e) {
var timestamp = e.values[0];
var address = e.values[1];
var image = e.values[2];
var price = e.values[3];
var summary = e.values[4];
var type = e.values[5];
var year_built = e.values[6];
var bed = e.values[7];
var bath = e.values[8];
var home_size = e.values[9];
var lot_size = e.values[10];
var occupancy = e.values[11];
var templateFile = DriveApp.getFileById("xxxxxxxx");
var templateResponseFolder = DriveApp.getFolderById("yyyyyyyyyy")
var copy = templateFile.makeCopy( address , templateResponseFolder);
var doc = DocumentApp.openById(copy.getId())
var body = doc.getBody();
body.replaceText("{{address}}", address);
body.replaceText("{{price}}", price);
body.replaceText("{{summary}}", summary);
body.replaceText("{{type}}", type);
body.replaceText("{{year_built}}", year_built);
body.replaceText("{{beds}}", bed);
body.replaceText("{{baths}}", bath);
body.replaceText("{{home_size}}", home_size);
body.replaceText("{{lot_size}}", lot_size);
body.replaceText("{{occupancy}}", occupancy);
doc.saveAndClose;
}
Google Form to Google Slides
function generateLandingPagesReport(){
var dataSpreadsheetUrl = "https://docs.google.com/spreadsheets/xxxxxxxxx/edit"
var Presentation_ID = "xxxxxxxxxxxxxx";
var ss = SpreadsheetApp.openByUrl(dataSpreadsheetUrl);
var deck = SlidesApp.openById(Presentation_ID);
var sheet = ss.getSheetByName('Sheet1');
var values = sheet.getRange('A1:J17').getValues;
var slides = deck.getSlides();
var templateSlide = slides[1];
var presLength = slides.length;
values.forEach(function(page){
values.forEach(function(page){
if(page[0]){
var landingPage = page[0];
var sessions = page[1];
var newSessions = page[2];
}
templateSlide.duplicate(); // duplicate the template page
/*slides = deck.getSlides(); // update the slides array for indexes and length*/
newSlide = slides[2]; // declare the new page to update
var shapes = (newSlide.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{landing page}}', landingPage);
shape.getText().replaceAllText('{{sessions}}', sessions);
shape.getText().replaceAllText('{{new sessions}}',newSessions);
});
presLength = slides.length;
newSlide.move(presLength);
//end our condition statement
}); //close our loop of values
//remove template slide
templateSlide.remove();
});
}
You're missing the parenthesis when calling the getValue() method.
Change this:
var values = sheet.getRange('A1:J17').getValues;
To this:
var values = sheet.getRange('A1:J17').getValues();
Not exactly what I was looking for but this uses the first Row to identify the tag inside the Google slides template like {{title}} and replaces that with the value in the second row of the sheet
function createPresentation() {
var templateFile = DriveApp.getFileById("1YVEA4WtU1Kf6nZRgHpwnKBIR-V6rRN6s9zCdOQDkWNI");
var templateResponseFolder = DriveApp.getFolderById("1k7rcfXODij4o4arSULuKZUHbit1m_X64");
var copy = templateFile.makeCopy("New" , templateResponseFolder);
var Presentation = SlidesApp.openById(copy.getId());
var values = SpreadsheetApp.getActive().getDataRange().getValues();
values.forEach(function(row) {
var templateVariable = row[0];
var templateValue = row[1];
Presentation.replaceAllText(templateVariable, templateValue);
});
}
After you have copy the template page, you work on it and try to do replace.
However, change may be pending such that newSlide = slides[2]; give undefined.
You may need to try saveAndClose() before performing any actions.
templateSlide.duplicate(); // duplicate the template page
/*slides = deck.getSlides(); // update the slides array for indexes and length*/
/* flush the presentation */
deck.saveAndClose();
deck = SlidesApp.openById(Presentation_ID);
slides = deck.getSlides();
newSlide = slides[2]; // declare the new page to update
var shapes = (newSlide.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{landing page}}', landingPage);
shape.getText().replaceAllText('{{sessions}}', sessions);
shape.getText().replaceAllText('{{new sessions}}',newSessions);
});

xml using javascript with attribute missing end tag

I am trying to prepare a XML using JavaScript which should look like below.
<Service>
<NewInstance ref="External_UCSD_Serverinfo">
<Std>DiscoveredElement</Std>
<Virtual/>
<Key>Key001</Key>
<Attributes>
<Attribute name="hpom_citype" value="External_UCSD_Serverinfo"/>
</Attributes>
</NewInstance>
</Service>
i have prepared below code.
var doc = builder.newDocument();
var rootElement = doc.createElement("Service");
var NewInstance_node = doc.createElement("NewInstance");
var attr = doc.createAttribute("ref");
attr.setValue("External_UCSD_Serverinfo");
NewInstance_node.setAttributeNode(attr);
rootElement.appendChild(NewInstance_node);
var Std_node = doc.createElement("Std");
Std_node.appendChild(doc.createTextNode("DiscoveredElement"));
rootElement.appendChild(Std_node);
var Std_Virtual = doc.createElement("Virtual");
rootElement.appendChild(Std_Virtual);
var Key_node = doc.createElement("Key");
Key_node.appendChild(doc.createTextNode("Key001"));
rootElement.appendChild(Key_node);
var CIAttributes_node = doc.createElement("Attributes");
var CIAttribute_node1 = doc.createElement("Attribute");
var attr_name1 = doc.createAttribute("name");
attr_name1.setValue("hpom_citype");
var attr_val1 = doc.createAttribute("value");
attr_val1.setValue("External_UCSD_Serverinfo");
CIAttribute_node1.setAttributeNode(attr_name1);
CIAttribute_node1.setAttributeNode(attr_val1);
rootElement.appendChild(CIAttributes_node);
CIAttributes_node.appendChild(CIAttribute_node1);
doc.appendChild(rootElement);
var tf = javax.xml.transform.TransformerFactory.newInstance();
var t = tf.newTransformer();
t.setOutputProperty("omit-xml-declaration", "yes");
var sw = new StringWriter();
t.transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(sw));
but as a result i get below Output.
<Service>
<NewInstance ref='External_UCSD_Serverinfo'/>
<Std>DiscoveredElement</Std>
<Virtual/>
<Key>Key001</Key>
<Attributes>
<Attribute name='hpom_citype' value='External_UCSD_Serverinfo'/>
</Attributes>
</Service>
So i am getting what i am looking for except the end tag of "NewInstance". can soomeone tell me what i am missing? also is there simple way of writing XML Content using JavaScript?
the reason is that the nodes Std, Virtual, Key etc. are appended to rootElement instead of NewInstance_node
in detail:
var doc = document.implementation.createDocument(null, null);
var rootElement = doc.createElement("Service");
var NewInstance_node = doc.createElement("NewInstance");
var attr = doc.createAttribute("ref");
attr.value="External_UCSD_Serverinfo";
NewInstance_node.setAttributeNode(attr);
rootElement.appendChild(NewInstance_node);
var Std_node = doc.createElement("Std");
Std_node.appendChild(doc.createTextNode("DiscoveredElement"));
NewInstance_node.appendChild(Std_node);
var Std_Virtual = doc.createElement("Virtual");
NewInstance_node.appendChild(Std_Virtual);
var Key_node = doc.createElement("Key");
Key_node.appendChild(doc.createTextNode("Key001"));
NewInstance_node.appendChild(Key_node);
var CIAttributes_node = doc.createElement("Attributes");
var CIAttribute_node1 = doc.createElement("Attribute");
var attr_name1 = doc.createAttribute("name");
attr_name1.value="hpom_citype";
var attr_val1 = doc.createAttribute("value");
attr_val1.value="External_UCSD_Serverinfo";
CIAttribute_node1.setAttributeNode(attr_name1);
CIAttribute_node1.setAttributeNode(attr_val1);
rootElement.appendChild(CIAttributes_node);
CIAttributes_node.appendChild(CIAttribute_node1);
doc.appendChild(rootElement);

Photoshop/Javascript - EPS to Tiff file conversion and removing duplicates

Hey all so I have this script that converts EPS files to Tiffs in Photoshop.
At present it allows you to pick a folder of files to be converted and creates a new folder in that for the Tiff files. I had tried creating the Tiffs in the same folder without creating an extra folder but this seemed to mess with the original EPS file. The conversion was happening fine but it was taking the data out of the EPS and saving it like a blank file. Since I put the new converted Tiff files in a folder it is creating a copy of the original EPS in there too which I don't need.
Basically I need to convert all the EPS files in a folder to Tiffs but do not want to mess with the original EPS and do not want an additional copies of the file.
The script I have at present is as follows:
#include "~/AppData/Local/wbmUtils/lib/underscore.js";
//-------------- declare measurement in pixels and declare vars for HxW --------------\\
app.preferences.rulerUnits = Units.PIXELS;
var height =0;
var width = 0;
//-------------- select input and output folders --------------\\
alert("Choose a folder of EPS's");
var inPath = Folder.selectDialog();
var outPath = inPath+'/Tiffs';
$.writeln(inPath);
$.writeln(outPath);
//-------------- get full image list from input folder --------------\\
var inputs = getImageList (inPath);
function getImageList (dirPath)
{
var contents = dirPath.getFiles();
var imageList=[];
_.each(contents, function(item)
{
imageList.push(item.toString());
})
return imageList;
}
//-------------- create new folder for files --------------\\
$.writeln(inputs);
var imageFolderName = outPath;
var imageFolder = Folder(imageFolderName);
if(!imageFolder.exists) imageFolder.create();
_.each(inputs, function(input)
{
$.writeln("height: " + height + " width: " + width);
var imgWithExt = _.last(input.split('/'))
doPreviews(input, imageFolderName +'/' + imgWithExt);
var of = new File(input);
of.copy (imageFolderName +'/' + imgWithExt.split('.')[0] + '.eps');
})
//-------------- main conversion function --------------\\
function doPreviews(input, output)
{
var idOpn = charIDToTypeID("Opn ");
var desc4 = new ActionDescriptor();
var idnull = charIDToTypeID("null");
desc4.putPath(idnull, new File(input));
var idAs = charIDToTypeID("As ");
var desc5 = new ActionDescriptor();
var idRslt = charIDToTypeID("Rslt");
var idRsl = charIDToTypeID("#Rsl");
desc5.putUnitDouble(idRslt, idRsl, 300.000000);
var idAntA = charIDToTypeID("AntA");
desc5.putBoolean(idAntA, true);
var idEPSG = charIDToTypeID("EPSG");
desc4.putObject(idAs, idEPSG, desc5);
executeAction(idOpn, desc4, DialogModes.NO);
var idMk = charIDToTypeID("Mk ");
var desc7 = new ActionDescriptor();
var idnull = charIDToTypeID("null");
var ref1 = new ActionReference();
var idDcmn = charIDToTypeID("Dcmn");
ref1.putClass(idDcmn);
desc7.putReference(idnull, ref1);
var idUsng = charIDToTypeID("Usng");
var ref2 = new ActionReference();
var idHstS = charIDToTypeID("HstS");
var idCrnH = charIDToTypeID("CrnH");
ref2.putProperty(idHstS, idCrnH);
desc7.putReference(idUsng, ref2);
executeAction(idMk, desc7, DialogModes.NO);
height = app.activeDocument.height;
width = app.activeDocument.width;
if (height > width)
{
$.writeln("IS HIGHER THAN WIDE");
var idImgS = charIDToTypeID("ImgS");
var desc8 = new ActionDescriptor();
var idHght = charIDToTypeID("Hght");
var idPxl = charIDToTypeID("#Pxl");
desc8.putUnitDouble(idHght, idPxl, 6500.000000);
var idscaleStyles = stringIDToTypeID("scaleStyles");
desc8.putBoolean(idscaleStyles, true);
var idCnsP = charIDToTypeID("CnsP");
desc8.putBoolean(idCnsP, true);
var idIntr = charIDToTypeID("Intr");
var idIntp = charIDToTypeID("Intp");
var idautomaticInterpolation = stringIDToTypeID("automaticInterpolation");
desc8.putEnumerated(idIntr, idIntp, idautomaticInterpolation);
executeAction(idImgS, desc8, DialogModes.NO);
} else {
$.writeln("IS WIDER THAN HIGH");
var idImgS = charIDToTypeID("ImgS");
var desc32 = new ActionDescriptor();
var idWdth = charIDToTypeID("Wdth");
var idPxl = charIDToTypeID("#Pxl");
desc32.putUnitDouble(idWdth, idPxl, 6500.000000);
var idscaleStyles = stringIDToTypeID("scaleStyles");
desc32.putBoolean(idscaleStyles, true);
var idCnsP = charIDToTypeID("CnsP");
desc32.putBoolean(idCnsP, true);
var idIntr = charIDToTypeID("Intr");
var idIntp = charIDToTypeID("Intp");
var idautomaticInterpolation = stringIDToTypeID("automaticInterpolation");
desc32.putEnumerated(idIntr, idIntp, idautomaticInterpolation);
executeAction(idImgS, desc32, DialogModes.NO);
}
var idMk = charIDToTypeID("Mk ");
var desc20 = new ActionDescriptor();
var idnull = charIDToTypeID("null");
var ref4 = new ActionReference();
var idDcmn = charIDToTypeID("Dcmn");
ref4.putClass(idDcmn);
desc20.putReference(idnull, ref4);
var idUsng = charIDToTypeID("Usng");
var ref5 = new ActionReference();
var idHstS = charIDToTypeID("HstS");
var idCrnH = charIDToTypeID("CrnH");
ref5.putProperty(idHstS, idCrnH);
desc20.putReference(idUsng, ref5);
executeAction(idMk, desc20, DialogModes.NO);
var idCls = charIDToType("Cls ");
executeAction(idCls, desc20, DialogModes.NO);
//-------------- tiff options --------------\\
tiffSaveOptions = new TiffSaveOptions();
tiffSaveOptions.byteOrder = ByteOrder.MACOS;
tiffSaveOptions.layers = false;
tiffSaveOptions.transparency = true;
tiffSaveOptions.alphaChannels = true;
tiffSaveOptions.embedColorProfile = false;
tiffSaveOptions.imageCompression = TIFFEncoding.TIFFLZW;
tiffSaveOptions.saveImagePyramid = false;
app.activeDocument.saveAs(File(output.split('.')[0]+'.tiff'), tiffSaveOptions, true);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}
//-------------- success message --------------\\
alert("ALL DONE!")
I would be inclined to do this with ImageMagick which is installed on most Linux distros and is available for OSX and Windows.
So, at the command-line in your Terminal:
mkdir TIFFs # Make the output directory called "TIFFs"
mogrify -format tif -path TIFFs *.eps # Convert all EPS to TIFFs/*.tif

Having trouble with image preload code

I have this object constructor function that has a preload method for preloading
rollover images pairs.
So, I have two questions:
1: why is the alert dialog just doing 'STR: ' with no data attached? (this type of problem is generally due to my blindness.
2: is it possible to treat the this.buttons_on and this.buttons_off as objects in that instead of
a numerical index, use a sting index so the rollover event handler does not need to loop through
the buttons_on and buttons_off arrays to get the one that should be swapped out;
function _NAV()
{
this.list_off = [];
this.list_on = [];
this.buttons_on = [];
this.buttons_off = [];
this.buttons_all = {}; // .on and .off
this.button_events = {};
this.img = true;
this.img_ids = {}
this.preLoad = function()
{
if(document.images) //creates image object array for preload.
{
var STR = '';
for(var i = 0; i < list_off.length; i++)
{
var lab_on = list_on[i].replace('\.jpg', '');
var lab_off = list_off[i].replace('\.jpg', '');
STR += lab_on+'||'+lab_off+"\n";
this.buttons_on[i] = new Image();
this.buttons_on[i].src = srcPath+list_on[i];
this.bottons_on[i].id = img_ids[i];
this.buttons_off[i] = new Image();
this.buttons_off[i].src = srcPath+list_off[i];
this.buttons_off[i].id = img_ids[i];
}
alert("STR: "+STR);
}
else
{
this.img = false
}
}
//// ...etc...
Here is the call before the onload event fires
var rollover = new _NAV();
rollover.preLoad();
Here are the arrays used
var srcPath = '../nav_buttons/';
var list_off = new Array(); // not new Object;
list_off[0] = "bio_off.jpg";
list_off[1] = "cd_off.jpg";
list_off[2] = "home_off.jpg";
list_off[3] = "inst_off.jpg";
list_off[4] = "photo_off.jpg";
list_off[5] = "rev_off.jpg";
list_off[6] = "samp_off.jpg";
var list_on = new Array();
list_on[0] = "bio_on.jpg";
list_on[1] = "cd_on.jpg";
list_on[2] = "home_on.jpg";
list_on[3] = "inst_on.jpg";
list_on[4] = "photo_on.jpg";
list_on[5] = "rev_on.jpg";
list_on[6] = "samp_on.jpg";
var img_ids = new Array();
Thanks for time and attention.
1:
Try PHPGlue's suggestion and add this. in front of all your member variables (this.list_on, this.list_off, this.img_ids)
You also have a typo on one line. bottons_on is misspelled.
this.bottons_on[i].id = img_ids[i];
2:
Yes, you can use a string as an index. Just make buttons_on and buttons_off objects instead of arrays.
function _NAV()
{
this.buttons_on = {};
this.buttons_off = {};
// For example:
this.buttons_off[lab_off] = new Image();
}

Categories

Resources