Drag a file from my GTK app to another app (not the other way around) - drag-and-drop

I have searched for examples, but all the examples were the opposite direction (my app is getting file drag-and-drop from another application). But this must be possible because I can drag a file from Files (Nautilus) to another app, Text Editor (gedit).
Could you show me a very simple example of a GTK Window with one widget on it, and when I drag from the widget to Text Editor, it passes a text file on the system (such as /home/user/.profile) to the Text Editor so that it will open the text file?

In order to make it so that your application can receive files, you need to use uri. In the function you bind to drag-data-received, you can use data.get_uris() to get a list of the files that were dropped. Make sure that you call drag_dest_add_uri_targets(), so that the widget can receive URIs.
This code example has one button that drags a file, and another button that can receive it. You can also drag the file and drop it into any file-receiving app, such as gedit (Text Editor) or VSCode.
import gi
gi.require_version("Gdk", "3.0")
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk
window = Gtk.Window()
window.connect("delete-event", Gtk.main_quit)
box = Gtk.HBox()
window.add(box)
# Called when the Drag button is dragged on
def on_drag_data_get(widget, drag_context, data, info, time):
data.set_uris(["file:///home/user/test.html"])
# Called when the Drop button is dropped on
def on_drag_data_received(widget, drag_context, x, y, data, info, time):
print("Received uris: %s" % data.get_uris())
# The button from which the file is dragged
drag_button = Gtk.Button(label="Drag")
drag_button.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, [], Gdk.DragAction.LINK)
drag_button.drag_source_add_uri_targets() # This makes sure that the buttons are using URIs, not text
drag_button.connect("drag-data-get", on_drag_data_get)
box.add(drag_button)
# The button into which the file can be dropped
drop_button = Gtk.Button(label="Drop")
drop_button.drag_dest_set(Gtk.DestDefaults.ALL, [], Gdk.DragAction.LINK)
drop_button.drag_dest_add_uri_targets() # This makes sure that the buttons are using URIs, not text
drop_button.connect("drag-data-received", on_drag_data_received)
box.add(drop_button)
window.show_all()
Gtk.main()

Mr Kruin's answer was for Python's GTK. The language I actually wanted was C#. Using his code as a hint, I modified the default GtkApplication project like so, and it worked on Linux.
private MainWindow(Builder builder) : base(builder.GetRawOwnedObject("MainWindow"))
{
builder.Autoconnect(this);
DeleteEvent += Window_DeleteEvent;
_button1.DragDataGet += (o, args) =>
{
args.SelectionData.SetUris(new string[]{fullFilePath});
};
Gtk.Drag.SourceSet(_button1, Gdk.ModifierType.Button1Mask,
new TargetEntry[0],
Gdk.DragAction.Link);
Gtk.Drag.SourceAddUriTargets(_button1);
}
On Windows, however, it did not work. I have tried both string fullFilePath = "file:///c:/windows/win.ini" and string fullFilePath = "c:\\windows\\win.ini" and none of them seemed to work.

Related

Visual Studio Code: Is it possible to make a decorations hoverMessage clickable

Hi I am developing an extension for VSCode. I am decorating the text editor and hovering some items. Is it possible to make clickable items at hoverMessage and modify the range according to it.
The extension is at:
https://marketplace.visualstudio.com/items?itemName=serayuzgur.crates
You can see the hoverMessage from the GIF
Yes, using markdown you can then create a command link that will execute a command when a user clicks on it:
import * as vscode from 'vscode';
const myContent = new vscode.MarkdownString('[link](command:myCommand?arg1)');
// Command Uris are disabled by default for security reasons.
// If you set this flag, make sure your content is not constructed
// using untrusted/unsanitized text.
myContent.isTrusted = true;
const myHover = new Hover(myContent);
This command can perform whatever action you want

Dat.GUI: A few questions

