You are not logged in.

#51 2019-12-05 09:40:32

misko_2083
Member
Registered: 2016-05-24
Posts: 438

Re: Alarm clock scripts

^Well that depends from the chemical composition of the water, temerature, volume of the pot, barometric pressure, density of the spaghetti...
No, I'm pretty sure they boil them in the microwave oven. For science... :-)
Time is relative, for someone hungry waiting for spaghetti to boil - it takes too long, for someone who had a snack when no one was watching those 12 minutes are a blink of an eye.


Што ни оштровиди ум сагледати не може - љубав превазилази.

Offline

#52 2020-01-21 14:10:05

misko_2083
Member
Registered: 2016-05-24
Posts: 438

Re: Alarm clock scripts

New script with at command.

You can choose between running the file in mpv or a custom command.
If you type in custom command, don't use "@" character. This is the limitation.
Custom command can be firefox "www.youtube.com" for example.
Leave the custom blank for mpv.
Ticking "Loop forever" overides "repeat".
Job can be listed and removed via "List at Job" button.


#!/bin/bash
# Fancy alarm Misko_2083 @ 2020
# Requires: at, yad 0.42 (with html dialog), mpv

#########################
# Begin User Interface  #
#########################

# JavaScript, HTML and CSS

YURI="$(cat << EOF
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

<!--CSS for the page-->
<style>
.body, .html {
  overflow-y: hidden;
  cursor: default;
  background-color: #CECECE;
}

#jsalarmclock{
font-weight: bold;
font-size: 14px;
}

#jsalarmclock div{
margin-bottom: 0.8em;
}

#jsalarmclock div.leftcolumn{
float: left;
width: 150px;
font-size: 14px;
clear: left;
}

#jsalarmclock span{
 margin-right: 10px;
}

#jsalarmclock input[type=number]{
 width: 50px;
}

p {
 font-weight: bold;
 font-size: 11px;
}

.default:hover {
  background: #000000;
  color: white;
  text-decoration: none;
}

.title {
 font-size: 10px
 cursor: default;
}
</style>

<!--Script to prevent right click menu-->
<script type="text/javascript">
    if (document.addEventListener) { // IE >= 9; other browsers
        document.addEventListener('contextmenu', function(e) {
            //here you do nothing
            e.preventDefault();
        }, false);
    } else { // IE < 9
        document.attachEvent('oncontextmenu', function() {
            alert("You've tried to open context menu");
            window.event.returnValue = false;
        });
    }
</script>


<script type="text/javascript">

/***********************************************

* JavaScript Alarm Clock- by JavaScript Kit (www.javascriptkit.com)
* This notice must stay intact for usage
* Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and 100s more

***********************************************/

/* Modified for my needs Misko_2083 */

var jsalarm={
	padfield:function(f){
		return (f<10)? "0"+f : f
	},
	showcurrenttime:function(){
		var dateobj=new Date()
		var ct=this.padfield(dateobj.getHours())+":"+this.padfield(dateobj.getMinutes())+":"+this.padfield(dateobj.getSeconds())
		this.ctref.innerHTML=ct
		this.ctref.setAttribute("title", ct)
	},
	init:function(){
		var dateobj=new Date()
		this.ctref=document.getElementById("jsalarm_ct")
		this.submitref=document.getElementById("submitbutton")
		this.submitref.onclick=function(){
			jsalarm.setalarm()
			//this.value="Alarm Set"
			this.disabled=false
			return false
		}
		var selections=document.getElementsByTagName("select")
		this.hourselect=selections[0]
		this.minuteselect=selections[1]
		for (var i=0; i<60; i++){
			if (i<24) //If still within range of hours field: 0-23
			this.hourselect[i]=new Option(this.padfield(i), this.padfield(i), false, dateobj.getHours()==i)
			this.minuteselect[i]=new Option(this.padfield(i), this.padfield(i), false, dateobj.getMinutes()+1==i)

		}
		jsalarm.showcurrenttime()
		jsalarm.timer=setInterval(function(){jsalarm.showcurrenttime()}, 1000)
	},
        info:function(a) {
                var h = document.createElement("p");
                var filename = String(a).replace(/^.*[\\\/]/, '');
                var t = document.createTextNode("Alarm "+filename);
                h.appendChild(t);
                document.body.appendChild(h);
                h.setAttribute("id", "info");
        },
        dom:function(a){
                // DOM 2 Events
                var dispatchMouseEvent = function(target, var_args) {
                  var e = document.createEvent("MouseEvents");
                  // If you need clientX, clientY, etc., you can call
                  // initMouseEvent instead of initEvent
                  e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
                  target.dispatchEvent(e);
                };
                dispatchMouseEvent(a, 'mouseover', true, true);
                dispatchMouseEvent(a, 'mousedown', true, true);
                dispatchMouseEvent(a, 'click', true, true);
                dispatchMouseEvent(a, 'mouseup', true, true);
        },
	setalarm:function(){
		this.hourwake=this.hourselect.options[this.hourselect.selectedIndex].value
		this.minutewake=this.minuteselect.options[this.minuteselect.selectedIndex].value
                var a = document.createElement('a');
                var linkText = document.createTextNode("Go");
                a.appendChild(linkText);
                a.title = "fake link";

                a.href = this.hourselect.options[this.hourselect.selectedIndex].value+":"+this.minuteselect.options[this.minuteselect.selectedIndex].value;
                jsalarm.dom(a)
                jsalarm.info(a)
                a.href = "repeat@"+document.getElementById("repeat").value;
                jsalarm.dom(a)
                if(document.getElementById("forever").checked == true) {
                  a.href = "repeat@"+document.getElementById("forever").value;
                  jsalarm.dom(a)
                }
                a.href = "command@"+document.getElementById("command").value;
                jsalarm.dom(a)
                //a.parentNode.removeChild(linkText);
		//this.hourselect.disabled=true
		//this.minuteselect.disabled=true
	}

}

