Bejegyzések relevancia szerint rendezve a(z) "script" lekérdezésre. Rendezés dátum szerint Az összes bejegyzés megjelenítése
Bejegyzések relevancia szerint rendezve a(z) "script" lekérdezésre. Rendezés dátum szerint Az összes bejegyzés megjelenítése

2015. január 25.

Nautilus scripting in bash: processing multiple files / handle space in filenames

Where do I put the scripts? 

Nautilus scripts folder is in your user home directory:
in Ubuntu 12.04 and before: .gnome2/nautilus-scripts/
from Ubuntu 14.04: .local/share/nautilus/scripts/

You'll have to make all script files executable in order to be able to run them.
chmod +x

What does a nautilus script do? 

All executable files in this folder will appear in the Scripts menu. Choosing a script from the menu will run that script.

When executed from a local folder, scripts will be passed the selected file names. When executed from a remote folder (e.g. a folder showing web or ftp content), scripts will be passed no parameters.

What nautilus script specific variables can I use?

In all cases, the following environment variables will be set by Nautilus, which the scripts may use:

  • NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
    # newline-delimited paths for selected files (only if local)
  • NAUTILUS_SCRIPT_SELECTED_URIS
    # newline-delimited URIs for selected files
  • NAUTILUS_SCRIPT_CURRENT_URI
    # URI for current location
  • NAUTILUS_SCRIPT_WINDOW_GEOMETRY
    # position and size of current window
# from Ubuntu 14.04 Nautilus does not have split view (extra pane), so these variables (most likely) will not work:
  • NAUTILUS_SCRIPT_NEXT_PANE_SELECTED_FILE_PATHS
    # newline-delimited paths for selected files in the inactive pane of a split-view window (only if local)
  • NAUTILUS_SCRIPT_NEXT_PANE_SELECTED_URIS
    # newline-delimited URIs for selected files in the inactive pane of a split-view window
  • NAUTILUS_SCRIPT_NEXT_PANE_CURRENT_URI
    # URI for current location in the inactive pane of a split-view window
How do these variables work? 

To test what these variables do you might use this nautilus script:
#!/bin/bash
# test your nautilus variables
touch $HOME/nautilustesting.txt
echo "SELECTED_FILE_PATHS: " "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" >> $HOME/nautilustesting.txt
echo "SELECTED_URIS: " "$NAUTILUS_SCRIPT_SELECTED_URIS"  >> $HOME/nautilustesting.txt
echo "CURRENT_URI: " "$NAUTILUS_SCRIPT_CURRENT_URI" >> $HOME/nautilustesting.txt
echo "WINDOW_GEOMETRY: " "$NAUTILUS_SCRIPT_WINDOW_GEOMETRY" >> $HOME/nautilustesting.txt
echo " " >> $HOME/nautilustesting.txt

How to use these variables?

The variables you get will look something like this (in case of selecting 4 files with spaces in the names):
SELECTED_FILE_PATHS:  /home/username/.gnome2/nautilus-scripts/Screen rotate/Set screen inverted
/home/username/.gnome2/nautilus-scripts/Screen rotate/Set screen left
/home/username/.gnome2/nautilus-scripts/Screen rotate/Set screen normal
/home/username/.gnome2/nautilus-scripts/Screen rotate/Set screen right (notes)
SELECTED_URIS:  file:///home/username/.gnome2/nautilus-scripts/Screen%20rotate/Set%20screen%20inverted
file:///home/username/.gnome2/nautilus-scripts/Screen%20rotate/Set%20screen%20left
file:///home/username/.gnome2/nautilus-scripts/Screen%20rotate/Set%20screen%20normal
file:///home/username/.gnome2/nautilus-scripts/Screen%20rotate/Set%20screen%20right%20(notes)
CURRENT_URI:  file:///home/username/.gnome2/nautilus-scripts
WINDOW_GEOMETRY:  1022x690+0+1024

How to read nautilus selected file paths with spaces into a bash array?

To have a use of them as input file path for example imagemagick, I'll have to deal with the spaces, because these command line programs usually take "file path" as input and do not take "file URI" as input, and file path may contain spaces.

