Friday, June 5, 2020

Executing a Method on the Main Thread With C#/.NET

Copyright © 2020, Steven E. Houchin. All rights reserved.

I recently updated some C# code to use the async/await feature to offload some processing to a background thread.  Mine is a WPF GUI application using .NET Framework 4.6.1.

A problem I immediately ran into was this: my background thread calls back into the UI to show status updates. But, when that call was made to show a line of status text, the app caused an unhandled exception (System.InvalidOperationException). I realized immediately what the problem was, having dealt with it many times in other multithreaded applications.  You cannot update user interface controls from secondary threads.  I knew the answer for C++ wxWidgets applications, but had to figure out what to do for C# and WPF.

I, of course, did a lot of digging online and got sidetracked with likely-looking solutions, which then turned out to be for WinForms applications.  Ultimately, I found that the answer lies with the System.Windows.Threading.Dispatcher class.  The documentation states it "Provides services for managing the queue of work items for a thread."  Sounds like just what I needed.

In my method that outputs the status line of text, it appends the new text to a TextBlock control. Before doing that, though, the method now needed to check whether it was running in a background thread, or the primary thread of the UI.  Here is the new method I wrote to determine this:

/// <summary>
/// Determine if current thread is secondary or primary (which
/// is determined from this object's dispatcher)
/// </summary>
protected bool IsBackgroundThread()
{
    return (this.Dispatcher != Dispatcher.CurrentDispatcher);
}

This IsBackgroundThread method is implemented in the main window class derived from System.Windows.Window, so is a class created with the application primary thread's dispatcher.  Thus, "this.Dispatcher" returns that primary thread Dispatcher object.  The static property "Dispatcher.CurrentDispatcher" returns the Dispatcher object for the currently running thread.  So, comparing the two thus determines background versus primary thread.

Now that I had the ability to determine the thread context, I could use it when updating the UI control with the new status text.  I did this in an AppendOutput method.

/// <summary>
/// Append the given text string to the control that shows
/// operation results.
/// </summary>
/// <param name="text" />The new text to append.
protected void AppendOutput(string text)
{
    if (IsBackgroundThread())
    {
        // Method was called from secondary thread, so dispatch
        // again to the primary thread using it's dispatcher
        this.Dispatcher.Invoke(() => AppendOutput(text),
                                DispatcherPriority.Normal);
    }
    else
    {
        // Method was called from primary thread, so do the work here
        textBlockResult.Text = textBlockResult.Text + "\n" + text;
    }
}

The above is a generalized way to determine the primary thread on a particular window, but the control on that window can be queried, too. In this simpler method, the code merely calls the DispatcherObject.CheckAccess method, as follows:

if (!textBlockResult.CheckAccess())
{
    this.Dispatcher.Invoke(() => AppendOutput(text),
                                DispatcherPriority.Normal);
}

When executing in the primary thread, the given text string is simply appended to the TextBlock control's current text value as a new line. When running in a background thread, the primary thread's Dispatcher is called to invoke the given Action, which is in the form of a Lambda expression that simply recursively calls the same method, but now in the primary thread's context.

Note that the Invoke method is of the form Invoke(Action, DispatcherPriority), where the first argument implicitly creates an Action delegate object for the method call. The documentation states, for Invoke, "Executes the specified Action synchronously at the specified priority on the thread the Dispatcher is associated with."  They key here is this is a synchronous call in a different thread context.

And that's it. With this change, all the status messages from the background thread show up just fine in the TextBlock control.






Tuesday, April 21, 2020

JavaFX desktop application on macOS - Part III

Copyright © 2020, Steven E. Houchin. All rights reserved.

This is the third and final post in this series, which deals with installing a JavaFX desktop application on macOS, when it was developed on a Windows system.  In my first post on this subject, I left two issues unresolved, the first of which I discussed in the second post.

Here, I discuss the second lingering issue left over from that first post, namely that the application's title in the macOS system menu bar shows as simply "java," instead of my application's title, "MapApp." This happens when I merely double click on the app's JAR file to run it.

To solve the problem, I had to create an installation package on the Mac, then run that package so the app is properly placed in the Mac's Applications folder, thus appearing like any other Mac application.


Build Steps on Windows


