Can you say that again, Mr. Alarm?

While using my Hourglass app for Android phones, a user made an interesting observation:

Hi
I love this open source app and using it quite often. But sometimes my phone is in my pocket and I’m listening to music and I miss the time ended notification ! The vibration is short, easy to miss, same thing for the notifications sounds. I’d find “logical” to have a continuous notification that vibrates and rings until I manually stop it (from notification bar or inside app).
Is this feature planned for a future release ?
Thanks

What a great idea! I’m glad that “bruneton” opened this issue on my issue tracker. That’s part of the beauty of open source. Sure, closed source programs could take input as well, but the open source community encourages and enables it, as well as giving others the code so that they can make changes themselves!

So, I added another button:

time_up

And with that button, some new code, which you can check out in full from the commit on my GitLab, but here is the gist of it:

– // Cancel the notification.
 – mNotificationManager.cancel(0);

 – // Set the time bar back to usable.
 – timeBar.setEnabled(true);
 + if (alreYes) {
 +
 + startCount(2000,1000);
 +
 + } else {
 + // Cancel the notification.
 + mNotificationManager.cancel(0);
 +
 + // Set the time bar back to usable.
 + timeBar.setEnabled(true);
 + }

What we have here, is a repeating timer that, if the continuous alarm is set, will “repeat” by resetting the countdown to 2 seconds, over and over again, until you cancel the repeating alarm!

It seems to work well so far, but I think I can do better. So, I’m looking at adding a “Stop” or “Cancel” option to the notification pop up. We’ll see, but for now, it does repeat rather nicely!

Linux – keep it simple.

Advertisements

Adding a countdown timer to my Android notification….

This was actually a great idea brought up by a user, and posted in my issue tracker for the Hourglass app. He pointed out that it would be really handy to have the remaining time posted in the notification popup, and get it to be consistently updated.

I thought there must surely be something for this in Android already, but I couldn’t find one. However, I did find a chronometer that can count how long a notification has been open. With some careful thought, here is what I came up with:

NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
        .setSmallIcon(R.drawable.hourglass).setWhen(System.currentTimeMillis()+recureTime).setUsesChronometer(true)
        .setContentTitle("Hourglass").setContentText(intentPhrase);

What I found was that I could “back up” time to before the notification started. Essentially giving it a negative number. Then, passing the time saved for recurring alarms (even saved if not used), then I can set it to a negative of that number. Now it counts “up” from negative time, giving the appearance of counting down your timer!

timer_notification

Works pretty well, however, 2 interesting things. I would have thought the code should be MINUS recureTime, not PLUS recureTime, but it only works properly with PLUS.

Second, the “countdown timer” in the notification doesn’t track exactly with the Hourglass app timer. In the course of several minutes, it becomes off by a second. Odd, but workable. The timer still goes off in the app on time, just that the countdown in the notification may get there a second early.

Linux – keep it simple.

Fool’s Mate Friday: Where to, Governor?

Today’s update is pretty basic. Just cleaning up and filling in some blanks on my JustChess app. While I wont bore you with the whole commit, you are welcome to check it out.

jc9

Basically, I just added an about and settings page. Both pages are pretty basic, but the settings page does have a cool star strength indicator for the computer engine strength. I thought it wise to add it so people could play against the JustChessEngine at lower strengths. It seems a bit funny, since it is currently so weak that I doubt this would be needed. However, it seemed to me, that when making a full fledged app of this sort, one would include some sort of slider or adjustment for the engine strength, so there it is.

This does beg the question of where to go next. As is, my goal was to learn more app making skills and increase my java strength by creating a chess app in which I made my own engine, and one that you could play against a person or a computer. To God be the glory, this app has met that goal. With pass’n’play mode, you could play a friend in a room, or with single player, you can play as black or white against your phone.

But the road forks here.

On the one hand, I could pursue the avenue of making the game playable with someone who was not in the same room, via email, text, online server (parse comes to mind, as I set one of those up for a different app). On the other hand, I could focus on the engine and try to make it stronger.

And yet the road forks again….

One of the big problems is that of programming language. As I delve deeper and deeper into java, I have found only one place that it is applicable, Android. As I’m sure you have seen from my blog, I’ve switched to using Ubuntu Touch on my phone. But Ubuntu Touch doesn’t support java naively (or perhaps at all). As I continue to apply time to learning java, I continue to limit myself to just one application. Perhaps it would be better to learn c++, java-script, or some other language that has a broader application?