</script>
</head>
<body class="body">
<br />

 <form action="" method="">
  <div id="jsalarmclock">
  <div><div class="leftcolumn">Current Time:</div> <span id="jsalarm_ct" style="letter-spacing: 2px"></span></div>
  <div><div class="leftcolumn">Set Alarm:</div> <span><select></select> Hour</span> <span><select></select> Minutes</span> </div>

  <div><div class="leftcolumn">Repeat:</div><input size="5" type="number" id="repeat" min="1" value="1"/>  <br>
        <div class="leftcolumn">Loop forever</div> <input type="checkbox" id="forever" value="forever"/>
       <span style="font: normal 11px Tahoma">Loop forever overides repeat</span> <br>
  <div><div class="leftcolumn">Set file:</div><a href="file:///musicfile@"><button type="button">Select a file to play</button></a>
             <span style="font: normal 11px Tahoma">Select a file to run with mpv or type in a custom action</span></div>
  <div><div class="leftcolumn">Set Custom Action:</div> <input type="text" id="command" size="55" value="" /> <br>
       <span style="font: normal 11px Tahoma">*Command to launch, if empty mpv will be used (do not use "@" character here)</span></div>
  <input type="submit" value="Set Alarm!" id="submitbutton" />

  </div>
</form>

<a href="file:///atq@"><button type="button">At Job List</button></a>

<script type="text/javascript">

jsalarm.init()

</script>
</body>
</html>
EOF
)"
#########################
# End of User interface #
#########################

#########################
# Bash functions        #
#########################

# Main window
function _yad_ui(){
    # Set the line buffering with stdbuf
    echo "${YURI}" | stdbuf -oL -eL yad --title="Set Alarm" --width=650 --height=500 --no-escape \
    --html --no-buttons --print-uri --borders=0 --window-icon="alarm1c.png" 2>&1 & echo $!
}

# Main Function
function _do_stuff(){
    # fetch yad process id
    read YAD_PID

    # read yad stdout line by line
    while read -r line
    do
        case ${line##*/} in
         [0-9][0-9]:[0-9][0-9]*)
            #kill -SIGUSR1 $YAD_PID
            echo "Alarm set to: ${line##*/}"
            alarm_time="${line##*/}"           
;;
                   repeat@*) REPEAT="$(echo  "${line##*@}" | sed 's/%20/ /g')"
;;
                   command@*) COMMAND="$(echo  "${line##*@}" | sed 's/%20/ /g')"

if [ ! -e "/tmp/yalarm.$$" ] ; then
      MUSIC="$(yad --width=600 --height=500 \
                    --title="Alarm" --text="Select a file to play in mpv" \
                    --file-filter="Audio | *.mp3 *.MP3 *.wav *.WAV *.ogg *.OGG" \
                    --file 2>/dev/null)"
      [ $? != 0 ] && continue
       echo "${MUSIC}" > /tmp/yalarm.$$
fi

# Fredx181
hrnow=$(echo $(date +"%k"))

# For when trying to set alarm for next day e.g. from current 21:00 to target 6:00
if [ "${alarm_time%%:*}" -eq "$hrnow" ] &&  [ "${alarm_time##*:}" -le "$(date +"%M")" ]; then
    # prompt yes/no in case accidentally chosen current hour but less than current minute
    yad --center --title="Are you sure?" --text="Are you sure to set the alarm to ${alarm_time} - tomorrow ?" --width=400 --button="Yes:0"  --button="No:1"
[ $? -ne 0 ] &&  continue 
fi

if [ ! "${COMMAND}" = "" ]; then
at "${alarm_time}" << EOF
exec env DISPLAY="$DISPLAY" $(echo  "${line##*@}" | sed 's/%20/ /g') &
EOF
else
    if [  "${REPEAT}" = "forever" ]; then
at "${alarm_time}" << EOF
exec env DISPLAY="$DISPLAY" mpv --force-window --loop inf "$(cat /tmp/yalarm.$$)"
EOF
    else
at "${alarm_time}" << EOF
exec env DISPLAY="$DISPLAY" mpv --force-window --loop "${REPEAT}" "$(cat /tmp/yalarm.$$)"
EOF
   fi
fi

;;
                   atq@*) (REMOVE_JOB="$(atq | yad --list --width=600 --height=500 \
                                                  --text="Select 'at' job to remove or close this window" \
                                                  --column "Job List" \
                                                  --button="Remove at Job" 2>/dev/null \
                                            | awk '{print $1}')"
                          if [[ "${REMOVE_JOB}" == [0-9]* ]]; then
                             echo "${REMOVE_JOB}"
                             atrm "${REMOVE_JOB}"
                             killall mpv
                          fi) &                      
