Make jxBrowser open popups in the current window instead of "popping up" - popup

How to set jxBrowser to open links that would pop-up in a new window to open on the calling page (or, at least, in a new tab)?
this is the call I think I have to override (it's the example):
//....
Engine engine = Engine.newInstance(
EngineOptions.newBuilder(
enderingMode.OFF_SCREEN ).enableIncognito().build()
Browser _browser = engine.newBrowser();
//this won't even compile
_browser.set(
OpenPopupCallback.class,
(params) -> {
// Access the created popup.
Browser popup = params.popupBrowser();
_browser.navigation().loadUrl(params.targetUrl());
return Response.proceed();
});
_browser.navigation().loadUrl("http://www.stackoverflow.com");
This is how I call it in my jfx but won't even compile, the code without this call works (opens a browser).
Update, given the nature of the popup I tried to rewrite javascript function (window.open) itself to force name to _parent.
This by running on every navigation the code
String the Javascript = "window.open = function (open) {return function (url, name, features{ console.log("open wrapper");return open.call(window, url, '_parent', features);};}(window.open);"
I thaught I couldn achieve this by
_browser.frames().get(0).executeJavaScript(theJavascript);
But in the remote console, I can't even see the log message ("open wrapper").
I double-checked the same code and it works if copy-pasted in the remote consolle.
What am I missing?

Here's complete JavaFX example that demonstrates how to open popup's URL in the main Browser instance and suppress popup:
import static com.teamdev.jxbrowser.engine.RenderingMode.OFF_SCREEN;
import com.teamdev.jxbrowser.browser.Browser;
import com.teamdev.jxbrowser.browser.callback.CreatePopupCallback;
import com.teamdev.jxbrowser.browser.callback.CreatePopupCallback.Response;
import com.teamdev.jxbrowser.engine.Engine;
import com.teamdev.jxbrowser.view.javafx.BrowserView;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public final class SmokeTest extends Application {
#Override
public void start(Stage primaryStage) {
// Creating and running Chromium engine.
Engine engine = Engine.newInstance(OFF_SCREEN);
Browser browser = engine.newBrowser();
browser.set(CreatePopupCallback.class, params -> {
browser.navigation().loadUrl(params.targetUrl());
return Response.suppress();
});
// Creating UI component for rendering web content
// loaded in the given Browser instance.
BrowserView view = BrowserView.newInstance(browser);
BorderPane root = new BorderPane(view);
Scene scene = new Scene(root, 1280, 900);
primaryStage.setTitle("Hello World");
primaryStage.setScene(scene);
primaryStage.show();
browser.navigation().loadUrl(
"https://www.encodedna.com/javascript/demo/open-new-window-using-javascript-method.htm");
// Close the engine when stage is about to close.
primaryStage.setOnCloseRequest(event -> engine.close());
}
}
Run this program and click a button that displays popup. You will see that popup is not displayed and its URL is loaded in the main Browser.

Related

Create new NetBeans "save as" module

My goal is simple - save the current HTML file in the NetBeans editor with one additional line at the top and bottom of the file, and with the extension of ".h".
This is my first attempt at a NetBeans module, but following some tutorials and research, I got as far as adding an entry to the popup menu when you right-click on an HTML file in the editor. It currently just shows a "Hello World" message:
The code to do that is here:
package ksmiller99.savehtmlasarduinoresource;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
#ActionID(
category = "Edit",
id = "ksmiller99.savehtmlasarduinoresource.SaveHtmlAsArduinoResource"
)
#ActionRegistration(
displayName = "#CTL_SaveHtmlAsArduinoResource"
)
#ActionReference(path = "Editors/text/html/Popup")
#Messages("CTL_SaveHtmlAsArduinoResource=Save as Arduino Resource")
public final class SaveHtmlAsArduinoResource implements ActionListener {
#Override
public void actionPerformed(ActionEvent ev) {
//todo add a line to top and bottom of current file and save with .h extension
JOptionPane.showMessageDialog(null, "Hello Save As World");
}
}
How can I access the contents of the current editor? Would a different approach make more sense?
I'm using NetBeans 12.0, JDK 13, Windows 10.
Use the New Action wizard to create the source code for a Conditionally Enabled action, enabled when User Selects One Node.
In the 2nd wizard panel select File Type Context Menu and choose text/html as content type. If you want your action to appear only in the context menu you can disable Global Menu Item.
You should end up with code like this:
#ActionID(
category = "File",
id = "org.test.TestHtmlAction"
)
#ActionRegistration(
displayName = "#CTL_TestHtmlAction"
)
#ActionReference(path = "Loaders/text/html/Actions", position = 0)
#Messages("CTL_TestHtmlAction=TestHtmlAction")
public final class TestHtmlAction implements ActionListener
{
private final DataObject context;
private static final Logger LOGGER = Logger.getLogger(TestHtmlAction.class.getName());
public TestHtmlAction(DataObject context)
{
this.context = context;
}
#Override
public void actionPerformed(ActionEvent ev)
{
FileObject file = context.getPrimaryFile();
LOGGER.info("context=" + context.getName() + " file.getPath()=" + file.getPath());
}
}
The wizard creates a context aware action, which is enabled only when user selects a single HTML file node. The DataObject parameter gives you the context of the selected node, so you can retrieve the file path etc.