The FAQ of the G-Scripts site suggests some ways to handle this:
  1. protect your variable with double quotes: instead of $1 use "$1"
  2. process the filenames with SED:
    files=`echo "$1" | sed 's/ /\\ /g'`
  3. process the filenames with AWK and SED:
    quoted=$(echo -e "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" | awk 'BEGIN {FS = "\n" } { printf "\"%s\" ", $1 }' | sed -e s#\"\"##); eval "your-program $quoted"
Actually, for me NONE of the above worked.
I found my solution in a stackoverflow post. It uses the IFS value to deal with the filenames. I read somewhere that using the IFS is an inelegant way to deal with field separators, and one should use AWK FS variable instead.

My solution: 

This is to use with nautilus scripts:
IFS=$'\n' read -d '' -r -a filelist < <(printf '%s\n' "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"); unset $IFS
This is to use with my image manipulation scripts (where the script file is located in the same folder as the to-b-manipulated files):
IFS=$'\n' read -d "" -r -a filelist < <(find -iname "*.jpg" | sort); unset $IFS
When you want to call the elements of the array, you'll have to put them in double quotes, like
for i in "${filelist[@]}" 
do echo "$i"
done
Google search keywords to find the solution:

  • escape space in bash script
  • awk fs line break
  • sed change space to newline
  • escape space in bash script with sed
  • internal field separator
  • bash read file names into array
  • bash read space file names into array
  • echo into array bash
  • while read output array bash


2015. január 11.

How to reserve space for panel between monitors

I have two monitors set up above each other.
The primary monitor is the lower one, and has the two edge panels on the top and bottom of the display.
The setting looks something like this:
+---------------+
|               |
|               |
|               |
|               |
|-----------+---+
|'''''''''''|
|           |
|,,,,,,,,,,,|
+-----------+
However, when I maximize a window on the screen with the panels, the panel between the two screens gets ignored, and the window maximizes partially behind it, hiding the top of the window (where the controls are). The same thing happens with the bottom panel, if I switch the panels to the upper monitor.

I ran into this problem while trying to configure a snap-to script for a two monitor environment. Obviously, I had to sort this out before moving forward with the script.

The heart of the problem is the thing called "strut" which is basically a reserved space on the screen for a window.

Long story short, a strut for a window can be set with xprop.

You can find more information about the things I describe below on the xprop manpage, the ewmh reference page, and on the manpages of xwininfo, xrandr and grep.

Let's get started!

First you'll need some information about your screen setup to know what you're doing is right.

Get the size of your virtual screen (you can skip this):
xprop -root | egrep '^(_NET_WORKAREA)'


I got this (I have 4 workspaces, this is why the numbers appear four times in a row):
_NET_WORKAREA(CARDINAL) = 0, 0, 1280, 1792, 0, 0, 1280, 1792, 0, 0, 1280, 1792, 0, 0, 1280, 1792
So my screen is 1280x1792 pixels, and it's one big virtual screen alltogether.
I know that my upper screen is 1280x1024 in resolution, and the lower one is 1024x768. If I needed to check this with a command, I would use xrandr -q | grep '*'

Get the ID of the relevant panel (you'll have to click on the panel after you run this):
xwininfo | grep -w id


I got this:
xwininfo: Window id: 0x1600007 "Top Expanded Edge Panel"
Now I know the ID of the top panel is 0x1600007. I'll need this later.

Get an idea about the strut currently set for your panels (you can skip this):

xprop -id 0x1600007 | egrep '^(_NET_WM_STRUT_PARTIAL)'


I got this:
_NET_WM_STRUT_PARTIAL(CARDINAL) = 0, 0, 0, 0, 0, 0, 0, 0, 0, 1023, 0, 0

For a comparison, this is the same output for the bottom panel - notice the "24" in the fourth place:
_NET_WM_STRUT_PARTIAL(CARDINAL) = 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 1023

Now, plan your setting!
How to use ewmh _net_wm_strut_partial property?

The property you want to set is somewhat complicated. The lot of zeros and non-zeros you see above mean the following:
_NET_WM_STRUT_PARTIAL, left, right, top, bottom, left_start_y, left_end_y, right_start_y, right_end_y, top_start_x, top_end_x, bottom_start_x, bottom_end_x,CARDINAL[12]/32

This is still very confusig. I could sort out these settings for myself thanks to this stackoverflow post.

The values are not independent of each other: they are groups. They have to be used together like this:
left & left_start_y & left_end_y
right & right_start_y & right_end_y
top & top_start_x & top_end_x
bottom & bottom_start_x & bottom_end_x
The trick is that you use only one group of values for one window setting. Choosing the one depends on the position you want the window to take.

I will show how to do this on my settings.
My screen dimensions are 1280x1792. The upper screen is 1280x1024, the lower is 1024x768 big.
If I want to reserve space on the bottom of this area, I will relate to this area with the "bottom" value group. So for a panel 1024x24 big, I'll use bottom = 24, bottom_start_x = 0, bottom_end_x = 1024. (because this is on my smaller screen).
Likewise, if I want to reserve space on the top of the two screen big area, I will relate to this area with the "top" value group. So for a panel 1024x24 big, I'll use top = 24, top_start_x = 0, top_end_x = 1280. (because this is on my bigger screen).
However, if I want to put the panel to the top of the lower, smaller screen, I will have to relate to the "left" group, because the left screen sides are the ones lined together (creating a dead area besides the right side of the lower screen).
Relating to the "left" group looks like this: left = 1024 (this is the width of my panel),  left_start_y = 1024 (this is the height of the upper screen), left_end_y= 1048 (this is left_start_y plus the height of my panel (24)).
Reserving space on the upper screen for the bottom panel could be done with the "left" group, but I will demonstrate it with the "right" group. It will be: right = 1280 (with of panel), right_start_y = 1000 (which is the height of the upper screen minus the height of the panel (24)), right_end_y = 1024 (height of upper screen).

Generally, you define left, right, top and bottom relative to the left, right, top and bottom edge of the whole virtual screen, and you define the rest of the values in the regular coordinate system, the top left corner of the whole screen being x=0, y=0, and the bottom right corner being x= full width, y= full height.

Now I have all the values I want to set, and all the information to set them.

I will use xprop -set to set them.
xprop -id 0x1600007 -f _NET_WM_STRUT_PARTIAL 32c -set _NET_WM_STRUT_PARTIAL 1024,0,0,0,1024,1048,0,0,0,0,0,0


The meaning of options are:

-id 0x1600007 (this is the window ID I got from xwininfo)
-f _NET_WM_STRUT_PARTIAL 32c (this is the format of the property I am about to set. for more info check out the manpage)
-set _NET_WM_STRUT_PARTIAL 1024,0,0,0,1024,1048,0,0,0,0,0,0 (this is the property and the values I am setting)

A future plan is to make the system automatically set this option for any kind of multi-monitor setup.

UPDATE: 
I wrote a script to calculate the position of the floating panel and set the strut for me (still manually):
#!/bin/bash
# (re)set panel struts on (different sized) dual monitor screen
#************************************************************
# what this script needs to do?
#############################################################
# PART 1
#************************************************************
# check if screen settings has been modified since the last time this script set the strut
## if yes: the panel position has to be recalculated
### check last modification date of /home/user/.config/monitors.xml
# check if panel strut has been removed anyhow (even when the screen setting has not changed)
## if yes: the strut has to be reset (to the previously used setting)
### comment: since strut gets removed by clicking the menu on the panel, how will it react it it is set back instantly
#############################################################
# PART 2
#************************************************************
# check for panel positions -- done
# set strut for panels -- done
#############################################################
# CONDITIONAL RUNNIG OF THE SCRIPT
# This script should work only if the full screen width < height, because this is the only case when the panel does not have a proper strut.
# Should this script run at all?
#read -a screen_geo < <(xwininfo -root | grep geometry | cut -f4 -s -d" " | awk 'BEGIN { FS="[x+]" } { print $1,$2 }')
#if [ "${screen_geo[0]}" -gt "${screen_geo[1]}" ]; then
#echo "this thingy should quit now, of stand by until screen settings are modified"
#else ### the program should modify the settings.
### however not this does nothing and the settings are modified anyway.
#fi
#############################################################
# PART 2
#************************************************************
# It should be decided which one is the floating panel, and the script should run editing only this panel.
# An array for all the panels (id numbers get in it)
read -a panels_id < <(wmctrl -l | grep "Panel" | awk '{ print $1 }' | tr '\n' ' ' | awk '{ print $1,$2}')
# Which panel is floating?
# A panel is floating if the first 4 values in the testpanel array are all 0.
for i in "${panels_id[@]}"; do
counter=0
read -a testpanel < <(xprop -id $i | egrep '^(_NET_WM_STRUT_PARTIAL)' | cut -f3- -d" " | awk 'BEGIN { FS="," } { print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12 }') # 0 0 0 0 0 0 0 0 0 1023 0 0
#echo ${testpanel[*]}
 for j in "${testpanel[@]:0:4}"; do
  if [ "$j" -gt "0" ]; then
  let "counter = $counter + 1"
  fi
 done
 if [ $counter -lt "1" ]; then
 fl_id=$i
 fi
done
#echo $fl_id
# Get important values for the floating panel to work with: 
# geometry of the floating panel
read -a fl_geo < <(xwininfo -id $fl_id | grep geometry | cut -f4 -s -d" " | awk 'BEGIN { FS="[x+-]" } { print $1,$2,$3,$4 }') # 1024 24 0 1024
#echo ${fl_geo[*]}

# strut values of the floating panel
read -a fl_strut < <(xprop -id $fl_id | egrep '^(_NET_WM_STRUT_PARTIAL)' | cut -f3- -d" " | awk 'BEGIN { FS="," } { print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12 }') # 0 0 0 0 0 0 0 0 0 1023 0 0
#echo ${fl_strut[*]}

# Calculate correct strut position
# Should it be on the Left or on the Right? 
# The panel is on the left side if there is less than two value in the strut array greater than 0.
counter=0
for i in "${fl_strut[@]}"; do
 if [ "$i" -gt "0" ]; then
 let "counter = $counter + 1"
 fi
done
if [ $counter -lt "2" ]; then
side="left"
else
side="right"
fi
#echo $side
# Calculate the values for the strut position
# Usage: _NET_WM_STRUT_PARTIAL, left, right, top, bottom, left_start_y, left_end_y, right_start_y, right_end_y, top_start_x, top_end_x, bottom_start_x, bottom_end_x,CARDINAL[12]/32
left=0; right=0; top=0; bottom=0; left_start_y=0; left_end_y=0; right_start_y=0; right_end_y=0; top_start_x=0; top_end_x=0; bottom_start_x=0; bottom_end_x=0
# ${fl_geo[0]} width
# ${fl_geo[1]} height
# ${fl_geo[2]} x
# ${fl_geo[3]} y
if [ "$side" = "left" ]; then
left=${fl_geo[0]}
left_start_y=${fl_geo[3]}
left_end_y=$((${fl_geo[3]}+${fl_geo[1]}))
elif [ "$side" = "right" ]; then
right=${fl_geo[0]}
right_start_y=${fl_geo[3]}
right_end_y=$((${fl_geo[3]}+${fl_geo[1]}))
fi
# set correct strut for floating panel
# echo "xprop -id $fl_id -f _NET_WM_STRUT_PARTIAL 32c -set _NET_WM_STRUT_PARTIAL $left,$right,$top,$bottom,$left_start_y,$left_end_y,$right_start_y,$right_end_y,$top_start_x,$top_end_x,$bottom_start_x,$bottom_end_x"

xprop -id $fl_id -f _NET_WM_STRUT_PARTIAL 32c -set _NET_WM_STRUT_PARTIAL $left,$right,$top,$bottom,$left_start_y,$left_end_y,$right_start_y,$right_end_y,$top_start_x,$top_end_x,$bottom_start_x,$bottom_end_x

# set -x #activate debugging in normal run from here
# set +x #stop debugging in normal run from here
exit 0

2015. október 1.

Plex Plugin Installer

So, since I found plex plugin manual installation painfully boring, I wrote a nautilus script to do the job for me.
Instead of copy-pasting, you can also download this script form github.

I wasted a couple hours finding out that  if I use "double quotes" instead of 'single quotes' when assigning the plugin folder path to the PLUGIN_FOLDER variable, then 1.) the path will break on spaces and won't work; 2.) if I surround the call with '"'-s (a double quote between two single quotes) or just another "-s the program will fail not finding the files/directories. This was the tricky part because if instead of running I echoed the lines, they looked perfectly okay, and if I copy-pasted them to the command line they would even run properly... only not within a script.

#!/bin/bash
# nautilus script
# install PLEX plugin on Ubuntu 12.04.

# run this script by right clicking on the directory you want to install
install_plugin () {
 # standard feature: install by copying folder
 # future enhancement: install from ZIP file

 PARAMETERS=( "$@" )               ## array containing all params passed to the script

 PLUGIN_FOLDER='/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-ins/'

 # read folder paths into TO_BE_INSTALLED
 IFS=$'\n' read -d '' -r -a TO_BE_INSTALLED < <(printf '%s\n' $PARAMETERS); unset $IFS

 need_to_restart_server=false

 for package in "${TO_BE_INSTALLED[@]}"; do
  package_name="${package##*/}" # Strip longest match of substring (*/) from front of string

 # sanity check: is the path correct? it should be a directory and end with ".bundle".
  if  [[ -d "$package" ]]; then # if selected path IS a directory
   if [[ "${package_name##*.}" == "bundle" ]]; then
    installed_package=$PLUGIN_FOLDER$package_name
   # check if plugin already exists
    if [[ -d "$installed_package" ]]; then 
     # if yes, ask to delete it 
     echo -n "A package with the same name is already installed. Would you like to overwrite it? (yes/no): "; read overwrite 
     if [[ $overwrite == [Yy][Ee][Ss] || $overwrite == [Yy] ]]; then 
      sudo rm -R "$installed_package"
     else
      echo "You chose not to overwrite $package_name so it will not be processed."
      continue
     fi
    fi
   # install plugin
    #copy the downloaded plugin to the plex plug-in directory
    sudo cp -R "$package" "$PLUGIN_FOLDER"

    #change the permissions to be like the existing plug-ins 
    #(this is not needed in 14.04 anymore)
    sudo chmod ugoa+rx "$installed_package"

    #change the owner of the files to be like the existing plug-ins
    sudo chown -R plex:plex "$installed_package"

    need_to_restart_server=true

   else # if not "bundle"
    echo "Package name should end with '.bundle'. $package_name will not be processed."
    continue # process next package instead
   fi

  else # if not directory
   echo "Package should be a directory. $package_name will not be processed."
   continue # process next package instead
  fi

 done
# when finished with all packages, restart plex server.
if [[ $need_to_restart_server = true ]]; then 
 sudo service plexmediaserver stop
 sleep 5
 sudo service plexmediaserver start
 
 echo "Installation complete. Your new plug-in should show up now in PLEX."
fi
}

export -f install_plugin

gnome-terminal --execute bash -c 'install_plugin "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"; bash'

2015. január 10.

Aero snap for Ubuntu 14.04 Flashback with Metacity

In this AskUbuntu post, a solution is described to have the Aero snap to left and right in Metacity Ubuntu. This AskUbuntu post, from the same user, is aiming to develop the solution further. I'll just cover the info from the first post here:

EDIT: I changed the code a little bit to fit my screen better.

You'll need to install two packages for this thing to work:
sudo apt-get install wmctrl xbindkeys

Than you'll need to create two scripts: one for snap left and one for snap right:
Create the files in terminal and give them right to execute by:
sudo touch /bin/snapleft.sh
sudo chmod ugoa+rx /bin/snapleft.sh
sudo touch /bin/snapright.sh
sudo chmod ugoa+rx /bin/snapright.sh 

Open the snapleft.sh by
sudo gedit /bin/snapleft.sh

Copy this text into it:
#!/bin/bash
sleep 0.1 && wmctrl -r :ACTIVE: -b remove,maximized_vert,maximized_horz && wmctrl -r :ACTIVE: -e 0,0,0,`xwininfo -root | grep Width | awk '{ print (($2/2)-2)}'`,`xwininfo -root | grep Height | awk '{ print $2 }'`

than save and close it.
Open the snapright.sh by
sudo gedit /bin/snapright.sh

Copy this text into it:
#!/bin/bash
sleep 0.1 && wmctrl -r :ACTIVE: -b remove,maximized_vert,maximized_horz && wmctrl -r :ACTIVE: -e 0,`xwininfo -root | grep Width | awk '{ print (($2/2))}'`,0,`xwininfo -root | grep Width | awk '{ print (($2/2))}'`,`xwininfo -root | grep Height | awk '{ print $2 }'`
than save and close it.

Now set the keyboard shortcuts with xbinkeys (to the left-side "super"/windows key and the left and right arrow keys) by
printf '"bash /bin/snapleft.sh"\n Mod4 + Super_L + Left\n' > ~/.xbindkeysrc 
printf '"bash /bin/snapright.sh"\n Mod4 + Super_L + Right\n' >> ~/.xbindkeysrc

You can check the name of a key (if something is amiss) with
xbindkeys -k


NEW STUFF:

To have a snap up and snap down function use the above guide with the following changes:

script name: snapup.sh
script content:
#!/bin/bash
sleep 0.1 && wmctrl -r :ACTIVE: -b remove,maximized_vert,maximized_horz && wmctrl -r :ACTIVE: -e 0,0,0,`xwininfo -root | grep Width | awk '{ print $2 }'`,`xwininfo -root | grep Height | awk '{ print (($2/2)-40)}'`
binding key: Mod4 + Super_L + Up

script name: snapdown.sh
script content:
#!/bin/bash
sleep 0.1 && wmctrl -r :ACTIVE: -b remove,maximized_vert,maximized_horz && wmctrl -r :ACTIVE: -e 0,0,`xwininfo -root | grep Height | awk '{ print (($2/2))}'`,`xwininfo -root | grep Width | awk '{ print $2 }'`,`xwininfo -root | grep Height | awk '{ print (($2/2)-40)}'`
binding key: Mod4 + Super_L + Down

2015. február 25.

PDF smart rename and split based on content


I was planning to do these scripts for some time to ease my work with pdf files.

The original idea was to grep some text from the pdf file and do a file manipulation based on the text.

This StackExchange post suggests the following methods to find a piece of text in a pdf:
  • pdftotext + grep
  • pdfgrep
  • strings + grep
  • pdftohtml + grep
I used pdftotext in the following examples.

I also needed to learn some more Bash scripting:
1st Quest
I have a monthly employee data sheet (payroll), which I get in one big multipage pdf file, having a single page for each employee. The content for each page is: 1st line: title, 2nd line: month, 3rd line: employee name.
I wanted to burst this pdf file into single pages and rename it to title month and employee name.
My solution is:
#!/bin/bash
# NAUTILUS SCRIPT
# automatically splits pdf file to single pages while renaming the output files using the first three of lines of the pdf

# read files
IFS=$'\n' read -d '' -r -a filelist < <(printf '%s\n' "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"); unset $IFS

pagecount=1
datestamp=1

# burst and rename pages to separate files
for file in "${filelist[@]}"; do
 pagecount=`pdfinfo $file | grep "Pages" | awk '{ print $2 }'`
 for (( pageindex=1; pageindex<=$pagecount; pageindex+=1 )); do
  newname=`pdftotext -f $pageindex -l $pageindex $file - | head -n 3 | tr '\n' ' ' | cut -f1 -d"("`
  let "datestamp =`date +%s%N`" # to avoid overwriting with same new name
  pdftk $file cat $pageindex output "$newname"$datestamp.pdf
 done
done

2nd Quest
I have files I would like to rename based on the content of the file. Each file is some kind of employee data file, and has the employee name in the content, but not necessary in the file name.
I wanted to rename the file based on the employee name and the page title (first line of the file).
My solution is:
#!/bin/bash
# NAUTILUS SCRIPT
# automatically renames pdf file based on content maching a list of names

# read files
IFS=$'\n' read -d '' -r -a filelist < <(printf '%s\n' "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"); unset $IFS

names=( "Aaa Aaa" "Bbb Bbb" "Ccc Ccc") # names to match in the files

# process files
for file in "${filelist[@]}"; do
 # find name from names in the file
 foundname=''
 for name in "${names[@]}"; do
  testname=`pdftotext "$file" - | grep $name`
  if [[ $testname != "" ]]; then
   foundname=$name
   break
  fi
 done

 # rename file based on found name
 title=`pdftotext -f 1 -l 1 "$file" - | head -n 1`
 let "datestamp =`date +%s%N`"
 mv "$file" "${file%/*}/$foundname $title $datestamp.pdf"
done

3rd Quest
I have a yearly employee data sheet (personal tax data), which I get in one big multipage pdf file, having a multiple pages for each employee. This year it is three pages per employee, but the tax ID number is the only common point in the three pages (it it a 10 digit long number beginning with number 8). The first line of each page is a header, and it is different for each page for a single employee.
I wanted to split the pdf to employees and rename it with the header of the pages.
My solution is:
#!/bin/bash
# NAUTILUS SCRIPT
# automatically splits pdf file to multiple pages based on search criteria while renaming the output files using the search criteria and some of the pdf text.

# read files
IFS=$'\n' read -d '' -r -a filelist < <(printf '%s\n' "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"); unset $IFS

# process files
for file in "${filelist[@]}"; do
 pagecount=`pdfinfo $file | grep "Pages" | awk '{ print $2 }'`
 # MY SEARCH CRITERIA is a 10 digit long ID number that begins with number 8: 
 storedid=`pdftotext -f 1 -l 1 $file - | egrep '8?[0-9]{9}'`
 pattern=''
 pagetitle=''
 datestamp=''

 for (( pageindex=1; pageindex<=$pagecount; pageindex+=1 )); do

  header=`pdftotext -f $pageindex -l $pageindex $file - | head -n 1`
  pageid=`pdftotext -f $pageindex -l $pageindex $file - | egrep '8?[0-9]{9}'`
  let "datestamp =`date +%s%N`" # to avoid overwriting with same new name

  # match ID found on the page to the stored ID
  if [[ $pageid == $storedid ]]; then
   pattern+="$pageindex " # adds number as text to variable separated by spaces
   pagetitle+="$header+"

   if [[ $pageindex == $pagecount ]]; then #process last output of the file 
    pdftk $file cat $pattern output "$storedid $pagetitle $datestamp.pdf"
    storedid=0
    pattern=''
    pagetitle=''
   fi
  else 
   #process previous set of pages to output
   pdftk $file cat $pattern output "$storedid $pagetitle $datestamp.pdf"
   storedid=$pageid
   pattern="$pageindex "
   pagetitle="$header+"
  fi
 done
done

4th Quest
I wanted to have an alternate version of the 3rd Quest in case I have to split in equal sets of pages any other type of file, not having the tax ID as a common point in them.
So I wanted to split this multipage pdf based on a manually set block size, i.e. 3 pages / set.
My solution is:
#!/bin/bash
# NAUTILUS SCRIPT
# automatically splits pdf file to multiple pages based on given block size, and renames the files using the original filename plus datestamp

# read files
IFS=$'\n' read -d '' -r -a filelist < <(printf '%s\n' "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"); unset $IFS

# process files
for file in "${filelist[@]}"; do

 # variables
 blocksize=3 # ADD BLOCK SIZE MANUALLY HERE
 blocks=()
 filename=${file%.pdf} # remove extension from filename

 # calculate page range blocks
 pagecount=`pdfinfo $file | grep "Pages" | awk '{ print $2 }'` 
 let setcount=$pagecount/$blocksize 
 for (( setindex=1; setindex<=$setcount; setindex+=1 )); do

  if [[ $setindex -lt $setcount ]]; then
   let lastpage=$setindex*$blocksize
   let firstpage=$lastpage-$blocksize+1

  elif [[ $setindex -eq $setcount ]]; then # handle last page
   let lastpage=$pagecount
   let firstpage=$setindex*$blocksize-$blocksize+1

  fi
  blocks+=("$firstpage-$lastpage")
 done

 # process ranges to output
 for block in "${blocks[@]}"; do
  let "datestamp =`date +%s%N`" # to avoid overwriting with same new name
  pdftk $file cat $block output "$filename $datestamp.pdf"
 done
done

That's it. Could be better, but is functioning all right.

2014. március 16.

DJVU extract images

A useful link:
http://askubuntu.com/questions/46233/converting-djvu-to-pdf

Another useful link: http://unix.stackexchange.com/questions/20592/extract-several-pages-from-a-djvu-file
http://kheyali.blogspot.hu/2011/08/in-order-to-convert-djvu-file-into.html

And another: http://en.wikisource.org/wiki/Help:DjVu_files#DjVu_to_Images


Extract images from DJVU:
DDJVU
The easiest way to do this is probably by extracting to multipage tiff
Than split tiff file with tiffsplit: http://manpages.ubuntu.com/manpages/hardy/man1/tiffsplit.1.html
Than convert to anything useful.
Except that did not work for the file I had...

Okay, so the second way is the script way. Copy the script, paste it to an empty text file. Give it the extension .sh and give it permission to execute as program. Put it in a directory with all the djvu-s you want to extract and run in terminal.

#!/bin/bash
#Ubuntu 10.04 Lucid Lynx

#Put this script file in a directory with all the djvu-s you want to extract and run it in terminal.
#All the DJVU-s in this folder will be extracted to PNM-s.

### Select files to process
#defining the filelist
filelist=(`find -iname '*.djvu' | sort`)
#counting the files in the filelist
element_count=${#filelist[*]}
echo "alltogether $element_count djvu will be processed"

#process only 1 file at a time:
counter=1
echo "processing file:"
for i in "${filelist[@]}"
do
echo -ne "$element_count/$counter"\\r

#Get the number of pages from input file
pagecount=`djvused -e n $i`
#Set a filelist for the pages
 for (( filelist=1; filelist<=$pagecount; filelist+=1 ))
 do
 #Extract with DDJVU
 ddjvu -format=pnm -page=$filelist $i file_$counter.page_$filelist.pnm
 #Or use DjvuPs to extract PS from DJVU the same way:
 #djvups -page=$filelist $i file_$counter.page_$filelist.ps
 done
let "counter = $counter + 1"
done

echo DONE.

2012. december 31.

Scanning script for SCANIMAGE

As I wrote before, the program called scanimage cannot scan to numbered files repeatedly.
Well, not anymore.

I wrote a little script to automate the scanning.
I did this because I dislike gscan2pdf scanning to temp. I find it too risky not having the file in a safe place after scanning.

#!/bin/bash
#Ubuntu 10.04 Lucid Lynx

#Automatization of "scanimage" to create sequentially numbered output.

#START
echo "WELCOME TO AUTOMATED SCANIMAGE"
echo ""

echo "Please give me the size of scan area in mm"
echo -n "width: "; read x
echo -n "height: "; read y
#make it failsafe:
if [[ $x>213.8 || $x = "" ]]; then x="213.8"; fi
if [[ $y>300 || $y = "" ]]; then y="300"; fi

echo "Scan area will be: $x x $y mm"
echo ""

echo "Please choose scan mode: L for Lineart, G for Gray. Press enter for Color."; read mode
#make it failsafe:
if [[ $mode == [Ll] ]]; then mode="Lineart" && ext="pbm"
elif [[ $mode == [Gg] ]]; then mode="Gray" && ext="pnm"
else  mode="Color" && ext="pnm"
fi

echo "Scan mode will be $mode"

#print "to start printing press enter to quit press escape"
#scan and save
#go back to enter or escape
date=1
while true; do
 echo -n "Press 'enter' to scan; anything else to quit' "; read scan;
 if [[ $scan = "" ]]; then
  let "date =`date +%Y%m%d%H%M%S`"
  echo "Scanning will progress with the following parameters:"
  echo "size: $x x $y, mode $mode, filename: $date.$ext"
  scanimage -x $x -y $y --mode $mode > $date.$ext
 else break
 fi
done

echo "Finished scanning. Thank you for using this script :-*"

2010. március 7.

Image rotation nautilus script in the right click menu

create folder:
/home/user/.gnome2/nautilus-script

create files:
"Rotate CW"
"Rotate CCW"
"Rotate 180"

edit these in gedit, and than make them executable.

This is the script for Rotate CW:
#!/bin/bash
mogrify -rotate 90 $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
for CCW use 270 and for 180 use 180 instead of 90.

2019. augusztus 3.

Display settings lost on reboot

As described here, this problem is affecting others as well:
Here are the steps I tool to assemble the little script below:

How many displays do you have right now?
xrandr | grep -w connected | wc -l
How to position your displays?
xrandr --output PRIMARY-SCREEN-ID --below SECONDARY-SCREEN-ID
How to rotate a display?
xrandr --output SCREEN-ID --rotate [normal|left|right|inverted]
How to get your display IDs?
primary display:
xrandr | grep -w connected | grep primary | cut -d' ' -f1
secondary display:
xrandr | grep -w connected | grep -v primary | cut -d' ' -f1
How to position your gnome-panels?
Apparently there is no easy way, but for the note, here's where to find these setting:
org.gnome.gnome-panel.layout.toplevels.bottom-panel monitor 0
org.gnome.gnome-panel.layout.toplevels.top-panel monitor 1

Here's the script I put into my .bashrc (.profile would be also a good place for it) to restore the positions of my displays (I have the laptop below the monitor).

# set dual display positions
# because they are forgotten after logout
function reset_displays {
 display_count=`xrandr | grep -w connected | wc -l`
 if [ "$display_count" -eq "2" ]; then
  id1=`xrandr | grep -w connected | grep primary | cut -d' ' -f1`
  id2=`xrandr | grep -w connected | grep -v primary | cut -d' ' -f1`
  xrandr --output $id2 --rotate normal
  xrandr --output $id1 --below $id2
 fi
}
reset_displays

2008. június 15.

Updating to Gutsy

After some time the pen just crashed: after using the pen none of the pointing devices would do a click.
So I updated to Gutsy.
...
Ta-damm:
- the scroll joystick on the edge of the monitor works out os the box.
- the 3 tablet button just don't work with the previous script.
- I had to reinstall linuxwacom to fix the pen buttons.
- Firefox works with Flash :-)
- I had to change the rotate script to this:
#!/bin/sh
if [ -n "$(xrandr | grep "768x1024+0+0 right")" ]; then
 xrandr -o inverted
 xsetwacom set "stylus" Rotate 3
else
 if [ -n "$(xrandr | grep "1024x768+0+0 inverted")" ]; then
 xrandr -o normal
 xsetwacom set "stylus" Rotate NONE
else
 if [ -n "$(xrandr | grep "1024x768+0+0")" ]; then
 xrandr -o right
 xsetwacom set "stylus" Rotate CW
fi
fi
fi

2011. április 20.

DVD ripping with MEncoder

From where I learned:
MEncoder DVD to MPEG-4
Making a high quality MPEG-4 (divx) rip of a DVD movie (mplayerhq manual)
HOWTO: rip DVDs in MPEG-4 (ubuntuforums)

And this turned out to be the most useful:
SimpleRip: Ripping / Encoding DVD-s to Xvid with MEncoder

An automated way should be AcidRip, but it somehow got the code messed-up, when shell-script exported, and I had to correct it manually. What I learned from it is how to handle frameno.avi and divx2pass.log:
#!/bin/sh
echo "***********************************************************"
echo "Automated script created by AcidRip - http://acidrip.sf.net"
echo "***********************************************************"

unlink frameno.avi 2> /dev/null
mencoder dvd://1 -dvd-device /dev/dvd  -aid 129 -oac mp3lame -lameopts mode=2:cbr:br=128  -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=740:vhq:v4mv:vqmin=3:vpass=1 -vf crop=672:432:24:22    -o "/dev/null"
mencoder dvd://1 -dvd-device /dev/dvd  -aid 129 -oac mp3lame -lameopts mode=2:cbr:br=128  -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=740:vhq:v4mv:vqmin=3:vpass=2 -vf crop=672:432:24:22    -o "/home/user/movie.avi"
unlink divx2pass.log  2> /dev/null
As for the subtitle (.idx + .sub = VOBSUB format):
I want to convert them to SRT.
--> I used AVIDEMUX (downloaded from Synaptic) It worked fine.

2008. december 29.

ImageMagick

I gave up on tesseract, so now I'm modifying the photos I took to a smaller size, and attaching them in a PDF with gscan2pdf.

I installed ImageMagick with synaptic, and found the matching script on it's webpage.
I had to modify this script, because convert didn't find the
-contrast-stretch.
Now it looks like this:
convert eredeti.JPG -background white -flatten -colorspace Gray -negate -edge 1 -negate -normalize -sharpen 1 -threshold 50% -despeckle -blur 0x.5 -normalize +dither -posterize 8 verzio_dit3.gif
Since I want to modify a lot of images, I tried to do this simple, so I tried to use these tricks:
- input filename globbing (convert *.JPG [outputfilename])
- output filename references (convert *.jpg myimage-%d.jpg) which should produce myimage-1.jpg, myimage-2.jpg, etc.
However, the output just didn't want to work. It always gave me a single file: the last file. But the procedure was so long, I think the program did the work, just saved all the images over that one file.

To see if this is only because of the older version (2.4) of the program, I tried to install, the newest version(2.6). It installed well, however, something went wrong, and I got the following error while trying to use convert
error while loading shared libraries:libMagickCore.so.1
Now I'm reinstalling, following these tips
./configure LDFLAGS="-L/usr/local/lib -Wl,-rpath,/usr/local/lib"
Installation was a success.

However, converting more files at once still doesn't work.

2009. január 3.

ImageMagick converting multiple files

*I do not use this method anymore, although it was a great start.*

After being a book-worm for half a day, I found out how can I write a working script to solve my imagemagick output problem.
It looks like this:


#!/bin/sh

for i in `find -iname '*.jpg'`
do
convert $i -background white -flatten -colorspace Gray -negate -edge 1 -negate -normalize -sharpen 1 -threshold 50% -despeckle -blur 0x.5 -normalize +dither -posterize 8 gif:- >> $i.gif
done
1.) open your favorite text editor
2.) copy paste the script
3.) save as anyname.sh
4.) make it executable

Usage:
1.) copy anyname.sh in the folder containing only the image files you want to make simple
2.) go (cd) to this folder in the terminal
3.) type ./anyname.sh
4.) wait and see.

How to convert this to pdf?

mogrify -format pdf *.JPG

How to join these single-page pdfs?

pdfjoin *.pdf --outfile newname.pdf

2015. május 22.

Connection the Ubuntu Phone to the Ubuntu Desktop

Sadly, if you connect the Ubuntu Phone with an USB cable to the Ubuntu Desktop PC, it just might not show up in Files/Nautilus.

On Ubuntu 14.04 the problem can be solved by installing the latest libmtp on the Ubuntu Desktop.
As written in this askubuntu answer:
sudo add-apt-repository ppa:fossfreedom/libmtp
sudo apt-get update
sudo apt full-upgrade

On Ubuntu 12.04 it is not this easy.

To install the latest libmtp, use these commands instead of the above:
sudo add-apt-repository "deb http://ppa.launchpad.net/fossfreedom/libmtp/ubuntu trusty main" 
sudo add-apt-repository "deb-src http://ppa.launchpad.net/fossfreedom/libmtp/ubuntu trusty main"
sudo apt-get update
sudo apt-get dist-upgrade

However, the Ubuntu Phone still not shows up in Nautilus.
But it is definitely recognized in lsusb:
~$ lsusb
Bus 001 Device 004: ID 2a47:2008 

ADB: an alternate way

An alternate way to reach the phone in with the Android Debugging Bridge (adb).
Install adb, if you don't have it yet:
sudo apt-get install android-tools-adb 

To be able to use the adb with the Ubuntu Phone, turn on Developer Mode on your phone.
Go to 'Apps > System Settings > About this phone > Developer mode' and turn it on. You'll have to set a Lock security first if you use Swipe only to unlock your phone.

As written in this askubuntu post, you'll have to add the phone vendor manually to the list adb recognizes, and then restart the adb-server:
printf '0x2a47\n' > ~/.android/adb_usb.ini
sudo adb kill-server;  sudo adb start-server

Now the Ubuntu Phone is recognized by adb:
~$ adb devices
List of devices attached 
JU013288 device

Usage of adb:
As a regular user, you'll probably just want to move files around.
This can be done with the push and pull commands.
Push copies a specified file from your computer to the phone.
adb -d push <local> <remote>
For example:
adb -d push ~/Music/testfile.mp3 Music/
Pull copies a specified file from the phone to your computer.
adb -d pull <remote> [<local>]
For example:
adb -d push Music/testfile.mp3 ~/Music/
List files and directories of your phone:
~$ adb -d shell ls
Documents  Downloads  Music  Pictures  Videos

~$ adb -d shell ls Music/
testfile.mp3

Mass-copy files with adb:
With adb it is impossible to mass-copy files. There is a sync option, but it only updates files that already exist, and copies none.
Alternate ways are script and tools based on adb, for example:

2015. január 11.

Aero Snap for extended display on different screen resolutions - a workaround

In this AskUbuntu post, a solution is described to have the Aero snap to left and right in Metacity Ubuntu. I covered the content of the post previously based on the post, and added a snap up and snap down function too.

This AskUbuntu post, from the same user, is aiming to develop the solution further for multiple monitors. Based on this post I'll do my own workaround.

I have two displays. One is 1024x768, the other is 1280x1024 in resolution.
I either put them beside or on top of each other.
I already worked out the usage of the tablet screen as a tablet in similar settings.

I will call displays beside each other "Sided", and displays on top of each other "Topped".

Sided screen is 2304x1024, Topped is 1280x1792 in resolution.

The script as is, puts the active window according to this table:
SnapSided displayTopped display
leftleft screenbigger screen left
rightright screenbigger screen right
upbigger screen upupper screen
downbigger screen downlower screen

There are problems with the resized window's sizes, caused by the different screen sizes and the expanded edge panels (top and bottom panel). This is what I would like to fix.

Defining screens
the tool for dynamic screen manipulation is xrandr.

Normal/Default (with only one screen and the expanded edge panels (top+bottom) in place)
Small display maximized window is 1024x692 in position 0:80
Big display maximized window is 1280x948 in position 0:80


Topped Displays
Small display (with panels) maximized window is 1024x716 in position 0:1080
Small display maximized window is 1024x740 in position 0:1080
Big display (with panels) maximized window is 1280x972 in position 0:80
Big display maximized window is 1280x996 in position 0:56

As is visible from the altering numbers, either the top or the bottom of the windows are hidden under the edge panels in the Topped view.
This is a problem experienced by different users in AskUbuntu and elsewhere.
It is caused because "panels in between monitors are not supported, and this is a limitation in the freedesktop specification for reserving space for things like panels."

# What is my Desktop Manager? ("dm")
~$ env | grep XDG_CURRENT_DESKTOP
Mine is GNOME.

# What is my Window Manager? ("wm")
~$ wmctrl -m
Mine is Metacity. It's configuration tool is gconftool-2.
It can be set to be a compositing window manager (like compiz but simpler) by opening dconf-editor and navigating to > org > gnome > metacity > compositing-manager > mark checked. It has these features: real window transparency (i.e. terminal window), window shadow, Alt+Tab window selector shows screenshot of the window; it is said to support AWN, and Gnome Do.


#What is EWMH?
EWMH is a standard for window management. For more info visit this site.

# What is the full size of the display?
that is given by ~$ wmctrl -G -l | grep Desktop
or by ~$ xwininfo -root | grep Height and ~$ xwininfo -root | grep Width
or by ~$ xwininfo -root | egrep '(Height|Depth)' displayed in two rows.

# Is the view topped or sided?
if width>height it is the sided view, else it is the topped view.

# What are the single display sizes?
they are given by xrandr -q | grep '*' displayed in two rows.

#What are the names of the displays?
they are given in ~$ xrandr -q
my displays are LVDS1 and VGA1 indicating the connection port they use.

# How many displays do I have?
~$ xrandr -q | grep -c -w connected

# What are the positions (coordinates) of the displays?
they are given in ~$ xrandr -q in the form of XxY+W+H where the W and H are the x and y positions

# Which display has the edge panels?
the primary display has them. that is given by ~$ xrandr -q | grep -w primary

#What do I need?
  • I need the edge panes handled so they would not hide any portion of the maximized windows. --> partially done.
  • I need new scripts for moving a windows to either one of the displays.
  • I need the snap-to-sides scripts to work within the screen where the window actually is.
  • A next step would be if this whole thing would work by dragging the windows to the side of the screen, like on Microsoft Windows.
#References
#Tools (manpages)

2013. június 26.

Nautilus Open-in-terminal

Beside of using Nautilus script to open a specific nautilus folder in terminal,
it is possible to use the nautilus-open-terminal software.

Download it with
sudo apt-get install nautilus-open-terminal
Then restart nautilus with logging out and in again, or with
nautilus -q
This should do the trick.
&& Have fun using it!

2017. április 6.

How to make .sh files run on double click?

In Ubuntu 16.04 LTS unlike in previous LTSs executable shell script files when double clicked open automatically for editing instead of seeing a popup asking what to do with them.

To restore the confirmation popup do as it is said in this askubuntu post: make sure your file manager supports executing files:
$ gsettings set org.gnome.nautilus.preferences executable-text-activation ask
Alternatively:
  1. Open dconf Editor
  2. Navigate to org.gnome.nautilus.preferences
    1. Set the 'executable-text-activation' to 'ask'

2015. január 3.

Plex Configuration for various reasons

Restart Plex Server:

~$ sudo service plexmediaserver stop
~$ sudo service plexmediaserver start

Install Plug-in manually:
Plug-in directory: /var/lib/plexmediaserver/Library/Application\ Support/Plex\ Media\ Server/Plug-ins/

To install a new plug-in:
the new plug-in's directory name should end with ".bundle" like the existing plug-in directories.
copy the downloaded plugin to the plex plug-in directory
~$ sudo cp -R /download_dir/new_plug-in_dir /plex_plugin_dir/
change the permissions to be like the existing plug-ins (this is not needed in 14.04 anymore)
~$ sudo chmod ugoa+rx /plex_plugin_dir/new_plug-in_dir
change the owner of the files to be like the existing plug-ins
~$ sudo chown -R plex:plex /plex_plugin_dir/new_plug-in_dir
restart plex server as written above.
the new plug-in should show up in plex.

Custom plug-in sources:


works fine for me.


To get AnimeToon working you need to update this file:
AnimeToon.bundle/Contents/Services/URL/AnimeToon/ServiceCode.pys

UPDATE: a fixed version of the plugin can be downloaded from here.

Add these lines to the end of the file:

###new stuff begins

elif each.find("videozoo") >= 0:
 page_data = HTML.ElementFromURL(each)
 string_data = HTML.StringFromElement(page_data)
 find_url = RE_PLAY44.search(string_data).group()
 url = String.Unquote(find_url, usePlus=False)
 Log(url)
 return [MediaObject(parts = [PartObject(key = url)])]

elif each.find("playbb") >= 0:
 page_data = HTML.ElementFromURL(each)
 string_data = HTML.StringFromElement(page_data)
 find_url = RE_PLAY44.search(string_data).group()
 url = String.Unquote(find_url, usePlus=False)
 Log(url)
 return [MediaObject(parts = [PartObject(key = url)])]

elif each.find("easyvideo") >= 0:
 page_data = HTML.ElementFromURL(each)
 string_data = HTML.StringFromElement(page_data)
 find_url = RE_VIDEO44.search(string_data).group()
 url = String.Unquote(find_url, usePlus=False)
 Log(url)
 return [MediaObject(parts = [PartObject(key = url)])]

elif each.find("playpanda") >= 0:
 page_data = HTML.ElementFromURL(each)
 string_data = HTML.StringFromElement(page_data)
 find_url = RE_PLAY44.search(string_data).group()
 url = String.Unquote(find_url, usePlus=False)
 Log(url)
 return [MediaObject(parts = [PartObject(key = url)])]

###new stuff over

2018. május 2.

NVIDIA GeForce 930MX driver update

I ran into this "little" problem with SweetHome3D that it says "Sweet Home 3D will exit now because of a fatal error in 3D rendering system". The SH3D FAQ suggests to upgrade to the lastet graphic card driver.

I did not have a dedicated graphic card in my laptop before so having to care for the driver is a new experience.

The card in my Dell Latitude 5480 is an NVIDIA GeForce 930MX.
I found that the driver can be downloaded from the official site.
Here's how to pick it out from the list.
Current version is 390.48; released on 2018.03.28. It needs to be run from terminal with root.

Then I tried to install it from the terminal by running the .ran file and got stuck on errors

First I got the error: "You do not appear to have an NVIDIA GPU supported..."
This is fixed by changing the PRIME Profile from Intel (Power Saving Mode) to NVIDIA (Performance Mode) in NVIDIA X Server Settings (screenshot) (in flashback: Applications --> System Tools --> Administration)
Then log out and log in again, and this error will be gone.
However this alone did not solve the SweetHome3D problem, in the contrary it got it worse, now the program crashes at startup with the mentioned error.
The next error was "You appear to be running an X server..."
To get rid of this, here's a handy step-by-step:
  1. Switch to terminal with Ctrl+Alt+F1
    (switch back with Ctrl+Alt+F7 if you need to)
  2. Stop X with sudo service lightdm stop
    (start it back up with sudo service lightdm start if you need to)
Now, the following error was "The distribution-provided pre-install script failed..."
When I searched for this I ran into a some promising askubuntu answers:

Then I acquired some more info on my hardware

First of all, I ran lspci -k | grep -EA2 'VGA|3D' to find out what I have on the machine:
00:02.0 VGA compatible controller: Intel Corporation Device 591b (rev 04)
 DeviceName:  Onboard IGD
 Subsystem: Dell Device 07d0
--
02:00.0 3D controller: NVIDIA Corporation Device 134e (rev a2)
 Subsystem: Dell Device 07d0
 Kernel driver in use: nvidia
With sudo lshw -numeric -C display | grep -E "(product|vendor)" we get a different but similar set of information:
product: NVIDIA Corporation [10DE:134E]
vendor: NVIDIA Corporation [10DE]
product: Intel Corporation [8086:591B]
vendor: Intel Corporation [8086]
To get the current nvidia driver version, run nvidia-smi from terminal.
This information is also available from the Software&Updates setting Additional Drivers tab. (screenshot here) and also from the NVIDIA X Server Settings mentioned before.
I'm running 384.111

Then I tried to install it from the ppa repository and succeeded

sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt update
sudo apt-get install nvidia-390
It said that there are recommended packages: libcuda1-390 nvidia-opencl-icd-390, so I installed those too:
sudo apt-get install libcuda1-390 nvidia-opencl-icd-390
I also did a sudo apt autoremove while I was at it.
Restarted the machine, and now I have the 390.48 version driver successfully installed. The procedure was pretty painless.

As for the SweetHome3D program, this unfortunately did not help.
However I succeeded with the next suggestion in the FAQ: running SH3D compiled with the older Java3D library (SweetHome3D-Java3D-1_5_2)