;;
                   musicfile@*) (MUSIC="$(yad --width=600 --height=500 \
                                              --title="Alarm" --text="Select a file to play in mpv" \
                                              --file-filter="Audio | *.mp3 *.wav" \
                                              --file 2>/dev/null)" \
                                               [ $? = 0 ] && echo "${MUSIC}" > /tmp/yalarm.$$) &
;;
       esac 
    done
rm /tmp/yalarm.$$
exit
}

_yad_ui | _do_stuff & wait $! 2>/dev/null

This can be converted from HTML to regular GTK+ dialogs.

Last edited by misko_2083 (2020-01-21 14:17:13)


Што ни оштровиди ум сагледати не може - љубав превазилази.

Offline

#53 2020-01-22 10:30:06

brontosaurusrex
Middle Office
Registered: 2015-09-29
Posts: 2,277
Website

Re: Alarm clock scripts

@misko, nice, some thoughts (I build latest yad)
- position 'Repeat' and 'Loop forever' under 'Select a file to play' so it is clear this is related to sound and not repeating alarm every day (or something)
- Select a file to play' doesn't do anything for me, I get file dialog after clicking 'Set Alarm!'
- 'At Job List' is showing two alarms set at same time, but when running atq from cli there is only single event
- Missing delete event functionality?

edit: I wonder if analog picker like
https://weareoutman.github.io/clockpicker/ or
https://github.com/luncheon/clocklet
could be implemented?