Why isn't Gtk Filechooser Button selecting any file in my flatpak build?

I have a file chooser button that triggers a change in the titlebar whenever a file is selected with it. And it seems to work fine in my non-flatpak build.
import gtk.Application : Application;
import gtk.ApplicationWindow : ApplicationWindow;
import gio.Application : GioApp = Application;
import gtkc.gtktypes : GApplicationFlags, FileChooserAction;
import gtk.FileChooserButton : FileChooserButton;
const string AppID = `org.github.flatfcbtest`;
int main(string[] args)
{
auto app = new App();
return app.run(args);
}
public class App : Application
{
public:
this(const string appID = AppID, const GApplicationFlags flags = GApplicationFlags.FLAGS_NONE)
{
super(appID, flags);
addOnActivate(delegate void(GioApp _) {
auto pw = new PrimaryWindow(this);
pw.showAll();
});
}
}
class PrimaryWindow : ApplicationWindow
{
this(Application app)
{
super(app);
setSizeRequest(500, 300);
auto fcb = new FileChooserButton(`Select file`, FileChooserAction.OPEN);
fcb.addOnFileSet(delegate void (FileChooserButton _) {
setTitle(`file set!`);
});
add(fcb);
}
}
(GtkD reference)
However in my flatpak builds, the file selected with the chooser button does not select anything and it keeps saying (None). However my titlebar is changes accordingly so I know that the signal was emitted by the file chooser button.
Here is my flatpak permissions list:
finish-args:
- --socket=fallback-x11
- --share=ipc
- --filesystem=host
- --device=all
- --socket=session-bus
What's causing this?
Typically if you're shipping a flatpak, you want to avoid --filesystem=host and just use GtkFileChooserNative instead. This class supports portals, allowing a user to select files the application does not have permission to access by itself.
This is a much better approach than giving the application full filesystem access. GtkFileChooserNative will still work in a non-flatpak application and you shouldn't notice any difference unless you're doing something fancy.
As for your question of why GtkFileChooser is not working with --filesystem=host however, I do not know.

I am unable to upload attachment using SeleniumWebDriver