The key to making all that happen starts back on my Windows machine, and my build steps in NetBeans.  Since my app is made up of an application JAR, a library JAR, and some support files (like image files), I needed to integrate them together in a single JAR for the Mac.

  1.  I included the support files in my NetBeans Java package, along with the java source files for the application. That bundles those support files as Java package resources, instead of separate files on the disk.
  2.  I modified the application package's 'build.xml' file to add a new Run Target named "package-for-store."  It is intended to run after all the sources are compiled into their JARs. I show that new target script below.
  3.  Once the sources were built into JARs, I used NetBeans to execute the new Run Target. This is done by …
    1. Open a Files window on NetBeans
    2. Right-click the application's 'build.xml' file
    3. Select Run Target
    4. Select Other Targets
    5. Select the target "package-for-store," which runs the packaging script
  4. Once the packaging script runs, the resulting application JAR file is found in the folder 'store', which is a peer to the project's 'dist' folder. This is the JAR file that contains everything, including libraries, that can then be copied over to the Mac. The script must be run manually anytime the application is changed.
So, what is in this packaging script that I added to the 'build.xml' that performs this magic?  It is a custom "target" I added, and it looks like this:

<target name="package-for-store" depends="jar">
 <property name="store.jar.name" value="MapApp"/>
 <property name="store.dir" value="store"/>
 <property name="store.jar" value="${store.dir}/${store.jar.name}.jar"/>
 <echo message="Packaging ${application.title}
 into a single JAR at ${store.jar}"/>
 <delete dir="${store.dir}"/>
 <mkdir dir="${store.dir}"/>
 <jar destfile="${store.dir}/temp_final.jar" filesetmanifest="skip">
  <zipgroupfileset dir="dist" includes="*.jar"/>
  <zipgroupfileset dir="dist/lib" includes="*.jar"/>
  <manifest>
   <attribute name="Main-Class" value="mapapp.MapApp"/>
  </manifest>
 </jar>

 <zip destfile="${store.jar}">
  <zipfileset src="${store.dir}/temp_final.jar"
  excludes="META-INF/*.SF, META-INF/*.DSA, META-INF/*.RSA"/>
 </zip>
 <delete file="${store.dir}/temp_final.jar"/>
</target>


Here are key items to note in the target script above.  The properties at the top specify the application name, the 'store' folder, and the jar file to create in the 'store' folder.  The "message" displays in NetBeans when the script is run. The 'store' folder is deleted and remade anew. A temporary JAR is created, which includes all JARs in the 'dist' folder and in the 'dist/lib' folder. The application's main startup class is specified by package name (mapapp) and class name (MapApp) in the "Main-Class" attribute. The finalized MapApp.jar is created from the temp JAR, and the temp is deleted.

When the script is done, "store/MapApp.jar" should exist, ready to be copied to the Mac.

Packaging Steps on Mac


So, I must copy the final JAR from above over to the Mac so it can be made into a macOS .pkg file.

On the Mac, I created a working folder 'MapApp/packaging' under my Documents. In it, I placed the JAR, and a .css file I need in the package. Under the 'packaging' folder, I also created a 'package/macosx' folder. As part of the process, the macOS java packaging utility looks for certain files there (all optional), which it uses to customize the package. The files are:

  • Info.plist - this is a standard macOS bundle configuration file for setting application properties, such as version number and copyright string.
  • MapApp-background.png - this is an image that displays at the lower left of the installation window when the package executed.
  • MapApp.icns - the application's custom icon file.
  • MapApp-post-image.sh - a script to run after the application image is populated.
Here is a shell script file I created to automate all of this to conveniently create the package (.pkg) file, which I run from a Bash terminal window:



#/bin/bash
#
# Create a .pkg file for the java MapApp app
#
jdk="/Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home"

# Run the packager utlity
$jdk/bin/javapackager -version
$jdk/bin/javapackager -deploy -native pkg -name MapApp
-Bappversion=1.0.0 -srcdir . -srcfiles MapApp.jar:mapapp.css
-appclass mapapp.MapApp -outdir out -outfile MapApp
-description "MapApp description"
-title "MapApp Title"
-vendor "Company Name" -v

# Copy the new package
rm -f ./mapapp-installer.pkg
cp out/bundles/MapApp-*.pkg ./mapapp-installer.pkg

# List the results
ls -l


The key here is the "javapackager" utility, which is part of the installed JDK on my system.  The input sources to this are the MapApp.jar and mapapp.css files, as seen in the -srcfiles option.

The result is the file 'mapapp-installer.pkg' in my 'packaging' folder.  When I execute this, it installs my MapApp application in the usual macOS Applications folder, like any other application.

So, after all this, I've accomplished two things: a standard application installation and, when it executes, the title "MapApp" shows properly in the system menu bar.




Monday, March 9, 2020

JavaFX desktop application on macOS - Part II

Copyright © 2020, Steven E. Houchin. All rights reserved.