edit2: I have repacked some css/html/js/svg clock for testing purposes and it works (but don't feel brave enough for js->yad interface as it would be needed for picker).
https://github.com/brontosaurusrex/svgclockcool
jbTMpz4b.png

Last edited by brontosaurusrex (2020-01-22 23:31:53)

Offline

#54 2020-01-27 13:35:56

misko_2083
Member
Registered: 2016-05-24
Posts: 438

Re: Alarm clock scripts

^I'll check it out.


Што ни оштровиди ум сагледати не може - љубав превазилази.

Offline

#55 2020-01-28 16:58:13

misko_2083
Member
Registered: 2016-05-24
Posts: 438

Re: Alarm clock scripts

brontosaurusrex wrote:

edit: I wonder if analog picker like
https://weareoutman.github.io/clockpicker/ or
could be implemented?

It uses some libraries, you can see them in assets folder JQuery Bootstrap and html5shiv.
Some experimentation.
Unpacked it to Documents and created a file "yad.html" in that directory.
And put next inside:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ClockPicker</title>
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="dist/bootstrap-clockpicker.min.css">
<link rel="stylesheet" type="text/css" href="assets/css/github.min.css">
<style type="text/css">
.navbar h3 {
	color: #f5f5f5;
	margin-top: 14px;
}
.hljs-pre {
	background: #f8f8f8;
	padding: 3px;
}
.footer {
	border-top: 1px solid #eee;
	margin-top: 40px;
	padding: 40px 0;
}
.input-group {
	width: 110px;
	margin-bottom: 10px;
}
.pull-center {
	margin-left: 0px;
	margin-right: auto;
}
@media (min-width: 768px) {
  .container {
    max-width: 730px;
  }
}
@media (max-width: 767px) {
  .pull-center {
    float: right;
  }
}
</style>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
  <script src="assets/js/html5shiv.js"></script>
  <script src="assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body>



<div class="container">
	<div class="form-group">
                <h4> Local time: </h4>
                <label id="lblTime" style=" font-weight:bold" class=""></label>
		<h4>Pick alarm time:</h4>
		<div class="clearfix">
			<div class="input-group clockpicker-yad data-placement="bottom" data-align="top" data-autoclose="false">
				<input type="text" class="form-control" value="">
				<span class="input-group-addon">
					<span class="glyphicon glyphicon-time"></span>
				</span>
			</div>
		</div>
	</div>
	
</div>


<script type="text/javascript" src="assets/js/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="dist/bootstrap-clockpicker.min.js"></script>
<script type="text/javascript">
$('.clockpicker').clockpicker()
	.find('input').change(function(){
		console.log(this.value);
	});
var input = $('#single-input').clockpicker({
	placement: 'bottom',
	align: 'left',
	autoclose: true,
	'default': 'now'
});

$('.clockpicker-yad').clockpicker({
		donetext: 'Done',
		init: function() { 
                        //Set current time +1 on init
                        var now = new Date();
                        var minute = (now.getMinutes()+1);
                        var hour = (now.getHours());
                        if (hour   < 10) { hour   = "0" + hour;   }
                        if (minute < 10) { minute = "0" + minute; }
                        var time = (hour)+":"+(minute) ;
                        $('input[class=form-control]').val(time);
		}
	})
	.find('input[class=form-control]').change(function(){
                var clock = "time set to: "+this.value;
		console.log(clock);
	});

// Manually toggle to the minutes view
$('#check-minutes').click(function(e){
	// Have to stop propagation here
	e.stopPropagation();
	input.clockpicker('show')
			.clockpicker('toggleView', 'minutes');
});
if (/mobile/i.test(navigator.userAgent)) {
	$('input').prop('readOnly', true);
}
</script>
 <script type="text/javascript">  
        // datetime make using jquery  
        $(document)  
            .ready(function ()  
            {  
                ShowTime();  
            });  
  
        function ShowTime()  
        {  
            var dt = new Date();  
            document.getElementById("lblTime")  
                .innerHTML = dt.toLocaleTimeString();  
            window.setTimeout("ShowTime()", 1000); // Here 1000(milliseconds) means one 1 Sec  
        }  
        </script> 
<script type="text/javascript" src="assets/js/highlight.min.js"></script>
<script type="text/javascript">
hljs.configure({tabReplace: '    '});
hljs.initHighlightingOnLoad();
</script>
</body>
</html>

In terminal (remember to change the uri):

stdbuf -oL -eL yad --html --print-uri --uri="/home/misko/Documents/clockpicker-gh-pages/yad.html" --no-buttons --width=800 --height=600 2>&1 | while read line ;do [ "$line" != ""  ] && echo "MSG: $line";done

Once the time is set, click "Done" and it writes out in terminal.

https://i.imgur.com/9MPc8lb.gif

Last edited by misko_2083 (2020-01-28 17:15:48)


Што ни оштровиди ум сагледати не може - љубав превазилази.

Offline

#56 2020-01-28 19:57:54

brontosaurusrex
Middle Office
Registered: 2015-09-29
Posts: 2,277
Website

Re: Alarm clock scripts

^Nice, so this should basically echo js console.log back to terminal/stdsomething?
(Can't make it work for some reason (./openwithyad), not getting anything back to term).

Last edited by brontosaurusrex (2020-01-28 20:39:01)

Offline

#57 2020-01-28 21:52:50

misko_2083
Member
Registered: 2016-05-24
Posts: 438

Re: Alarm clock scripts

brontosaurusrex wrote:

^Nice, so this should basically echo js console.log back to terminal/stdsomething?
(Can't make it work for some reason (./openwithyad), not getting anything back to term).

Yes, Developer Console thing that every web browser has.

Your script is working here.

Let's try without the line buffering.
Needed line buffering for a different method.
This one is simpler.

#!/bin/bash

actual_path=$(readlink -f "${BASH_SOURCE[0]}")
script_dir=$(dirname "$actual_path")

cd "$script_dir" || exit

yad --title="when" --uri="yad.html" --html --width=800 --height=600 --no-buttons 2>&1 \
| while read -r stuff
do
    [ "$stuff" == ""  ] && continue
    echo "$stuff"
done

Downloaded and unpacked, opened the terminal in the dir containing yad.html and then ./openwithyad

What yad version do you have?
yad --version
0.41.0 (GTK+ 2.24.25)


Што ни оштровиди ум сагледати не може - љубав превазилази.

Offline

#58 2020-01-28 22:59:06

brontosaurusrex
Middle Office
Registered: 2015-09-29
Posts: 2,277
Website

Re: Alarm clock scripts

yad --version
5.0 (GTK+ 3.24.5

But i build this, since Debian Buster is not having webkit enabled by default as it seems? The nonbufered version not working either. Must be a custom yad issue...

Last edited by brontosaurusrex (2020-01-28 23:01:35)

Offline

#59 2020-01-29 02:44:33

misko_2083
Member
Registered: 2016-05-24
Posts: 438

Re: Alarm clock scripts

Could be a bug somewhere.

console-test.html

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    console.log("Hello!");
  });
});
</script>
</head>
<body>