This is my Code
driver.findElement(By.id("ctl00_ContentPlaceHolder1_cbpAssociationNew_panelAssnDetailAdd_Add_Photo_Browse0")).click();
Thread.sleep(2000);
StringSelection ss= new StringSelection("C:\\Users\\ns10\\Desktop\\download.jpg");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
Robot robo=new Robot();
robo.delay(1000);
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);
robo.keyPress(KeyEvent.VK_CONTROL);
robo.keyPress(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_CONTROL);
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);
When I run the above code in Eclipse, it clicks on the File upload; then the windows pop up comes but doesn't select the file which I mentioned. It was just idle.
Could someone please help me with this.
If possible try this first,
driver.findElement(By.id("ctl00_ContentPlaceHolder1_cbpAssociationNew_panelAssnDetailAdd_Add_Photo_Browse0")).sendKeys("C:\\Users\\ns10\\Desktop\\download.jpg");
This is a noted way to upload file via selenium webdriver as of now, where you don't have to bother about clicking on the File Upload button and then using Robot class to upload image. Just sending the path of the file to upload will accomplish the Upload.
If it still doesn't work, then below is the alternative way by using Robot and Sikuli (combined) to accomplish the task:-
Problem:-
Sometimes, the Robot class types the "attachment_path" into the "File Name" field of textbox but doesn't presses 'Enter key' thereafter for the file to upload.
Solution:-
To avert that, I've used Sikuli to click on the Open button, which does infact uploads the file then;
(Note:- You have to take a screenshot of Open button in the window's dialog box, that comes up after clicking on the "File Upload button".
First of all download sikuli-api standalone jar. And, add it to the build path of your project. Then, add the below code for the file upload:-
//Clicking on the File Upload button
driver.findElement(By.id("ctl00_ContentPlaceHolder1_cbpAssociationNew_panelAssnDetailAdd_Add_Photo_Browse0")).click();
//Copying the path of the file to the clipboard
StringSelection attachment = new StringSelection("C:\\Users\\ns10\\Desktop\\download.jpg"); //path to the attachment
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(attachment, null);
//Pasting the contents of clipboard in the field "File name" of the Window Pop-up
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
try{
ScreenRegion screen = new DesktopScreenRegion(); //screen is the default screen region which corresponds to the entire screen on your default monitor.
Target target = new ImageTarget(new File("<PUT HERE THE PATH FOR THE OPEN BUTTON'S IMAGE>"));
ScreenRegion screen_web = screen.wait(target,5000);
screen_web = screen.find(target); //screen_web holds the screen region occupied by the "Open" button that was found by Sikuli's image recognition engine.
if(screen_web != null)
{
Mouse mouse = new DesktopMouse(); // Create a mouse object
mouse.click(screen_web.getCenter()); // Use the mouse object to click on the center of the target region, i.e., the Open button
}else{
throw new Throwable();
}
}catch(Throwable e){
System.err.println("The Open file button wasn't clicked!!" + e.getMessage() + "\n---------------------");
}
Code for Uploading in Tiny Pic.com :-
package pack_ads;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.sikuli.api.DesktopScreenRegion;
import org.sikuli.api.ImageTarget;
import org.sikuli.api.ScreenRegion;
import org.sikuli.api.Target;
import org.sikuli.api.robot.Mouse;
import org.sikuli.api.robot.desktop.DesktopMouse;
public class Testing_TinyPicUpload {
public static void main(String[] args) throws AWTException, InterruptedException {
WebDriver driver = new FirefoxDriver(); //Opens a firefox browser instance
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); //Timeout of 30 seconds given
driver.manage().window().maximize(); //Maximizing the window
//Navigating to tiny pic site
driver.get("http://tinypic.com/");
//Uploading photo
driver.findElement(By.xpath("//input[#id='the_file']")).click(); //Locating the attach button
//Copying the path of the file to the clipboard
StringSelection photo = new StringSelection("D:\\\\Images\\default.jpg"); //Putting the path of the image to upload
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(photo, null);
//Pasting the contents of clipboard in the field "File name" of the Window Pop-up
Thread.sleep(5000);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
try{
ScreenRegion screen = new DesktopScreenRegion(); //screen is the default screen region which corresponds to the entire screen on your default monitor.
Target target = new ImageTarget(new File("Tinyimages\\Open_file.png")); //Made a folder in my project as Tinyimages and put the image of Open_file in there.
ScreenRegion screen_web = screen.wait(target,5000);
screen_web = screen.find(target); //screen_web holds the screen region occupied by the "Open" button that was found by Sikuli's image recognition engine.
if(screen_web != null)
{
Mouse mouse = new DesktopMouse(); // Create a mouse object
mouse.click(screen_web.getCenter()); // Use the mouse object to click on the center of the target region, i.e., the Open button
}
else{
throw new Throwable();
}
System.out.println("Attachment was successfully done.\n------------------------------\n");
}catch(Throwable e){
System.err.println("The Open file button wasn't clicked!!" + e.getMessage() + "\n------------------------------");
}
}
}
Note: You can download use this image for the "Open" button from here. Change the file path accordingly in the code Target target = new ImageTarget(new File("Tinyimages\\Open_file.png"));
I was finding the same result, that the code would halt and wait when the File Upload window was opened, and would only continue after the window was closed.
As a workaround I put the thread sleep and the robot keypresses in a separate thread that I spawned just before clicking the file upload button. This solved the issue for me.
// Thread class to be instantiated and run just before button click:
//
public class PasteUploadFileThread extends Thread {
String uploadFileName = "";
public PasteUploadFileThread(String filename){
this.uploadFileName = filename;
}
public void run() {
try {
// Pause 3 seconds giving window time to open up
Thread.sleep(3000);
System.out.println("STARTING PasteUploadFileThread for file: " + this.uploadFileName);
StringSelection ss= new StringSelection(this.uploadFileName);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
Robot robo=new Robot();
robo.delay(2000);
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);
robo.keyPress(KeyEvent.VK_CONTROL);
robo.keyPress(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_CONTROL);
robo.delay(2000);
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);
System.out.println("ENDING PasteUploadFileThread for file: " + this.uploadFileName);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (AWTException e) {
e.printStackTrace();
}
}
}
// Portion of the test class that spawns the thread and then clicks the button
String filepath = "C:\\UploadDocument.txt";
WebElement browseButton = wait60Secs.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//span[contains(.,'Browse')]")));
// Spawn a thread that will do the interacting with the File Upload window.
// This is needed because when we click on the browse button the code halts waiting for the File Upload window to be closed.
// So this thread will go off on it's own and do it's work while this code is paused.
(new PasteUploadFileThread(filepath)).start();
browseButton.click();
// Execution continues here after the Upload window is closed...
// Find the file that was uploaded before continuing
wait60Secs.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[contains(.,'UploadDocument.txt')]")));