In Part I of this topic, I showed snippets of Java code that help your JavaFX desktop application run correctly on macOS, even when you've developed and built it on a Windows system, as I have. I left off last time with two unfinished issues for my MapApp program. They occur on macOS when simply executing the application's JAR file by opening it directly, such as double-clicking it:

  1. The application's title in the system menu bar is "java," instead of "MapApp."
  2. The application's dock icon is the standard Java coffee cup image.

The first I will defer to my next post. The second is discussed here.

Setting the Dock Icon


Setting the program icon using "stage.getIcons().add()" in the Java code works fine to set a title bar icon, but doesn't affect the Dock icon. The Dock icon requires calls to a special package from Apple, named "com.apple.eawt", which should exist on your macOS system, but isn't available for development on Windows. Unfortunately, Apple's documentation of this package has gone extinct, or is buried somewhere far, far away. The best docs I have found for it are at:

  https://coderanch.com/how-to/javadoc/appledoc/api/com/apple/eawt/Application.html

In that package is an Application class that contains methods to do interesting Mac-only things, like to set the Dock icon. So, here's the code I used, which requires using Java Reflection since the package is not available on Windows for linking.

First, you must obtain the package's Application class:

    Class<?> applicationClass;
    try
    {
        // get the eawt Application class
        applicationClass = Class.forName(
               "com.apple.eawt.Application");
    }
    catch (ClassNotFoundException ex)
    {
        Alert alert = new Alert(
                Alert.AlertType.ERROR, ex.toString());
        alert.showAndWait();
        return false;
    }

Second, load the icon image you wish to use, which in my case is a 48x48 JPEG embedded in the JAR as a resource. You could also load the icon from a file installed separately with the JAR. The embedding of the image file is accomplished on NetBeans by simply including the JPEG file in the project sources folder.

    // get the dock icon from the jar's embedded resources
    java.awt.image.BufferedImage image =
        ImageIO.read(getClass().getResourceAsStream("MyApp-48.jpg"));

Next, use the Application class (obtained above) to call methods that set the icon, using Reflection:

    try
    {
        // use reflection to access the
        // com.apple.eawt.Application methods
  
        // com.apple.eawt getApplication()
        // factory method to get an instance of
        // com.apple.eawt.Application
        Method getApplicationMethod =
            applicationClass.getMethod("getApplication");
  
        // com.apple.eawt Application.setDockIconImage()
        // Application class instance method to
        // set the Dock icon
        Method setDockIconMethod = applicationClass.getMethod(
                                     "setDockIconImage",
                                     java.awt.Image.class);

        // get an instance of the Appication class
        Object macOSXApplication =
            getApplicationMethod.invoke(null);
  
        // set the image as the dock icon
        setDockIconMethod.invoke(macOSXApplication, image);
    }
    catch (NoSuchMethodException
            | IllegalAccessException
            | IllegalArgumentException
            | InvocationTargetException ex)
    {
        Alert alert = new Alert(
                Alert.AlertType.ERROR, ex.toString());
        alert.showAndWait();
        return false;
    }

My application calls this code right away in the application class's "start(Stage stage)" method. When you run the application, you will see the standard Java coffee cup Dock icon at first, then your application's icon will load and take its place.

Note that all of the above will become moot if you create a package for your application on the Mac, where you can specify your own Mac icon file (.icns) and other things to customize its installation in the Applications folder. More fodder for subsequent posts!

Tuesday, March 3, 2020

JavaFX desktop application on macOS - Part I

Copyright © 2020, Steven E. Houchin. All rights reserved.

This posting is first in a series, whose purpose is to show what is necessary to get a JavaFX desktop application to work reasonably on macOS.

Environment


In my case, I am running macOS High Sierra (10.13.6) with Java 8 (version 1.8.0_231). My development environment is Windows 10, Java 8 (version 1.8.0_241), NetBeans 8.2 and JavaFX Scene Builder 2.0.

The Application


Mine is a desktop application that loads map images and allows for smart panning, zooming, and custom annotations. It is intended to run on Windows and macOS, and thus I chose Java as the language, and JavaFX for the User Interface components.

Code Unique for macOS


In several places in the code, it was necessary to recognize macOS differences. In many cases, to do this, I had to know it was running on macOS, and not Windows. Here's the method I used to do this, which takes advantage of the built-in system properties Java provides:

/**
 * Return true if the running OS is Mac OS,
 * otherwise Windows is assumed.
 *
 * @return - True if Mac OS, else assume Windows.
 */
public static boolean isMacOS()
{
    String os = System.getProperty("os.name");
    return os.startsWith("Mac") || os.startsWith("mac");
}