<button>Write Hello to console</button>

</body>
</html>

In terminal:

cat console-test.html | yad --html --height=400 --width=500

If that doesn't work, then yad probably has a bug.


Што ни оштровиди ум сагледати не може - љубав превазилази.

Offline

#60 2020-01-29 15:59:37

brontosaurusrex
Middle Office
Registered: 2015-09-29
Posts: 2,277
Website

Re: Alarm clock scripts

It doesn't work.

Offline

#61 2020-01-29 18:01:52

misko_2083
Member
Registered: 2016-05-24
Posts: 438

Re: Alarm clock scripts

It's definitely working here, and writing "Hello!" in the terminal.
Can I suggest a bug report and maybe include this short example?


Што ни оштровиди ум сагледати не може - љубав превазилази.

Offline

#62 2020-01-29 19:46:41

brontosaurusrex
Middle Office
Registered: 2015-09-29
Posts: 2,277
Website

Re: Alarm clock scripts

Offline

#63 2020-04-18 05:54:22

johnraff
nullglob
From: Nagoya, Japan
Registered: 2015-09-09
Posts: 7,901
Website

Re: Alarm clock scripts

Possible alternative to 'at' for those who can live with systemd is 'systemd-run'.
The man page is not so easy to understand, but eg this:
https://www.linux-magazine.com/Issues/2 … eztoc0_0_3
Web-searching might bring up more stuff.
Anyway this worked:

systemd-run --user --on-active=1m -E DISPLAY=:0.0 /home/john/bin/beepmein --reaction test

Although the --on-active time seemed a bit slack. I haven't worked on this at all though...


...elevator in the Brain Hotel, broken down but just as well...
( a boring Japan blog (currently paused), idle Twitterings and GitStuff )

Introduction to the Bunsenlabs Lithium Desktop

Online

#64 2020-11-30 12:32:07

jerry3904
New Member
Registered: 2020-11-30
Posts: 2

Re: Alarm clock scripts

Hi. I'm the Lead for the Fluxbox version of MX Linux, and wanted to tell the Community how much we liked and appreciated the timer posted by @damo at the beginning of this thread and developed further by contributions from @misko_2083 and others.

We have just finished developing it further and it now forms part of our optional mxfb-goodies (https://github.com/MX-Linux/mxfb-goodies). I believe that with minor changes to icon and alarm sound this will work for you, so am posting the new script in case you are interested. BTW: the localization for that is in progress ATM and should be up within a week when we release the new package.

#!/bin/bash
#!/bin/bash
#
# Timer script using YAD dialog
#
# Author: D.M-Wilhelm (Leiche)
# Email: meisssw01 at gmail.com
# Licence: GPL
# Original date: 2011
#
# Updated and tweaked by @misko_2083 and @damo, of the bunsenlabs community
# November 2019
#
# Modified and elaborated by MX Linux Devs for use with MX-Fluxbox
# November 2020 
# The sound file used here is located in the components folder
########################################################################
Encoding=UTF-8
#
# i18n - Internationalization
export TEXTDOMAIN=mxfb-timer
export TEXTDOMAINDIR="/usr/share/locale"

TITLE=$"MXFB Timer"
DIR1=$"Enter local time"
DIR2=$"or number and unit"
DIR3=$"Click \"Check...\" button to confirm time and date are correct"
DIR4=$"Click systemtray icon to cancel"
DIR5=$"Choose an audio file for the alert"
DIR6=$"Alarm sound now in use is"
DIR7=$"You need to choose a sound file"
DIR8=$"Exit sound test"
DIR9=$"You entered"
DIR10=$"Alarm clock was set to"
DIR11=$"Alarm will be at  "
DIR12=$"Left-click to quit, right-click for menu"
DIR13=$"Time is up"
MSG10=$"Setting"
#MSG11=$"Alarm will be at"
#MSG12=$"Left-click to quit, right-click for menu"
#MSG13=$"Time is up!"

QUIT=$"Quit"

TIME1=$"minutes"
TIME2=$"hours"
TIME3=$"days"
BUTTON1=$"Change sound"
BUTTON2=$"Test sound"
FIELD1=$"Enter alarm time"
FIELD2=$"Check time and date"


#
# define some variables
#
TITLE="MXFB Timer"
#ICON="/usr/share/icons/Moka/64x64/apps/time-admin.png"
ICON="/usr/share/icons/Papirus/64x64/apps/alarm-clock.svg"
#ICON="/usr/share/icons/Paper/48x48/apps/alarm-clock.png"
ICON2="/usr/share/icons/mxflux.png"
SOUNDFILE="/usr/share/sounds/bleep.wav"
#SOUNDFILE="/usr/share/sounds/freedesktop/stereo/alarm-clock-elapsed.oga"
#SOUNDFILE=/usr/share/sounds/Fresh_and_Clean/stereo/phone-incoming-call.ogg
export SOUNDFILE
# Choose whether to use YAD dialog or system notification for Alarm alert
ALERT="YAD_ALERT"
#ALERT="SYSTEM_ALERT"

win_class="timer_class"

### Check default icon and sound file ###
[[ ! -f "$ICON" ]] && echo "$ICON not found"
[[ ! -f "$SOUNDFILE" ]] && echo "Default soundfile, $SOUNDFILE, not found"

### Test for mpv player
#if ! hash mpv; then
#    echo "$0: mpv binary is missing. Please issue 'sudo apt-get install mpv'." >&2
#    exit 1
#fi

PLAYERLIST=(
   paplay
   mpv
   cvlc
)

export PLAY=""
for P in ${PLAYERLIST[@]}; do
    which $P >/dev/null || continue
    case $P in
         paplay) PLAY="paplay"; break
              ;;
            mpv) PLAY="mpv --no-video"; break
              ;;
           cvlc) PLAY="cvlc --play-and-exit --no-loop --no-repeat"; break
              ;;
     esac   