So, I sit at the cross roads. What to do next? Hopefully I can figure it out before the next Fool’s Mate Friday!

Linux – keep it simple.

Fool’s Mate Friday: Check or Stale Mate?

Apparently, in 1988, World Champion Gary Kasparov accidentally stalemated his opponent during a blitz tournament in Canada. Mr. Kasparov had a king, queen, and a bishop against Kiril Dimitrov Georgiev’s lone king. The problem Mr. Kasparov was facing was that of time running out. In his efforts to move quicker, he forced a stalemate when he had every advantage and reason to win!

I will probably never be as great as Mr. Kasparov, so I certainly mean no disrespect when bringing this up. My point being is that even world champions can stalemate. How does this apply to my JustChess app? Well, it seems to me that it is pretty important to clarify when the opponent can’t move, if they are in stalemate, or checkmate.

Fortunately, I figured out how to do just that.

jc8

The code wasn’t particularly grueling, it turned out the hard part was figuring out the order of play for pass and play verses playing against the computer. The time which you need to look for a checkmate or stalemate actually changes between those two. Here’s the important snippet, but as always, you can check it out on my GitHub.

    moveOptions="";
    if (!wTurn){
        moveOptions= terminal("suggestMove,black");
    } else {
        moveOptions= terminal("suggestMove,white");
    }
    if (moveOptions.isEmpty()) {
        staleOrCheckMate();
    }

} // End clicked piece.

public void staleOrCheckMate() {
    String status = terminal("checkmate");
    if (status.equalsIgnoreCase("1")) {
        status = "checkmate!";
    } else {
        status = "stalemate!";
    }
    String turnIs = "";
    if (wTurn) {turnIs="White is in ";} else {turnIs="Black is in ";}
    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setTitle(turnIs + status)
            .setMessage(
                    "Would you like to play a new game?")
            .setPositiveButton("View Board", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    // Do nothing.

                }
            })
            .setNegativeButton("New Game", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    // First you define it.
                    Intent myintent = new Intent(MainActivity.this, IntroActivity.class);
                    myintent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    // Now you call it.
                    startActivity(myintent);

                }
            })
            .show(); // Make sure you show your popup or it wont work very well!

}

The longest part of this project was actually testing it against the computer! It’s easy to checkmate it right now, but I found it was a pesky bugger to stalemate! Be sure to give it a try, my GitHub has all of the updates of the app already built for you to download and test out!

Linux – keep it simple.

Fool’s Mate Friday: Suggestions, anyone?

Well, more specifically, suggestions, computer?

One of the cool things about having the built in JustChessEngine in my JustChess app, is the option to have the engine suggest a move for you. Of course, my engine has an elo rating below 300, so I’m not sure that I would take it’s advice, at least not yet. In any event, I thought it might be handy to have a button to suggest a “good” move.

jc7

You may also note that the GUI got cleaned up a bit in previous commits.

Adding the code for this was fairly easy. I already had the text at the bottom of the screen updating when you clicked on a piece, I sort of just changed that into making a query of the next “best” suggested move. Interesting to note, that this best move is based on the engine strength of 1, rather than of the strength you chose to play against.

At this point it is more or less just showing you a valid move that gains you some points on it’s own scale of value. It is not a very good at tactics.

In either event, here was the most important part of the code:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        moveOptions="";
        if (!wTurn){
            moveOptions= terminal("suggestMove,black");
        } else {
            moveOptions= terminal("suggestMove,white");
        }

        try {
            if (moveOptions.equals("K-0-0R,")) {
                chessImage[6].setBackgroundResource(R.drawable.suggested);;
            } else if (moveOptions.equals("K0-0-0,")) {
                chessImage[2].setBackgroundResource(R.drawable.suggested);;
            } else if (moveOptions.equals("k-0-0r,")) {
                chessImage[62].setBackgroundResource(R.drawable.suggested);;
            } else if (moveOptions.equals("k0-0-0,")) {
                chessImage[58].setBackgroundResource(R.drawable.suggested);;
            } else {
                String temp = String.valueOf(moveOptions.charAt(3)) +
                        String.valueOf(moveOptions.charAt(4));
                int highlightThis = Integer.parseInt(temp);
                chessImage[highlightThis].setBackgroundResource(R.drawable.suggested);
                temp = String.valueOf(moveOptions.charAt(1)) +
                        String.valueOf(moveOptions.charAt(2));
                highlightThis = Integer.parseInt(temp);
                chessImage[highlightThis].setBackgroundResource(R.drawable.suggested);
            }

        } catch (Exception e) {
            // Do nothing.
            Log.i("WJH", e.toString());
        }

        Snackbar.make(view, "JustChessEngine suggests: "+ moveOptions, Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
    }
});

