GLib, is there a reliable way to test icons existence ? (Vala) - glib

Typically, I’m gathering info of steam games, which does create game icons if user asked it. So there might be icons for games available like steam_icon_1524 but not for sure.
How could I test if an icon is available ?

This answer may not hold for steam games, but you said it's not specific to steam, so shrug.
Basically, you just need to call GLib.AppInfo.get_icon. It will return null if there is no icon.
To enumerate installed applications you use GLib.AppInfo.get_all ().
Under the hood, what is happening is that the *.desktop files stored in the applications/ subdirectory of $XDG_DATA_DIRS (fallback if not set: "/usr/local/share/:/usr/share/") and $XDG_HOME_DATA_DIR (fallback if not set: "~/.local/share/") are parsed (see Desktop Entry Specification for details on the file format), and the "Icon" key is used determine the icon name.
Technically, this doesn't quite tell you whether or not the icon actually exists with the current icon theme, only if it is supposed to exist. That's where the Icon Theme Specification comes in. There are several implementations, but since you're using Vala I'll assume you're using GTK+…
You can use Gtk.IconTheme.get_default to get the theme, then Gtk.IconTheme.lookup_by_gicon to get the Gtk.IconInfo (or null if it wasn't found).
Putting it all together, here is a quick program to list all the installed applications and their icons:
private static void main (string[] args) {
Gtk.init (ref args);
unowned Gtk.IconTheme theme = Gtk.IconTheme.get_default ();
foreach (unowned GLib.AppInfo appinfo in GLib.AppInfo.get_all ()) {
GLib.Icon? icon = appinfo.get_icon ();
if (icon != null && icon is GLib.ThemedIcon) {
GLib.message ("%s: %s", appinfo.get_display_name (), icon.to_string ());
Gtk.IconInfo? iconinfo = theme.lookup_by_gicon (icon, 48, 0);
if (iconinfo != null) {
GLib.message (iconinfo.get_filename ());
} else {
GLib.message ("No icon.");
}
}
}
}

Related

Genexus Extensions SDK - Where can I find the avaliable Menu Context strings?

Im trying to use the Genexus Extensions SDK to place buttons on the IDE, in this case, i want to place it in the "context" menu, avaliable only in objects of type "Webpanel/Webcomponent" and "Transaction", Just like WorkWithPlus does here:
So far, digging up into the avaliable documentation, i've noticed that you need tu put the context type string into the xml tag and the GUID of the package that you're aiming to add the menu item, such as below in GeneXusPackage.package:
The Context ID above will add the item into the "Folder View" Context.
My questions:
Where can I find a list with all the possible ID Context strings?
What is that package attribute for, where can i get it's possible values?
I am using the SDK for Genexus 16 U11
I'm sorry to say that there is no extensive list of all the menus available. I'd never thought of it until now, and I see how it could be useful, so we'll definitely consider making it part of the SDK so that any package implementor may use it for reference.
In the meantime, in order to add a new command in the context menu you mentioned, you have to add it to the command group that is listed as part of that menu. That group is KBObjectGrp which is provided by the core shell package whose id is 98121D96-A7D8-468b-9310-B1F468F812AE.
First define your command in your .package file inside a Commands section:
<Commands>
<CommandDefinition id='MyCommand' context='selection'/>
</Commands>
Then add it to the KBObjectGrp mentioned earlier.
<Groups>
<Group refid='KBObjectGrp' package='98121D96-A7D8-468b-9310-B1F468F812AE'>
<Command refid='MyCommand' />
</Group>
</Groups>
Then in order to make your command available only to the objects you said before, you have to code a query handler for the command, that will rule when the command is enabled, disabled, or not visible at all. You can do that in the Initialize method of your package class.
public override void Initialize(IGxServiceProvider services)
{
base.Initialize(services);
CommandKey myCmdKey = new CommandKey(Id, "MyCommand");
AddCommand(myCmdKey, ExecMyCommand, QueryMyCommand);
}
private bool QueryMyCommand(CommandData data, ref CommandStatus status)
{
var selection = KBObjectSelectionHelper.TryGetKBObjectsFrom(data.Context).ToList();
status.Visible(selection.Count > 0 && selection.All(obj => obj.Type == ObjClass.Transaction || obj.Type == ObjClass.WebPanel));
return true;
}
private bool ExecMyCommand(CommandData data)
{
// Your command here
return true;
}
I'm using some helper classes here in order to get the objects from the selection, and then a class named ObjClass which exposes the guid of the most common object types. If you feel something isn't clear enough, don't hesitate to reach out.
Decompiling the Genexus dll and looking for the resource called package, you can infer what the names are.
It's cumbersome but it works

Testing for GVfs metadata support in C

I am trying to add support for per-directory viewing settings to the Thunar file browser of the Xfce desktop. So for example if a user chooses to view the contents of a directory as a list rather than as a grid of icons, this setting is remembered for that directory and will be used whenever that directory is viewed.
Now Thunar is built on GLib, and the mechanism we have chosen to use to implement this is to store metadata using GFile attributes, using methods like g_file_set_attributes_async to store
keys with names such as "metadata::thunar-view-type". The per-directory feature can be turned on or off by the user via a checkbox in a preferences dialog. My knowledge of GIO and GLib is pretty limited, but I have now managed to get this all working as desired (you can see my merge request here if you are interested).
Now as I understand it, the functionality that I am using here relies on something called "GVfs metadata", and as I understand it this might not be available on all systems. On systems where GVfs metadata is not available, I want to turn this functionality off and in particular make the checkbox in the preferences dialog insensitive (i.e. greyed out). Thus I need to write a function to detect if gvfs metadata support is available, by which I mean whether I can use functions like g_file_set_attributes_async to successfully save metadata so that it will be available in future.
Thunar is written in C, so this function needs to be written in C using the C API for GLib, GIO, etc.
The function I have come up with (from much reading of API documentation, modifying code scraps I have found, and experimentation) is as follows.
gboolean
thunar_g_vfs_metadata_is_supported (void)
{
GDBusMessage *send, *reply;
GDBusConnection *conn;
GVariant *v1, *v2;
GError *error = NULL;
const gchar **service_names;
gboolean metadata_found;
/* connect to the session bus */
conn = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
/* check that the connection was opened sucessfully */
if (error != NULL)
{
g_error_free (error);
return FALSE;
}
/* create the message to send to list the available services */
send = g_dbus_message_new_method_call ("org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"ListNames");
/* send the message and wait for the reply */
reply = g_dbus_connection_send_message_with_reply_sync (conn, send, G_DBUS_SEND_MESSAGE_FLAGS_NONE,
-1, NULL, NULL, &error);
/* release the connection and the sent message */
g_object_unref (send);
g_object_unref (conn);
/* check if we got a sucessful reply */
if (error != NULL)
{
g_error_free (error);
return FALSE;
}
/* extract the GVariant with the array of strings describing the available services */
v1 = g_dbus_message_get_body (reply); /* v1 belongs to reply and must not be freed */
if (v1 == NULL || !g_variant_is_container (v1) || g_variant_n_children (v1) < 1)
{
g_object_unref (reply);
return FALSE;
}
v2 = g_variant_get_child_value (v1, 0);
g_object_unref (reply);
/* check that the GVariant we have been given does contain an array of strings */
if (!g_variant_is_of_type (v2, G_VARIANT_TYPE_STRING_ARRAY))
{
g_variant_unref (v2);
return FALSE;
}
/* search through the list of service names to see if gvfs metadata is present */
metadata_found = FALSE;
service_names = g_variant_get_strv (v2, NULL);
for (int i=0; service_names[i] != NULL; i++)
if (g_strcmp0 (service_names[i], "org.gtk.vfs.Metadata") == 0)
metadata_found = TRUE;
g_free (service_names);
g_variant_unref (v2);
return metadata_found;
}
As you can see, this function uses DBus to query service names to see if the necessary service is available. Now, as far as I have been able to test it, this function works as I want it to. However, during a code review it has been questioned whether this can be done without relying on DBus (which might itself not be available even though GVfs metadata is).
Thus (at last!) my question: what is the best (i.e. most robust and accurate) way to test for GVfs metadata support via the C API for GLib, GIO, etc?. As I said above, by "GVfs metadata support" I mean "can I use functions like g_file_set_attributes_async to successfully save metadata so that it will be available in future?".
One method I have considered is looking at the list of running processes for the name "gvfsd-metadata", but that seems a bit kludgy to me.
Also, as mentioned above I am very much a novice with these technologies, so I is absolutely possible that I have misunderstood stuff here, so if you spot any errors in the assertions I have made above, please let me know.
Thanks!
(And yes, usual story, I'm a long time reader of SO & co, but a first time asker, so please feel free to edit or let me know if I've done something wrong/bad)
Call g_file_query_settable_attributes() and g_file_query_writable_namespaces() on the GFile, as described in the GFileInfo documentation:
However, not all attributes can be changed in the file. For instance, the actual size of a file cannot be changed via g_file_info_set_size(). You may call g_file_query_settable_attributes() and g_file_query_writable_namespaces() to discover the settable attributes of a particular file at runtime.

Xamarin & Multiple Filepicker

i'm building a project on Xamarin. Right now i have a big issue. I need to browse user's computer for upload any file. He can of course upload multiple files. As i know Xamarin does not provide browsing of all the system but just its. So i tried to find a way with some drag n drop, i didn't find. I tried a filepicker but he let me pick just one file (my client would upload 100 files at once) so it doesn't fit to what i need. Finally i decided to do my own browsing system but it takes forever to browse because of the UI. Do you have any solution for me ? I would appreciate a package with a filepicker that allow multiple files.
Thanks
Have you tried the class FileOpenPicker in UWP ?
It supports to pick multiple files , check the method FileOpenPicker.PickMultipleFilesAsync.
Sample
Define interface in Forms project
public interface MyFilePicker
{
Task OpenFilePickerAsync();
}
Implement in UWP project
[assembly: Dependency(typeof(UWPFilePicker))]
namespace App24.UWP
{
class UWPFilePicker : MyFilePicker
{
public async Task OpenFilePickerAsync()
{
var openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
IReadOnlyList<StorageFile> files = await openPicker.PickMultipleFilesAsync();
if (files.Count > 0)
{
StringBuilder output = new StringBuilder("Picked files:\n");
// Application now has read/write access to the picked file(s)
}
else
{
return;
}
}
}
}
Call it in Forms project
private async void Button_Clicked(object sender, EventArgs e)
{
MyFilePicker service = DependencyService.Get<MyFilePicker>();
await service.OpenFilePickerAsync();
}

Can I auto-increment the CFBundleVersion value in the Info.plist file using Visual Studio?

I've seen solutions to doing this with Xcode and even Xamarin Studio, but nothing with Visual Studio.
Ideally, I'd like for every single build of the project to auto-increment the CFBundleVersion value within the Info.plist file.
<key>CFBundleVersion</key>
<string>9</string>
I don't even know where to start and haven't been able to find an article / blog post / tutorial on anything that includes Visual Studio.
Is this possible?
Just wanted to add that I am using Visual Studio 2015 on Windows 8.1.
Being in the same boat as you, as in not finding a proper solution, I decided to create my own. Maybe better late than never! :)
In my case I used the very useful Automatic Versions Settings tool (available on NuGet) to automatically update my assembly info, but wanted that to also update the Info.plist information as that's what HockeyApp uses to track and notify of new releases.
In the end, I kludged together a minimal C# program, which reads AssemblyInfo.cs, grabs the version info from there and edits the Info.plist XML file and writes it back.
It'd be a 20 line program if I hadn't put in a lot of paranoid checks, so as not to risk mangling Info.plist irretrievably (and even then it creates a backup of that file).
The "magic" comes down to two methods, the first one which I found here on SO:
Read AssemblyInfo.cs:
private static string GetVersionFromAssemblyInfo(string infile)
{
var version = String.Empty;
var readText = File.ReadAllLines(infile);
var versionInfoLines = readText.Where(t => t.Contains("[assembly: AssemblyVersion"));
foreach (var item in versionInfoLines)
{
version = item.Substring(item.IndexOf('(') + 2, item.LastIndexOf(')') - item.IndexOf('(') - 3);
}
return version;
}
Edit Info.plist, where the first 3 elements of the assembly info tuple becomes the CFBundleShortVersionString and the last element becomes CFBundleVersion which HockeyApp uses for build number.
The wonkiness in the LINQ is due to the slight weirdness of Apple's way of presenting the key/value pairs in that file:
private static bool SetVersionInInfoPlist(string infoplistFile, string version, string number)
{
var xelements = XDocument.Load(infoplistFile);
var dict = from el in xelements.Root?.Elements() select el;
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (dict == null) return false;
var cfshortversion =
from el in dict.Descendants("key")
where el.Value == "CFBundleShortVersionString"
select el.ElementsAfterSelf().FirstOrDefault();
;
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (cfshortversion == null) return false;
cfshortversion.FirstOrDefault()?.SetValue(version);
var cfversion =
from el in dict.Descendants("key")
where el.Value == "CFBundleVersion"
select el.ElementsAfterSelf().FirstOrDefault();
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (cfversion == null) return false;
cfversion.FirstOrDefault()?.SetValue(number);
// Make backup
try
{
File.Copy(infoplistFile, $"{infoplistFile}-backup", true);
}
catch (Exception)
{
Console.WriteLine($"Failed to create backup of {infoplistFile}. Will not edit.");
return false;
}
try
{
using (StringWriter sw = new StringWriter())
{
using (XmlWriter xWrite = XmlWriter.Create(sw))
{
xelements.Save(xWrite);
}
}
xelements.Save(infoplistFile);
}
catch (Exception)
{
Console.WriteLine($"Failed to save the edited {infoplistFile}.");
return false;
}
Console.WriteLine($"Successfully edited and saved new {infoplistFile}.");
return true;
}
EDIT: I should have also added that I use Bamboo for CI and build automation. This program therefore becomes a capability for the remote build agent and then I can add it as a Task in the Bamboo build Plan.

Vaadin : How to change favicon?

How can I change favicon of my pages in Vaadin ? I would like to change favicon of my pages but I have no idea where is the place to change it ? Has somebody experience on it ?
First, create a theme directory: /WebContent/VAADIN/themes/mynewtheme
Then, put your custom favicon.ico in this directory. You also need to set theme property in your application :
public class MyNewApplication extends Application {
#Override
public void init() {
...
...
setTheme("mynewtheme");
}
}
Here is a more detailed version of the similar Answer posted by Greg Ballot. My Answer here relates to Vaadin 7, current as of 7.5.3.
Custom Theme
In Vaadin 7.5, you can drop your favicon graphics image file into your own custom theme. If using the Vaadin plugin for various IDEs (NetBeans, Eclipse) or the Maven archetypes, a custom theme named mytheme should have already been created for you. Drop your image file into that mytheme folder.
The main part of your Vaadin 7 app, your subclass of UI, must specify that it uses your custom theme. Again, if using the IDE plugins and/or Maven archetype, this should have already been configured for you. The easiest way is an Java Annotation on the UI subclass.
#Theme ( "mytheme" ) // Tell Vaadin to apply your custom theme, usually a subclass of the Valo or Reindeer theme.
#Title ( "PowerWrangler" ) // Statically specify the title to appear in web browser window/tab.
#SuppressWarnings ( "serial" ) // If not serializing such as "sticky sessions" and such, disable compiler warnings about serialization.
#Push ( PushMode.AUTOMATIC ) // If using Push technology.
public class MyVaadinUI extends UI
{
…
Favicon Usage/Behavior Not Standard
Remember that favicon behavior is not standardized. Favicons developed haphazardly, mostly out of a sense of fun. The exact behavior depends on the particular browser and particular server. Other than the particular folder location, none of this is special to Vaadin.
Image File Formats
Originally the ICO file format was used exclusively. Since then most browsers have evolved to accept any of several formats including JPEG, TIFF, and PNG.
Image Size/Resolution
Originally favicons were intended to be very small bitmap icons. Some browsers have made various uses of the favicon in situations where you may want to provide a higher-resolution image. But remember that smaller files load faster without keeping your users waiting.
Favicon File Name
Some browsers or servers may handle other file names or name extensions, but I've found it easiest to name my file exactly favicon.ico -- even if using a different format! I usually use a PNG file but name it with the .ico extension. While I cannot guarantee this practice works one every server and browser, I’ve not encountered any problem.
Existing Favicon File
Recent versions of Vaadin have included a Vaadin-related icon in a favicon.ico file in a configured project. So you must replace that file with your own. In Vaadin 7.5.3 the file contains four sizes, the largest looking like this:
Older versions did not add a file, so you drop in your own.
IDE Screen Shots
Here are a pair of screen shots. One is the project (logical) view in NetBeans 8, while the other is a files (physical) view.
In case of custom icon name (Vaadin 7):
public class MyServlet extends VaadinServlet implements SessionInitListener {
#Override
protected void servletInitialized() throws ServletException {
super.servletInitialized();
getService().addSessionInitListener(this);
}
#Override
public void sessionInit(SessionInitEvent event) throws ServiceException {
event.getSession().addBootstrapListener(new BootstrapListener() {
#Override
public void modifyBootstrapPage(BootstrapPageResponse response) {
response.getDocument().head()
.getElementsByAttributeValue("rel", "shortcut icon")
.attr("href", "./VAADIN/themes/mynewtheme/custom.ico");
response.getDocument().head()
.getElementsByAttributeValue("rel", "icon")
.attr("href", "./VAADIN/themes/mynewtheme/custom.ico");
}
#Override
public void modifyBootstrapFragment(BootstrapFragmentResponse response) {
}
});
}
}
EDIT
It is better to use the BootstrapListener as a static nested class: link
Vaadin 23.x (plain spring/war application, no springboot!):
Derive an implementation of com.vaadin.flow.component.page.AppShellConfigurator:
#Theme(value = "mytheme")
#PWA(name = "My application", shortName = "MyApp", iconPath = "icons/favicon.ico" )
public class AppShellConfiguratiorImpl implements AppShellConfigurator {
#Override
public void configurePage(AppShellSettings settings) {
settings.addFavIcon("icon", "icons/favicon.ico", "16x16");
}
}
And put your favicon.ico into src\main\webapp\icons (in order that it is encluded in <war-root>/icons/favicon.ico)
A servlet container (3.0 plus, e.g. Tomcat 8.5) will pick up this class automagically and load it.

Resources