Disabling toolbar from icePDF viewer

I am trying a sample with icePDF . Everything is working fine but i need to disable the toolbar which appears at the top. i tried few things but its not working. Can some body please help me out with it. Below is my code.
//package XML.test;
package applet;
import java.util.ResourceBundle;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.icepdf.ri.common.ComponentKeyBinding;
import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;
import org.icepdf.ri.util.PropertiesManager;
import org.icepdf.core.pobjects.fonts.*;
import org.icepdf.core.views.DocumentViewController;
import org.icepdf.core.*;
public class ViewerComponentExample
{
static void buildFrame(String filepath)
{
System.getProperties().put("org.icepdf.core.scaleImages", "false");
System.getProperties().put("org.icepdf.core.imageReference","smoothScaled");
System.getProperties().put("org.icepdf.core.target.dither", "VALUE_DITHER_DISABLE");
System.getProperties().put("org.icepdf.core.target.fractionalmetrics", "VALUE_FRACTIONALMETRICS_OFF");
System.getProperties().put("org.icepdf.core.target.interpolation", "VALUE_INTERPOLATION_NEAREST_ NEIGHBOR");
System.getProperties().put("org.icepdf.core.screen.interpolation", "VALUE_INTERPOLATION_NEAREST_NEIGHBOR");
System.getProperties().put("org.icepdf.core.awtFontLoading","true");
SwingController controller = new SwingController();
PropertiesManager properties = new PropertiesManager(System.getProperties(), ResourceBundle.getBundle(PropertiesManager.DEFAULT_MESSAGE_BUNDLE));
properties.setBoolean(PropertiesManager.PROPERTY_SHOW_TOOLBAR_ANNOTATION, Boolean.FALSE);
properties.setBoolean(PropertiesManager.PROPERTY_SHOW_TOOLBAR_FIT, Boolean.FALSE);
// Build a SwingViewFactory configured with the controller
SwingViewBuilder factory = new SwingViewBuilder(controller);
JPanel viewerComponentPanel = factory.buildViewerPanel();
// add copy keyboard command
ComponentKeyBinding.install(controller, viewerComponentPanel);
// add interactive mouse link annotation support via callback
controller.getDocumentViewController().setAnnotationCallback(
new org.icepdf.ri.common.MyAnnotationCallback(
controller.getDocumentViewController()));
// Use the factory to build a JPanel that is pre-configured
//with a complete, active Viewer UI.
// Create a JFrame to display the panel in
JFrame window = new JFrame("Metrics Wizard Help");
window.getContentPane().add(viewerComponentPanel);
window.pack();
window.setVisible(true);
controller.setPageFitMode(DocumentViewController.PAGE_FIT_WINDOW_WIDTH, false);
controller.openDocument(filepath);
}
public static void main(String args[])
{
String filepath = "C:/Users/vishalt/Workspaces/Eclipse 4.2 Java/htmltopdf/src/XML/output/SCB_TEST.pdf";
buildFrame(filepath);
}
}
private SwingController controller;
controller = new SwingController();
SwingViewBuilder viewBuilder = new SwingViewBuilder(controller, properties);
JPanel panel = viewBuilder.buildViewerPanel();
controller.setToolBarVisible(false);
You have to set the toolbar invisible because icePdf looks in the PDF-document for the property and overwrites your setting with default when there is no document opened!
There are two ways to this.
1) Follow this example to set all the toolbars to false.
http://www.icesoft.org/JForum/posts/list/17673.page#sthash.48ICrL2A.dpbs
2) You can modify or remove the toolbar by editing the source code for SwingViewBuilder.
Here is a link to the code: http://sventon.icesoft.org/svn/repos/repo/show//icepdf/trunk/icepdf/viewer/src/org/icepdf/ri/common/SwingViewBuilder.java?revision=34004
You probably want to comment out lines 481 - 483.
481 JToolBar toolBar = buildCompleteToolBar(embeddableComponent);
482 if (toolBar != null)
483 cp.add(toolBar, BorderLayout.NORTH)
Remove your import for SwingViewBuilder and create your own class with those lines commented out.