done

echo "PLAYER=$PLAY"

function playsound {
    local sound
    if [ -f $HOME/.config/mxfb-timer/alert ]; then
          sound=$(readlink -e "$HOME/.config/mxfb-timer/alert")
    else
          sound="$SOUNDFILE"
    fi
 
    echo "Running: playsound" >&2
    echo "$PLAY $sound" >&2
    $PLAY "$sound"
}
export -f playsound 
    	
 


# to transform entered allert time
# in addtion to date's --date="STRING"
# allowed formats 
# "NMMM"  or "N MMM"  or "+NMMM" or "+N MMM"
# where N is a number and MMM any out of: minutes, hours, days, weeks, month, years
# MMM can be abriavated down to one letter, except "month" down to "mo" 
# e.g.:
#  "1" = "+1 minute"
#  "1m +2d +3w 4mo" = "+1 minutes +2 days +3 weeks +4 month"
function transform {
	local alert="$1"
	echo "$alert" | sed -r \
	 -e '/[:-]/b' \
	 -e 's/[+]?([0-9]+)$/+\1 minute/' \
	 -e 's/[+]?([0-9]+)[[:space:]]*m(i(n(u(t(e(s)?)?)?)?)?)?[[:space:]]*/+\1 minutes /' \
	 -e 's/[+]?([0-9]+)[[:space:]]*h(o(u(r(s)?)?)?)?[[:space:]]*/+\1 hours /' \
	 -e 's/[+]?([0-9]+)[[:space:]]*d(a(y(s)?)?)?[[:space:]]*/+\1 days /' \
	 -e 's/[+]?([0-9]+)[[:space:]]*w(e(e(k(s)?)?)?)?[[:space:]]*/+\1 weeks /' \
	 -e 's/[+]?([0-9]+)[[:space:]]*mo(n(t(h)?)?)?[[:space:]]*/+\1 month /' \
	 -e 's/[+]?([0-9]+)[[:space:]]*y(e(a(r(s)?)?)?)?[[:space:]]*/+\1 year /'
}	
export -f transform	
	
	
	
	
function get_alert {
    local mode="$1"
    local time_entered="$2"
    local time_transformed=$(transform "$time_entered")
    local alert_min=""
    local alert_time="<invalid time>"
    echo "time_entered=$1" >&2
    echo "time_transformed=$time_transformed" >&2
    if [ -n "$time_transformed" ]; then
	    local sec_ent="$(date --date="$time_transformed" '+%s' 2>/dev/null)"
	    local sec_now="$(date '+%s')"
	    echo "sec_ent=$sec_ent" >&2
	    echo "sec_now=$sec_now" >&2
	    alert_min=$(( ($sec_ent - $sec_now)/60 ))
	    echo "alert_min=$alert_min" >&2
	    
	    if [ $alert_min -lt 1 ]; then
	       if [ $alert_min -gt $(( -24 * 60 )) ]; then
	          alert_min=$(( $alert_min +  24 * 60  ))
	          alert_time=$(date --date="+$alert_min minutes" '+%X %x')
	       else
	          alert_time="<invalid time>"
	          alert_min=""
	       fi
	    else
	       alert_time=$(date --date="+$alert_min minutes" '+%X %x')
	    fi
    fi
    echo "alert_time=$alert_time" >&2

	case "$mode" in
	      time) echo "$alert_time"
	          ;;
	      min*) echo "$alert_min"
	          ;;
	         *) echo "<invalid time>"    
	          ;;
	esac
	
}
export  -f get_alert