I'm making a small billiards game in THREE.js, and have opted to use Dat.Gui as a GUI library. I have a few small questions regarding the latter:
First Question: Can I make a class that returns the GUI?
Currently I have a mygui.js file where I put the code of the gui (the example code[1], let's say), and I include that in mygame.html before the main.js. However, all other objects (table, balls, lights, etc) are classes and I'd like to do that too with the GUI. When I place everything inside a
class MyGUI {
constructor() {
//javascript part of the example here
return gui;
}
}
and then call in main.js
var mygui = new MyGUI();
the GUI isn't showing up, but when I don't include the class and the line in main.js, it works. I have downloaded dat.gui.min.js and included it in the html.
Second Question: I want to change variables now and then based on when I call the gui's change function, but how would I go about that without classes (should that not work)?
Third Question: I want to use the GUI, only to display values. Users are not supposed to change it. Can I make the GUI read-only? (to be clear: changing the values in the GUI will not change gameplay, they're just textual representations of the state of the game)
Fourth Question: I want to remove the top part of the GUI (where you can load/save presets or something). How do I do that?
Progressive insights:
As linked by #prisoner849: Page 9 of the example/tutorial.
gui.add(param, 'theSetting').listen();
function updateTheSetting(newVal){ param.theSetting = newVal; }
When param.theSetting is updated, and the added param listen()s to it, a change in the param.theSetting will automatically update the GUI.
Don't use gui.remember( someParameters ) and the save part will dissapear.

ITextPDF - Link creation with PDFAnnotation

I have a question about hyperlinks within pdf documents created with itext. Currently, using the following code written in java, I am able to successfully create links. However, when I hover over the link, the link text is displayed. The client does not want the link text to appear upon hover-over. How can I either remove the hover-over, or give it alternate text to display (e.g. "Course Info")? I am using itext version 5.5.9. I have looked at "iText in Action" chapter 7 but was not able to find what I needed. Is there a better way to create the links? Any help and examples will be appreciated. Thanks.
package edu.ucsd.act.academic.studente2t.util;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfAnnotation;
import com.itextpdf.text.pdf.PdfBorderArray;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPCellEvent;
import com.itextpdf.text.pdf.PdfWriter;
class LinkInCellEvent implements PdfPCellEvent
{
protected String url;
public LinkInCellEvent(String url)
{
this.url = url;
}
public void cellLayout(PdfPCell cell, Rectangle position,
PdfContentByte[] canvases)
{
PdfWriter writer = canvases[0].getPdfWriter();
PdfAction action = new PdfAction(url);
PdfAnnotation link = PdfAnnotation.createLink(writer, position,
PdfAnnotation.HIGHLIGHT_INVERT, action);
PdfBorderArray border = new PdfBorderArray(0, 0, 0);
link.setBorder(border);
writer.addAnnotation(link);
}
}
This is not an iText problem. It's inherent to PDF. The PDF specification (ISO-32000-1) doesn't say anything about the way viewers should present tool tips for link annotations.
Your client (who probably should also be our client), may be confused by the following concepts:
Additional actions
The only occurrence of the word "tool tip" is in a NOTE when the E (enter) and X (exit) event are described in the section about additional actions. One can use additional actions, for instance on a widget annotation, to have a custom tool tip appear / disappear when someone hovers over a widget annotation.
When you study the PDF standard, you will see that there are several instances where you can define additional action (/AA), but link annotations aren't one of them.
Alternative field name
There's also the /TU entry (formerly known as the user name entry), which is (I quote the spec) an alternative field name that shall be used in place of the actual field name wherever the field shall be identified in the user interface (such as in error or status messages referring to the field). This text is also useful when extracting the document’s contents in support of accessibility to users with disabilities or for other purposes. The value of the /TU entry is often used by viewers as a tool tip, but as you can tell from the description, the /TU entry is specific for fields, not for annotations. It can only be used in a field dictionary, not in an annotation dictionary.
Conclusion:
Whatever is shown when someone hovers over a link annotation is not described in the specification. Every vendor of a PDF viewer may decide what to show (if anything) when a user hovers over a link annotation. There is no way to add something to the PDF that can force the viewer to show something else (or nothing).

How to redirect key presses to another shell in an Eclipse-based app?

I'm working on a way to maximise an EditorPart in my Eclipse-based RCP app to be absolutely full-screen, no trim, no menu, and so on. Actually, it's a GEF Editor. It's a bit of a hack, but it kind of works:
GraphicalViewer viewer = (GraphicalViewer)getWorkbenchPart().getAdapter(GraphicalViewer.class);
Control control = viewer.getControl();
Composite oldParent = control.getParent();
Shell shell = new Shell(SWT.APPLICATION_MODAL);
shell.setFullScreen(true);
shell.setMaximized(true);
// Some code here to listen to Esc key to dispose Shell and return...
shell.setLayout(new FillLayout());
control.setParent(shell);
shell.open();
Basically it sets the parent of the GraphicalViewer control to the newly created, maximised Shell. Pressing escape will return the control to it's original parent (code not shown for brevity).
The only thing that doesn't work is receiving global key presses (Del, Ctrl+Z, Ctrl+A) the ones that are declared for the Workbench and forwarded to the EditorPart. Is there any way I can hook into these or redirect them from the EditorPart to forward them on to the GraphicalViewer?
Thanks in advance
The short answer is you can't do that. Once you re-parent that composite out of the workbench window, it's totally busted. The system won't correctly deal with the part, as events (like activation, focus, setBounds(*)) aren't being processed.
The only supported way would be to open a new Workbench window with a perspective that only contained the editor area, and extending your org.eclipse.ui.application.WorkbenchWindowAdvisor.createWindowContents(Shell) method for that window+perspective combination to hide all of the trim you don't want, using org.eclipse.ui.application.IWorkbenchWindowConfigurer.
ex, in MyWorkbenchWindowAdvisor:
public void createWindowContents(Shell shell) {
if (isCreatingSpecialPerspective()) {
final IWorkbenchWindowConfigurer config = getWindowConfigurer();
config.setShowCoolBar(false);
config.setShowFastViewBars(false);
config.setShowMenuBar(false);
config.setShowPerspectiveBar(false);
config.setShowProgressIndicator(false);
config.setShowStatusLine(false);
}
super.createWindowContents(shell);
}
Also check out http://code.google.com/p/eclipse-fullscreen/ which has EPLed code in it concerned with running an RCP program with fullscreen support.
My suggestion is to try to approach this problem from another angle. Instead of listening for keystrokes in your code and acting upon them, define your own key binding scheme and then create commands and make them use this scheme. This would mean that you no longer have to listen for the key strokes in your code, but instead do whatever needs to be done through commands executed by these key strokes.

How to add content control in a Word 2007 document using OpenXML

I want to create a word 2007 document without using object model. So I would prefer to create it using open xml format. So far I have been able to create the document. Now I want to add a content control in it and map it to xml. Can anybody guide me regarding the same???
Anoop,
You said that you are able to creat the document using OpenXmlSdk. With that assumption, you can use the following code to create the content control to add to the Wordprocessing.Body element of your Document.
//praragraph to be added to the rich text content control
Run run = new Run(new Text("Insert any text Here") { Space = StaticTextConstants.Preserve });
Paragraph paragraph = new Paragraph(run);
SdtProperties sdtPr = new SdtProperties(
new Alias { Val = "MyContentCotrol" },
new Tag { Val = "_myContentControl" });
SdtContentBlock sdtCBlock = new SdtContentBlock(paragraph);
SdtBlock sdtBlock = new SdtBlock(sdtPr, sdtCBlock);
//add this content control to the body of the word document
WordprocessingDocument wDoc = WordprocessingDocument.Open(path, true); //path is where your word 2007 file is
Body mBody = wDoc.MainDocumentPart.Document.Body;
mBody.AppendChild(sdtBlock);
wDoc.MainDocumentPart.Document.Save();
wDoc.Dispose();
I hope this answers a part of your question. I did not understand what you ment by "Map it to XML". Did you mean to say you want to create CustomXmlBlock and add the ContentControl to it?
Have a look for the Word Content Control Toolkit on www.codeplex.com.
Here is a very brief explanation on how to do what you are attempting.
You need to have access to the developer tab on the Word ribbon. To get this working click on the Office (Round thingy) in the top left hand corner and Select Word Options at the bottom of the menu. On the first options page there is a checkbox to show the developer toolbar.
Use the developer toolbar to add the Content controls you want on the page. Click the properties button in the Content controls section of the developer bar and set the name and tag properties (I stick to naming the name and tag fields with the same name).
Save and close the word document.
Open the Content control toolkit and then open your document with the toolkit. Use the left hand pain to create some custom xml to link to your controls.
Now use the bind view to drag and drop the mappings between your custom xml and the custom controls that are displayed in the right panel of the toolkit.
You can use the openxml sdk 1.0 or 2.0 (still in ctp) to open your word document in code and access the custom xml file that is contained as part of the word document.
If you want to have a look at how your word document looks as xml. Make a copy of your word document and then rename it to say "a.zip". Double click on the zip file and then navigate the folder structure. The main content of the word document is held under the word folder in a file called "document.xml". The custom xml part of the document is held under the customXml folder and is generally found in the file named "item1.xml".
I hope this brief explanation get you up and running.