I just edited the snack bar to pop up with the suggested move, and had the board highlight the squares green for it as well. The green squares clear when you make a move, weather it be the one suggested, or some other one. You can see the full commits and how I overcame the king castle suggestion problems on my GitHub.

Linux – keep it simple.

Fool’s Mate Friday: That move was the highlight of the game!

There were several computer GUI systems invented already, but the first (to the best of my knowledge, correct me if I’m wrong) computer GUI that would highlight your move options after selecting a piece was that of “Daly CP”. It was a computer chess interface written for the IDIIOM CAD computer, which was a computer that had a stencil and was used for Computer Aided Design of parts in manufacturing processes. The program was written by Chris Daly, who worked for NASA, and it was used for several tournaments against other computers, as well as against people.

I wanted my JustChess game to highlight the available moves of any piece that you tapped on, similar to what you see in the Daly CP program. Now, every time that you tap on a piece, it’s legal moves are highlighted for the user. This works for both your pieces, and that of your opponent. The process is simple to implement, but lengthy in explaining it here. The whole commit can be viewed on my GitHub, though.

The key problem that I ran into was that of castle moves. The way I was working this was to discern from a query of possible moves for a piece, all of the “to” positions, and to simply change the background color of those tiles. However, castle moves are “k0-0-0”, and “K-0-0R”, etc., as opposed to a standard move, which looked like “P0816*” (Pawn from square 8 to square 16, which is empty – *), from which I was just stealing the 3 and 4 character (remember, computers count the first character as a 0), and parsing an integer. That integer was then used to change the background tile of the corresponding number on the board.

To solve this I used a little trickery with an if/then statement inside of a try/catch block. Essentially saying, “try this: if it is one of these king castle moves on the list, then highlight x square, if not, then use the normal method.” It seems to have worked quite well. The great thing is, you can test it out for yourself now! That’s right, I’m releasing JustChess, version 1.0 for download. So give it a try and let me know what you think!

Do keep in mind, it has a long way to go, but is currently completely playable against the phone, or in pass and play two player mode.

Linux – keep it simple.

JustNotes – when your notes are too long to read!

A user of my open source app, JustNotes, made an interesting observation… if your note gets too long, you can’t read it because it goes below the keyboard and you can’t scroll it upward. You can read the bug tracker issue on my GitHub for the full story. This is a really great point. I guess I had always thought of using this app for small, short notes, but it is conceivable to make a list or note that was longer than the top half of your screen.

Fortunately, I’ve progressed a bit in my programming skills since then, so I was able to fix it in about ten minutes. Essentially, I just added a scroll field for the text, like so:

justnotes_gif

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_writenote"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.alaskalinuxuser.justnotes.writenote"
    tools:showIn="@layout/activity_writenote">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top|center"
        android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inputType="textMultiLine"
        android:ems="10"
        android:gravity="top|left"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/multiTextView" />

    </LinearLayout>
    </ScrollView>

</RelativeLayout>

As you can see, I just implemented a ScrollView around the LinearLayout. Simple. Functional. Just the way I like it!

Linux – keep it simple.

Fool’s Mate Friday: En passant checkmate!

According to legend, Gary Kasparov once checkmated via en passant in an on-line game. However, I couldn’t actually find a detailed reference to that specific game. I was, however, able to find an article that expressed the only officially logged game in which an opponent was check mated via en passant. It was a game between Gunnar Gundersen and A H Faul during a Christmas tournament in 1928. Here was the move list:

1.e4 e6 2.d4 d5 3.e5 c5 4.c3 cxd4 5.cxd4 Bb4+ 6.Nc3 Nc6 7.Nf3 Nge7 8.Bd3 O-O 9.Bxh7+ Kxh7 10.Ng5+ Kg6 11.h4 Nxd4 12.Qg4 f5 13.h5+ Kh6 14.Nxe6+ g5 15.hxg6# 1-0

enpassantcheckmate

Certainly an interesting prospect. In this case, the en passant move doesn’t actually check the king, but prevents the king from retreating from the now discovered check of the rook. In any case, en passant is a very important part of playing chess, which makes it all the more vital that I fix it in my JustChessEngine and make it usable in my JustChess game.

The fix was not an easy one, but it came down to a few mathematical errors on my part, as well as a huge technical oversight. The program used to work like this:

If doing en passant for white:

place pawn to new square (+7 for right/up, and +9 for left/up). Remove taken pawn.

However, it would end up with two white pawns and remove the attacked pawn. So I edited it to be proper, like so:

If doing en passant for white:

place pawn to new square (+9 for right/up, and +7 for left/up). Remove taken pawn. Remove pawn from old square.

So, both the math was wrong on which side to go to, but also the pawn was never “removed” from it’s old square, just a new pawn was placed where it was going to! The fix was simple in principle, complex in actuality, but you can view the whole set of changes here: https://github.com/alaskalinuxuser/app_JustChess/commit/3053591df42473577e557b860ad639485841051f

I’m just glad it’s finally fixed!

Linux – keep it simple.

Fool’s Mate Friday: Is the King safe from pawns?

Pawns can be scary things. They can en passant, they can form chains and islands, they can promote to the all powerful queen. Not to mention they can checkmate you. That’s right. Even Magnus Carlsen has been checkmated by a pawn (vs. Tal Baron)*. So, if the current world chess champion can get the ax from a pawn, I, being far, far, far (add a few more far-s in there) lesser player, should watch out for them too.

On that note, while testing out my now playable JustChess app, I’ve come to realize a major blunder in the programming! A blunder in regards to my pawns when it comes to king safety! By complete accident, rather than say that a pawn is a threat when forward and diagonal of you, I made pawns life threatening to the king when abreast him!

pawnsafety

Don’t worry, though, I fixed it with this commit. Essentially, I had to change 4 lines, and move the pawn problem from row +/-1 to +/-7 and 9. Now the king can move appropriately when responding to pawns.

// King check // Don't move next to another king! // Also includes pawns.
if (h < 7 ) {
    if (theBoard[z+8]=='k') {
        return false;}
    if (g > 0) {
        if (theBoard[z+7]=='k' || theBoard[z+7]=='p') {
            return false;}}
    if (g < 7) {
        if (theBoard[z+9]=='k' || theBoard[z+9]=='p') {
            return false;}}}
if (h > 0 ) {
    if (theBoard[z-8]=='k') {
        return false;}
    if (g > 0) {
        if (theBoard[z-9]=='k') {
            return false;}}
    if (g < 7) {
        if (theBoard[z-7]=='k') {
            return false;}}}
if (g > 0) {
    if (theBoard[z-1]=='k') {
        return false;}}
if (g < 7) {
    if (theBoard[z+1]=='k') {
        return false;}}
// End white king is safe.

Linux – keep it simple.

* Some imply Tal Baron may have cheated to win this game. This was brought to my attention, so I added the link above for explanation. I’m not sure, I don’t know the man, and have no desire to in any way slight his character. In any event, Mr. Carlsen lost by checkmate to a pawn, either from Mr. Baron or an engine, and most likely Mr. Baron, due to the blitz game being less than 3 minutes. My point in this article still proves true: pawns are dangerous!

Ubuntu Touch: Make your own Jabber/XMPP app in 10 minutes…

You probably think that I’m joking, but I’m not. You can actually build a jabber/xmpp app in less than 10 minutes if you have a good internet connection, and have already set up your system with “clickable”. If not, be sure to check out my last post about it.

Are you ready to get started? Okay, here we go!