### main dialog ###
function menu {
    #change_title &
    
    COUNTDOWN=$(/bin/yad --class="${win_class}" \
					--title="$TITLE     ($(date '+%D -- %R'))" \
                    --window-icon="$ICON2" --center \
                    --text "
                    <b><i>1) $DIR1 (9:15pm, 13:50, 12am, etc.)  \n
                         $DIR2 (\"3 $TIME1\", \"12 $TIME2\", \"2$TIME2 + 30$TIME1\", etc.) \n
                    2) $DIR3 \n
                    3) $DIR4</i></b>
                    " \
                    --image="$ICON" \
                    --borders=15 \
                    --button="$BUTTON1:2" \
                    --button="$BUTTON2:bash -c 'playsound $SOUNDFILE'" \
                    --button="gtk-cancel:1" \
                    --button="gtk-ok:0" \
                    --height=180 \
                    --form  \
                    --align=center \
					--field "$FIELD1 ... :LBL" ""  \
					--field "$FIELD2 ...:FBTN" '@bash -c "echo 4:$(get_alert time %3)"' \
					--field "" \
					--field ' :RO' ""  "<not set>" \
					--columns=2 \
					)

    ret=$?
	IFS='|' read -r _ _ COUNTDOWN _ <<<$COUNTDOWN
    COUNTDOWN=$(get_alert minutes $COUNTDOWN)
   
    [[ $ret -eq 1 ]] && exit 0
    #
    ### Change sound dialog ###
    #
    if [[ $ret -eq 2 ]]; then
        CHANGE=$(yad --title="$TITLE" --window-icon=$ICON2 \
            --file --width=600 --height=500 --center \
            --button="gtk-ok:0" --button="gtk-cancel:1" \
            --filename="/usr/share/sounds/" \
            --text="\n\t<b>$DIR5</b>\n") 
    
            if [ -z "$CHANGE" ];then 
                menu
            else
                # check soundfile exists
                if [ -f "$CHANGE" ];then
                    mkdir -p "$HOME/.config/mxfb-timer"
                    rm -rf "$HOME/.config/mxfb-timer/alert"
                    sleep 1
                    ln -s "$CHANGE" "$HOME/.config/mxfb-timer/alert"
                    yad --title "$TITLE" \
                        --button="gtk-ok:0" \
                        --width 300 --borders=15 --center \
                        --window-icon="$ICON2" \
                        --text="\n$DIR6:\n\n<i>$CHANGE</i>"
                else
                    yad --title "$TITLE" \
                         --button="gtk-ok:0" \
                         --borders=15 --center \
                         --window-icon="$ICON2" --image-on-top \
                         --image="gtk-dialog-warning" \
                         --text="\t<big>$DIR7</big>"
    
                    exec mxfb-timer
                    exit
                fi
            fi
        menu        
    fi
    #
    ### Test sound dialog ###
    #
    if [[ $ret -eq 3 ]]; then
        if [ -f $HOME/.config/mxfb-timer/alert ]; then
            SOUND="$HOME/.config/mxfb-timer/alert"
        else
            SOUND="$SOUNDFILE"
        fi
        echo $PLAY "$SOUND"
        timeout 10 $PLAY "$SOUND"
         
        #$PLAY "$SOUND" | yad --title "$TITLE" \
        #                 --button="gtk-ok:0" \
        #                 --width 300 --center --borders=15 \
        #                 --window-icon="$ICON2" \
        #                 --text="\n\t...$DIR8"
#        killall mpv
         #pkill -xf "mpv --no-video $SOUND"
         #pkill -xf "$PLAY $SOUND"

        menu                 
    fi
}
menu
echo "COUNTDOWN: $COUNTDOWN"
[[ "$COUNTDOWN" == 1 ]] && MINS="minute" || MINS="minutes"

if [ -z "$COUNTDOWN" ];then
    exit
else
    echo $DIR9 "$COUNTDOWN $MINS"
    TIMER=$(echo $((COUNTDOWN*60)))
    TASK1=$(date --date="+$TIMER seconds" 2>/dev/null | cut -d " " -f5)
    temp=$(mktemp -u --tmpdir alarm.XXXXXXXX)
    
    mkfifo $temp
    
