Creating a dynamic theme for Windows 7

If you want only the juicy part of this article, install the theme here

Windows 7 comes with a pretty neat theme manager, in which you can make your computer switch between a number of wallpapers on your drive or choose a theme you downloaded from Microsoft’s site (which comes with their own wallpapers too).

That’s fine enough if you have a lot of wallpapers and is okay with seeing about 10 different walls repeating from day to day… I don’t. That’s why I liked Bing Dynamic theme the most. What made this theme unique is, it fetches fresh wallpaper from Microsoft’s server everyday. This way I don’t have to see the same wallpapers over and over, and I don’t have to download the wallpapers first either. In case you didn’t know, downloading wallpapers is a tedious task:

  • It took at least two clicks from the wallpaper’s page to download the wallpaper you want (click download, choose the size).
  • You have to do this to each wallpaper you like.
  • You must have seen the wallpaper first, which ruins the surprise element.

The dynamic theme fixed those problems, you don’t have to do any browsing. The downside is, there’s only one such dynamic theme, and you can’t decide on the images. First, let’s have a look at the interesting part in the theme’s content (you can view the theme by opening it with notepad)

[Slideshow]
Interval=1800000
Shuffle=1
RSSFeed=http://themeserver.microsoft.com/default.aspx?p=Bing&c=Desktop&m=en-US
[boot]
SCRNSAVE.EXE=

You can see this theme fetches data from Microsoft’s server. It’s kinda RSS, but somewhat non-standard, Windows reads the enclosure element for the wallpaper instead of the link element like the standard (Microsoft loves breaking standards, this is why Internet Explorer is so hated among web developers).

Standard image RSS from NASA

<image xmlns:java_code="xalan://gov.nasa.build.Utils1"> 
    <url>http://www.nasa.gov/images/content/491481main_2010-5278-4x3_516-387.jpg</url> 
    <title>A Break in Training</title> 
    <link>http://www.nasa.gov/multimedia/imagegallery/index.html</link> 
    <description/> 
</image> 

Microsoft’s feed

        <item>
            <guid>Pipefish1920x120010-19-2010 7_57_11 PM3ed6bc33-88cb-4872-8097-5077cb6ad1a5</guid>
            <title>Pipefish1920x120010-19-2010 7_57_11 PM</title>
            <link ref="http://themeserver.microsoft.com/themeserver//Bing/Desktop/en-US/Images/Pipefish1920x120010-19-2010 7_57_11 PM.JPG" />
            <enclosure url="http://themeserver.microsoft.com/themeserver//Bing/Desktop/en-US/Images/Pipefish1920x120010-19-2010 7_57_11 PM.JPG" type="image/JPG" />
            <description>Picture for Bing, Desktop, en-US Theme.</description>
            <pubDate>10/19/2010 7:57:11 PM</pubDate>
        </item>

Actually, I think some engineer at Microsoft got mixed up between RSS (<item>) and Atom (<image>, <enclosure>) and created such an embarrassing feed. So you can’t just feed images from your favourite sites (like, cat images from flickr) right to your desktop.

Thankfully, we have just the tool for that: Yahoo pipes. It takes information from somewhere on the internet, transform it according to your specification, and is capable of exporting through RSS, JSON or PHP code.

So, I wanted to create a theme with images fed from xkcn.info (an image site about Vietnamese girls :p), I took the feed, feed it into the pipes. The pipes is a bit hard to use, because it cannot convert a XML element into string and vice versa, so you can’t just parse those neatly formatted elements but instead have to rely on the power of regular expression.

The pipe

  1. The first block fetches the feed
  2. The second block copy the data we need so we don’t mess up with existing stuff
  3. The third block removes all the text from the description and leaves only the first <img> tag
  4. The fourth block build a RSS feed formatted according to Microsoft “standard”

You can view the pipe here, and the RSS output of the pipe is here. So now all that remain is copy the Microsoft theme over, replace the feed URL and voilà, a more and more beautiful desktop everyday 😉

Desktop fully fed 😉

Download the theme here.

I have also created a Flickr-fed pipe and theme. To customize, clone the pipe, change it according to Flickr’s feed specification , modify the address in the theme to your pipe’s RSS output and you are set to go!

JSudoku

Yet another Sudoku program

Main interface