Also, I had to make sure file paths use the proper path separator character for the OS:
// get fully qualified path to the map file
String fullFilePath = myRootFolderPath +
                 File.separator + "mymap.jpg";
Then there is the application's menu bar. By default, when it runs on macOS, the menus appear atop the application's main window, just like on Windows. But, of course, that isn't what we want on the Mac; it should appear on the standard Mac menu bar at the top of the screen. Here's the trick to make that happen:
@FXML
private MenuBar menuBar;
if (isMacOS())
{
    // place the program menus on the standard
    // macOS menu bar
    menuBar.setUseSystemMenuBar(true);
}
Two more useful snippets of code that help get things right on the Mac.

First, how to find the user's home directory.

/**
 * Get the user's home directory path, appending the
 * system path separator to it.
 *
 * @return - The full path to the user home directory
 *    (ending in a path separator), or null if error
 */
public static String getUserHomeFolderPath()
{
    // get the user home directory from a standard
    // environment variable
    String folder = isMacOS() ? System.getenv("HOME") :
                                System.getenv("HOMEPATH");
    if (null != folder)
    {
        folder += File.separator;
    }
    return folder;
}

Second, how to get the name of the user's Documents folder.


/**
 * Get the user's Documents folder name.
 *
 * @return The folder name for Documents on this OS.
 */
public static String getDocumentsFolderName()
{
    if (!isMacOS())
    {
        String os = System.getProperty("os.version");
        double version = Double.parseDouble(os);
        if (version < 7.0)
        {
            // name of Documents folder for Windows 2000
            // and XP
            return "My Documents";
        }
    }
    // name of Documents folder for macOS and
    // Windows 7.0+
    return "Documents";
}

Installing the Application to Test


My application links with a library, which I also developed, which does the heavy lifting for drawing and manipulating the map. When I copy the application JAR (MapApp.jar) to my test folder on the Mac, my maps library JAR (MapLib.jar) must be placed in a "lib" subfolder below the test folder. At this point, I can execute the app on the Mac by double-clicking MapApp.jar, and it starts up. But, two things show up that aren't yet right:
  1. The application's title in the system menu bar is "java," instead of "MapApp."
  2. The application's dock icon is the standard Java coffee cup image.
I will discuss solving these problems and others in a future post.

Thursday, January 16, 2020

Opening an About dialog box with JavaFX

Copyright © 2020, Steven E. Houchin. All rights reserved.

I was recently putting the finishing touches on a demo desktop application written in Java 8 using JavaFX. The UI consists of a single FXML file attached to a controller class. My next task was to add a nice looking About box - something better than an Alert.  So, I created an About.fxml using JavaFX Scene Builder 2.0.  I wanted to attach the About.fxml to the same application controller class I already had, so the About's OK button would dispatch its event there.  That, apparently, was a mistake that caused much grief, because loading the About.fxml kept giving me a non-specific LoadException error.  Postings at online help sites didn't seem to match my situation. Most of them dealt with file path problems to the user's FXML file, resulting in a NullPointerException, but my FXML is embedded within my application JAR file.

I eventually came to the conclusion that the FXMLLoader did not like loading a second FXML specifying the same controller class as my main FXML. So, how to load my About.fxml to get the result I wanted - its use of the same controller class?

Okay, here's what I did.  First, I removed any reference to a controller in About.fxml.  That meant I had to specify the controller some other way.  Here's my code in the controller class handler for the About menu event:


// load the About box FXML document
javafx.fxml.FXMLLoader loader = new javafx.fxml.FXMLLoader(
                    MyMainApp.class.getResource("About.fxml"));
loader.setController(this); // set 'this' as its controller
Parent root = loader.load(); // load UI objects from the FXML document

It turns out the magic I needed was the "setController" method above.  Specifying the controller class in the FXML file tries to create a new instance of the controller class, I assume, which must be the origin of my earlier LoadException error.  So, without that, the above loads fine.

Once the UI was loaded into a root Parent object (above), then it was time to configure the About dialog just the way I wanted: modal, no extra window decorations (i.e. Utility), owned by the main window, always on top, and not resizable ...

// create the dialog stage and set up its attributes
javafx.stage.Window owner = MyMainApp.getStage().getScene().getWindow();
Stage dialog = new Stage();
dialog.initStyle(StageStyle.UTILITY);
dialog.initModality(Modality.WINDOW_MODAL);
dialog.initOwner(owner);
dialog.setAlwaysOnTop(true);
dialog.setTitle("About MyMainApp");
dialog.setResizable(false);

Lastly, it was time to show the dialog:

// create the scene and set onto the stage
Scene scene = new Scene(root);
dialog.setScene(scene);
dialog.sizeToScene();
dialog.showAndWait();

At that point, my nice About box with a title and the system close button pops up!  The underlying main window cannot gain focus.  When I press the About's 'OK' button, I then get its event callback in my same controller class, which then closes the About box:

@FXML
public void onButtonHelpAboutDismissAction(ActionEvent event)
{
    Stage stage = (Stage)buttonHelpAboutDismiss.getScene().getWindow();
    stage.close();
}

Now, I'm sure there's a stupidly simpler way to do this in JavaFX, but I didn't see any other online examples for an About box like this. So, this is my contribution, as a relative Java newbie.

Any comments?

Friday, June 22, 2018

Finding the default application for a file extension in WIndows

Copyright © 2018, Steven E. Houchin. All rights reserved.

A client of mine has a Windows application that lists various data files, and when a data file is clicked, opens the associated application for the file's extension, using an established API to do that.  It has worked fine for a long time, but gives unexpected results on Windows 10 for html files. The default program for html on the system is configured for MS Edge, but a click on the html file in the application always brought up Internet Explorer.

Sure enough, following the traditional file association scheme in the Registry showed IE, not Edge.  The traditional scheme is:

HKEY_CLASSES_ROOT\.html
    (Default) = program_identifier
HKEY_CLASSES_ROOT\program_identifier\shell\open\command
    (Default) = full path to default program

By doing more research, I discovered that M*Soft changed the file association scheme starting, I think, with Vista.  The old scheme may still work for some file types, but finding the right browser requires using the new scheme.

The new post-Vista scheme I found requires looking into file associations for Window Explorer and following from there.

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\
  FileExts\.html\UserChoice
    ProgId = program_identifier
HKEY_CLASSES_ROOT\program_identifier\shell\open\command
    (Default) = full path to default program

In the new scheme, for MS Edge, the ProgId value could be something strange like "AppXq0fevzme2pys62n3e0fbqa7peapykr8v", whereas the Firefox browser may be "FirefoxURL". The obvious advantage of this new scheme is that using HKEY_CURRENT_USER allows for user-by-user default program setting, where, I think, the traditional scheme sets it for all users.

So, by writing my own Registry traverser for the new scheme, I finally got MS Edge to open as the default browser. If the new scheme fails to find the default program, my code falls back to the traditional scheme shown before.



Friday, September 22, 2017

Making a Modal Dialog with C# and WPF

Copyright © 2017, Steven E. Houchin. All rights reserved.

For a unit test program I'm developing to validate a new library API, I created a window to show some attributes of an object. I wanted that window to display as follows:

  • normal modal dialog
  • centered on parent window
  • not shown in taskbar
  • can be resized
  • can be minimized

I'm using .NET Framework 4, C# and WPF on a Windows 10 system.

Here are some observations about how to properly set up a dialog as I describe above.

First, to show as a modal dialog, I call the Window class's ShowDialog method to open and show the dialog from the parent Window class:


    // Create the Detail View Controller object
    IDetailViewControl view_controller =
            app.MakeDetailViewController();

    // Create the Detail View Object, passing in this
    // Window class as a parent
    MyDetailView detail =
            new MyDetailView(myDataObject, view_controller, this);
                
    // Show the Detail dialog
    detail.ShowDialog();

Second, to center the dialog on its parent window, the MyDetailView dialog class's constructor sets its Owner property to the Window object passed by the caller:


    public partial class MyDetailView : Window
    {
        public MyDetailView (MyData dataObject,
                             IDetailViewControl controller,
                             Window owner)
        {
            this.Owner = owner;   // set parent window as owner
            InitializeComponent();

            // other constructor initialization
        }
    }



Note that, in the above code, the parent Window code could have set itself as Owner using the 'detail' object before calling ShowDialog, but I chose to have the dialog take care of that. Finally, to complete a centered dialog when open, the dialog Window's XAML properties must specify:

    WindowStartupLocation="CenterOwner"

Third, I set the dialog Window's XAML property to not show in the taskbar:

    ShowInTaskbar="False"

Set to False, it means this dialog will not show in the taskbar, but Restoring the parent window from the taskbar brings the MyDetailView dialog to the top with it.

Lastly, I set the dialog Window's XAML property so it can be resized and minimized:

    ResizeMode="CanResize"

The ResizeMode setting can instead be set to CanMinimize if resizing isn't desired. The CanResize value implies CanMinimize, since minimizing and maximizing is assumed to be part of any resize operation.

So, with the WPF Window implemented this way, it acts like a classic modal dialog we're all accustomed to.