Eclipse - Opening editor programmatically causes focus problems

I'm having a bit of an issue with an eclipse plugin that I am working on. In this plugin, a special type of plugin-specific editor is often opened programmatically; this is triggered by various actions in various views/editors, but the code to open the editor is the same. The plugin-specific editors open fine; however, I've recently noticed that every time one of these editors is opened, a strange focus glitch happens:
When the editor is opened, it appears to receive focus, but if the previously active view/editor is clicked immediately after this, it does not take back focus. As soon as anything other than the previously active view/editor is clicked, the problem is instantly solved, and focus resumes normally.
As an example, say you choose a context menu option from the Package Explorer view, which causes an editor to open. The editor opens properly and appears to have focus. After this, you first click again on the Package Explorer, but it doesn't get focus (the editor still appears to have focus). You right-click on Package Explorer, but Package Explorer-specific context menu items do not appear. After this, you click on some other view and then on Package Explorer again. Now Package Explorer gets focus, as normal.
This is the code I'm using to open the editor:
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
final GraphEditorPart gp = (GraphEditorPart) page.openEditor(new NullEditorInput(), "editor.id");
After this, the editor is populated with some visuals, via the albireo SWT-AWT bridge (Not sure if this is relevant to the problem -- the class used for main editor elements is org.eclipse.albireo.core.SwingControl).
I thought perhaps the problem was that the editor wasn't "really" getting focus, or the previously active view wasn't "really" losing focus, so I tried adding the following line:
page.activate(gp);
However this didn't seem to change anything. Why this might happen?
package name:rcp_demo.Editor
class name: EmpCommand.java, EmployeeEditor.java and EmployeeEditorInput.java
package rcp_demo.Editor;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
public class EmpCommand extends AbstractHandler {
public static final String Id = "rcp_demo.Editor.EmpCommand";
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IWorkbenchPage page = window.getActivePage();
IEditorReference[] editors = page.getEditorReferences();
EmployeeEditorInput input = new EmployeeEditorInput();
//All Comments are easily understand
//public class EmployeeEditorInput implements IEditorInput{}
for (int i=0; i<editors.length; i++) {
//List out all Exist editor
//compare with EmployeeEditor.Id="rcp_demo.Editor.emp";
if (editors[i].getId().equals(EmployeeEditor.Id)) {
//public class EmployeeEditor extends EditorPart
//{
// public static final String Id="rcp_demo.Editor.emp";
// public void createPartControl(Composite parent) {.....}
//}
page.activate(editors[i].getEditor(true));
System.out.println("set focus an existing editor(Employee)");
return null;
}
}
try {
//open new Editor like EmployeeEditor.Id="rcp_demo.Editor.emp";
page.openEditor(input,EmployeeEditor.Id);
System.out.println("open Editor(Employee) ");
} catch (PartInitException e) {
e.printStackTrace();
}
return null;
}
}
Full describe this question and answer visit :
Eclipse RCP : have the same editor open in editor window