Down to the basics, here’s what I did:

  1. Generate the whole board with backtracking, randomizing the number I chose at each step and remember the choice, this assures that the board is random, while still keep the algorithm run in an acceptable time (it doesn’t have to regenerate a long track of numbers if it get into some sticky situation). Sudoku board have to keep up with a number of rules that make up a complex vector class, lost in there and you’re done. The other method to generate the board was to swap the rows/column/numbers, it’s safe and much faster but it took more time to implement, and it generates only a subclass of the possible Sudoku class, but it’s a good choice if you don’t want recursive calls in your program.
  2. Difficulty: I implemented a simple, but it’s not good for real application, I think. A good difficulty implementation should have taken humans’ deduction rules into consideration (you should know what are these these if you’ve played Sudoku before), and the algorithm should also make sure that with the given cells, only one solution is possible, this is a continuous generate-remove-check for solutions-remove loop and it’s complex to implement. So, I have only removed a number of cells based on difficulty, the more difficulty chosen, the less given cell there are. This implementation suffers from the above points.
  3. Build a usable Sudoku class’ interface: I deducted from coding that you need to store both the solution and the playing board in the class, provide board and solution get method, the set move method for the board should only accept valid moves, this way you only need to count the number of moves played to know if the player have won or not. This has the drawback that you can’t store invalid values in the board (to visually notify the player of their wrong moves), but it keeps your code clean of unnecessary checks.
  4. Build the interface: If you choose to manually generate the JFrame, JButton and uses a loop to create JTextField, it saves time to point-and-click creating the cells, but you will have to manually calculate the button and frame’s position to get a nice interface; the other way around, you’ll have to create JTextFields 81 times. I choose a hybrid approach: use the designer to design the form, add a JPanel to it, and then add the JTextField in the user interface’s constructor.
  5. Just for kicks: I add a key press handler into the text fields, the handler catches input, and if it’s not a valid number, not correct according to Sudoku rules or some other reason, the cell will be highlighted so the user can see it easily, the hint function is implemented in this way too: it compares what the user have to the solution and highlight the differences.

Creating text fields

    /** Creates new form SudokuInterface */
    public SudokuInterface() {
        initComponents();

        // Automatically arranges the cells into a grid-like layout
        jPanel1.setLayout(new GridLayout(Sudoku.ROWS, Sudoku.COLUMNS));
        fields = new JTextField[Sudoku.ROWS * Sudoku.COLUMNS];
        for (int i = 0; i < Sudoku.ROWS * Sudoku.COLUMNS; i++) {
            fields[i] = new JTextField(1);
            fields[i].setSize(66, 66);
            fields[i].setFont(cellFont);
            fields[i].setName(Integer.toString(i));
            fields[i].addKeyListener(cellInputHander);
            fields[i].setHorizontalAlignment(JTextField.CENTER);
            fields[i].setEnabled(false);
            jPanel1.add(fields[i]);
        }

        // First screen
        String intro = "JSudoku";
        for (int i = 1; i < intro.length() + 1; i++) {
            fields[4 * Sudoku.ROWS + i].setText(intro.charAt(i - 1) + "");
        }

    }

Handling key input

    private final KeyListener cellInputHander = new KeyListener() {

        /**
         * Controls, the user's input, let them input invalid data and display it
         * to avoid confusing the user (higher usability), but this won't be
         * reflected in the actual game, we have to keep track of which cells are
         * invalid, resulting in this complex implementation
         */
        public void keyTyped(KeyEvent e) {
            e.consume();
            int move = 0;
            String moveString = e.getKeyChar() + "";
            try {
                move = Integer.parseInt(moveString);
            } catch (Exception exception) {
                return;
            }
            // If the move is invalid, do nothing, the key won't appear
            int cellIndex = Integer.parseInt(e.getComponent().getName());
            if (!game.set(cellIndex, move)) {
                ((JTextField)e.getSource()).setForeground(cellIncorrectForeground);
                jLabel3.setText("You have just performed an invalid move");
                isInvalid[cellIndex] = true;
            } else {
                ((JTextField)e.getSource()).setForeground(cellEnabledForeground);
                jLabel3.setText("");
                isInvalid[cellIndex] = false;
            }
            ((JTextField)e.getSource()).setText(moveString);
            if (game.won()) {
                JOptionPane.showMessageDialog(rootPane, "You have solved the puzzle!", "Congratulation", JOptionPane.INFORMATION_MESSAGE);
                newGame(lastDifficulty);
            }
        }

        public void keyPressed(KeyEvent e) {

        }

        public void keyReleased(KeyEvent e) {

        }
    };


Like I said, there’s plenty of room for improvement, so here’s the source code if you want to do just that 😉