The magic that makes this work is that someone (or rather a group of someones) has already made a javascript xmpp client called convers.js. Head over to their website (https://conversejs.org/) and download it, or more directly, just click here: https://github.com/conversejs/converse.js/archive/v3.3.4.zip

Now jump over to your downloads folder and unzip it, or extract it if you grabbed the tar version. Great job, we are 20% done!

Open up your terminal and start typing:

$ mkdir xmmpapp
$ cd xmmpapp/
$ clickable init
Available app templates:
[1] pure-qml-cmake – Pure QML App (built using CMake)
[2] cmake – C++/QML App (built using CMake)
[3] python-cmake – Python/QML App (built using CMake)
[4] html – HTML App
[5] webapp – Simple Webapp
Choose an app template [1]: 4
Generating new app from template: HTML App
You’ve cloned /home/alaskalinuxuser/.cookiecutters/ut-app-html-template before. Is it okay to delete and re-clone it? [yes]: yes
Cloning into ‘ut-app-html-template’…
remote: Counting objects: 28, done.
remote: Total 28 (delta 0), reused 0 (delta 0), pack-reused 28
Unpacking objects: 100% (28/28), done.
Checking connectivity… done.
title [App Title]: xmppapp
description [A short description of your app]: xmpp app.
app_name [appname]: xmppapp
app_full_name [appname.yourname]: xmppapp.alaskalinuxuser
version [1.0.0]: 1.0.0
maintainer_name [Your FullName]: Alaskalinuxuser
maintainer_email [email@domain.org]:
Select open_source_license:
1 – GNU General Public License v3
2 – MIT license
3 – BSD license
4 – ISC license
5 – Apache Software License 2.0
6 – Not open source
Choose from 1, 2, 3, 4, 5, 6 [1]: 5
Your new app has been generated, go to the app’s directory and run clickable to get started
$

All we did was make a directory, run clickable, and choose to make a html app. Notice that this is not a web-app, which is basically a shortcut to some web site. This app is all on the users phone and just opens up an html file. We are now 40% done!

Open up your file manager. Find the downloads folder with your extracted convers.js files. In my case it is ~/Downloads/c/converse.js-3.3.4. Be sure to be in the folder, so you see the files like dev.html. In another tab or window, open up the place that you made your new app, in may case it is ~/ubports_apps/xmmpapp/xmppapp. Be sure to be in this folder so that you see the www folder.

Open the www folder, and drag all of the contents of the converse folder into it. It will ask you if you want to overwrite index.html, say yes. You are 60% done! Five minutes down, five minutes to go!

Now back to you (hopefully) still open terminal. You should still be in the folder outside of the folder of the app you just made. Change directory to your app, like so:

$ cd xmppapp/
$ ls
clickable.json manifest.json www xmppapp.desktop
LICENSE README.md xmppapp.apparmor
$

Typing the ls command should show the same files I have, if you named the app the same as I did. Plug in your phone and be sure developer mode is enabled with Settings->about->Developer mode. You are 80% there!

All you have left to do is type:

$ clickable

 

Copied files to temp directory for click building
Successfully built package in ‘./xmppapp.alaskalinuxuser_1.0.0_all.click’.
3724 KB/s (3190648 bytes in 0.836s)
Installing files [=========================]
Finished [=========================]
Installing files [=========================]
Starting [=========================]
Finished [=========================]
Installed xmppapp.alaskalinuxuser-1.0.0.all (installed:click,removable=1,app_name=xmppapp) summary goes here
$

And you are 100% done! If all went as well as it did here, you should see this:

And now you can start jabber-ing! Obviously, you need an account somewhere. Currently, with this setup, you are using conversjs.org’s BOSH server, and you can connect to your xmpp server. However, this should only be done for testing purposes.

To really utilize this app, you should set up your own BOSH server, and perhaps your own XMPP server. I use ejabber2, so it is an XMPP server and a BOSH server all in one. In the index.html file is this line:

bosh_service_url: ‘https://conversejs.org/http-bind/&#8217;,

which should point to your BOSH server. But for testing purposes, the above line works flawlessly. Just recognize that since you are borrowing their BOSH server, it may be down at their leisure, or they can give your sessions the boot if they so desire.

As is, this app will run a non-encrypted conversation with no issues at all. Encryption does work, but it seems a bit funky. I was able to have one successful encrypted conversation, and two that were failures at encrypting. One other issue is that when you close the app, your encrypted “tunnel” ends, so you need to re-establish encryption after that, and I think you have to make sure that the other user turns off encryption so you can re-encrypt with them again.

Big thanks to the convers.js team for making such a great java script that we could drop into our app!

Linux – keep it simple.