exec 3<> $temp

# TOOLTIP="\nAlarm clock was set to <big><b>$COUNTDOWN</b></big> $MINS \
#        \n\nAlarm will be at  <big><b>$TASK1</b></big> \
#        \n\nLeft-click to quit, right-click for menu"


COUNTDOWN_BIG="<big><b>$COUNTDOWN</b></big>"
TASK_BIG="<big><b>$TASK1</b></big>"

T_LINE_1="$DIR10 $COUNTDOWN_BIG $MINS"
T_LINE_2="$DIR11 $TASK_BIG"
T_LINE_3="$DIR12"

M_LINE_1="$DIR10 $COUNTDOWN $MINS"
M_LINE_2="$DIR11 $TASK1"

TOOLTIP="\n"
TOOLTIP+="$T_LINE_1\n\n"
TOOLTIP+="$T_LINE_2\n\n"
TOOLTIP+="$T_LINE_3"

timeout --preserve-status ${TIMER}m \
   yad --notification  --listen <&3 & _pid=$!
echo tooltip: "$TOOLTIP" >&3
echo "action:quit" >&3
echo 'menu:'"$M_LINE_1"'!true|'"$M_LINE_2"'!true|'"$QUIT"'!quit!gtk-quit' >&3
echo "icon:${ICON}" >&3

wait $_pid

    [[ $? -eq 0 || $? -eq 252 ]] && rm $temp && exit
    
    rm $temp
    exec 3>&-

#check which sound
#
    if [ -f "$HOME/.config/mxfb-timer/alert" ]; then
        SOUND="$HOME/.config/mxfb-timer/alert"
    else
        SOUND="$SOUNDFILE"  # use default soundfile
    fi

    if [ "$ALERT" == "YAD_ALERT" ];then
        ### Using YAD ##########
        ($PLAY "$SOUND") | yad --title "$TITLE" --undecorated --center \
                         --no-buttons --sticky --escape-ok --on-top \
                         --width 300 --image="$ICON" \
                         --window-icon="$ICON2" \
                         --borders=15 \
                         --timeout=3 \
                         --text="\n\t<big><b>$DIR13!</b></big>"
                         exit
    else
        ### Using notify-send ###
        mpv --no-video "$SOUND" &
        notify-send -i "$ICON" "$DIR13! "
        exit
    fi
fi

exit

Offline

#65 2020-12-02 14:45:05

misko_2083
Member
Registered: 2016-05-24
Posts: 438

Re: Alarm clock scripts

Welcome Jerry.
You blew my cover when you finally asked for that Russian translation, ha, ha. :-)
You thought I'm Russian because of the Cyrillic word in my yt chanel.
"Do you want me to write your name in Russian?" you asked, and I went along with it.
Technically, I never said I'm Russian and you never asked me that.
I only said that I don't want my name in Russian and inserted a few спасибо here and there.
My joke could have lasted a little longer... I was just planing to use word Vodka instead of the word Cool. :-D
I know only few words in Russian and quite a few stereotypes from the Hollywood films I could have used.
Cyrillic is used officialy in a dozen of countries and even more languages, 40 or more if I remember.

But enough of this welcoming to the forum and let's get to the script.
There is a number of improvements in your script.
I really like what Fredx181, Vovchik and others did with the script on the puppy linux (murga linux) forums.
The forum maintainer John Murga died and the forum went offline for a few months.
However, the forum was restored by the community and it was archived.
Somewhere in the Yad thread there is an alarm script with a better UI.
I think they even inserted a custom font into that script.
Oh, here it is http://www.murga-linux.com/puppy/viewto … &start=825


Што ни оштровиди ум сагледати не може - љубав превазилази.

Offline

#66 2020-12-02 14:56:56

jerry3904
New Member
Registered: 2020-11-30
Posts: 2

Re: Alarm clock scripts

Glad to *see* you again, misko! Thanks for the reference--I wasn't aware of that version and will take a look the next time the mood hits me to look at this.

I should point out for everybody here that misko helped us greatly in our effort to resuscitate and rework iDesk and its GUI, which now functions well and is much more accessible to regular users.

Offline

#67 2020-12-04 10:00:23

misko_2083
Member
Registered: 2016-05-24
Posts: 438

Re: Alarm clock scripts

jerry3904 wrote:

should point out for everybody here that misko helped us greatly in our effort to resuscitate and rework iDesk and its GUI, which now functions well and is much more accessible to regular users.

Well the choice was between that and solving sudoku puzzles. :-D
Ever since the lockdown sudoku seems more attractive.


Што ни оштровиди ум сагледати не може - љубав превазилази.

Offline

Board footer

Powered by FluxBB