TweetFollow Us on Twitter

A Dashboard Widget that Reads and Saves its Preferences

Volume Number: 24
Issue Number: 10
Column Tag: Dashboard Widgets

A Dashboard Widget that Reads and Saves its Preferences

Create a Dashboard Widget that can save and read data after restarting it.

by Mihalis Tsoukalos

Introduction

In this article I am going to illustrate how to create a Dashboard Widget that saves its preferences. After saving the preferences, you will learn how to read and use the saved information and display the selected data in the front side of the Widget. The name of the Widget is "Save Prefs".

The files that compose the Widget

Figure 1 shows the files of the Widget as well as their sizes (in bytes).


Figure 1: The files that compose the "Save Prefs" Widget.

As you can understand by looking at Figure 1, the "Save Prefs" Widget is relatively simple. You should notice that it has a directory -the AppleClasses directory- that contains three JavaScript files. Apple provides the contents of the AppleClasses directory and the only thing that you should do is to copy the three JavaScript files inside your Widget's directory.

Also, as you will see in the next section, you will have to include them in the main HTML file of your Widget. Source code for this project can be downloaded from ftp.mactech.com/src/mactech/volume24_2008/24.10.sit. The source archive contains the following files:

SavePrefs.html file

SavePrefs.js file

SavePrefs.css

Info.plist

You may think that the SavePrefs.js JavaScript file contains a lot of code but most of the code is typical when creating a Dashboard Widget. The showPrefs() and hidePrefs() functions are used for watching and hiding the back side of the Widget and you usually have to copy and paste their definitions to your new Widgets.

The SavePrefs.css file

The CSS file looks pretty simple. Nevertheless, if you make small mistakes to the CSS code the Widget may misbehave very badly! I am saying this because I had some problems with the #OptionPopup declaration. Due to my wrong declarations the option list was displayed outside of the Widget area and I could not see it at all!

The Info.plist file

The Info.plist file is pretty simple and is as follows:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BackwardsCompatibleClassLookup</key>
<true/>
<key>CFBundleDisplayName</key>
<string>Save Prefs</string>
<key>CFBundleIdentifier</key>
<string>com.mtsouk.widget.saveprefs</string>
<key>CFBundleName</key>
<string>Save Prefs</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>CloseBoxInsetX</key>
<integer>14</integer>
<key>CloseBoxInsetY</key>
<integer>16</integer>
<key>MainHTML</key>
<string>SavePrefs.html</string>
</dict>
</plist>

Explaining the Technique

The presented technique uses the following two JavaScript methods:

  • widget.preferenceForKey(keyName): This method tries to read the value of a key, if the value is already saved.
  • widget.setPreferenceForKey(value, keyName): This method sets the value of a key. The Dashboard Reference suggests that you should pass null in order to delete an existing key.

Apple suggests that you utilize the widget.preferenceForKey(keyName) function using the following practice:

   if(window.widget)
   {
       var optionString = widget.preferenceForKey("optionString");
       if (optionString && optionString.length > 0)
       {
           optionText.innerText = optionString;
       }
   }

Similarly, Apple suggests that you use the widget.setPreferenceForKey(value, keyName) function as follows:

   if(window.widget)
   {
       widget.setPreferenceForKey("Hello MacTech!","optionString");
   }

A word of advice: The described method stores strings without any encryption. It is therefore not a secure way to store your sensitive information.

The following lines of JavaScript code declare two global variables, called glassDoneButton and whiteInfoButton, respectively. Each of the two variables holds one button. The first declaration creates the done button whereas the second declaration creates that little info (i) button that you frequently see in Widgets.

   var glassDoneButton;
   var whiteInfoButton;

The following JavaScript code implements the two button definitions:

   glassDoneButton = new AppleGlassButton(document.getElementById("doneButton"),
            "Done", hidePrefs);
   whiteInfoButton = new AppleInfoButton(document.getElementById("infoButton"),
            document.getElementById("front"), "white", "white", showPrefs);

The following command line output text explains where Dashboard keeps the Widget stored information using the described method:

mtsouk$ ll ~/Library/Preferences/widget-com.mtsouk.widget.saveprefs.plist
-rw————
    1 mtsouk   mtsouk         98 May 18 22:13
    /Users/mtsouk/Library/Preferences/widget-com.mtsouk.widget.saveprefs.plist
mtsouk$

The contents of the widget-com.mtsouk.widget.save-prefs.plist file are the following:

   <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>OptionString</key>
   <string>Option 4</string>
</dict>
</plist>


Figure 2: The final look of the presented Widget (both sides).

A word of advice: You can now understand why it is extremely important to have a uniquely defined CFBundleIdentifier key for every Widget that you create or use. The above plist file that stores the Widget preferences uses the CFBundleIdentifier value as a part of its filename. It is also important to have a UNIQUE CFBundleName key because if you try to install a Widget with the same CFBundleName key, Dashboard will ask you if you want to replace the existing Widget (the other, different Widget with the same CFBundleName name)!!

Conclusions

This article presents an advanced technique that lets you store and retrieve your Dashboard Widget preferences or any other data you like. The presented Widget uses the back side for selecting the desired preference and its front side for displaying it but you can choose to implement it any way you want.

Bibliography and References

Introduction to Dashboard Programming Topics: http://developer.apple.com/documentation/AppleApplications/Conceptual/Dashboard_ProgTopics/Introduction/Introduction.html

Introduction to Dashboard Tutorial: http://developer.apple.com/documentation/AppleApplications/Conceptual/Dashboard_Tutorial/Introduction/chapter_1_section_1.html

Developing Dashboard Widgets: http://developer.apple.com/macosx/dashboard.html

Apple Dashboard Page: http://developer.apple.com/appleapplications/dashboard/

Debugging Dashboard Widgets: http://developer.apple.com/technotes/tn2005/tn2139.html

Dashboard Sample Code: http://developer.apple.com/samplecode/AppleApplications/idxDashboard-date.html#//apple_ref/doc/uid/TP30000925-TP30000418-TP40001366

Disclaimer: The presented Widget code is a modified version of the "GoodBye" Widget provided by Apple and located on your Tiger machine (but not in Mac OS X 10.5), inside the "/Developer/Examples/Dashboard/GoodbyeWorld/3-SavingPreferences" folder. The "Save Prefs" Widget that is presented in this article has four options and, as you saw, it is a little bit more complicated than the "GoodBye" Apple Widget.


Mihalis Tsoukalos lives in Greece with his wife Eugenia and enjoys digital photography and writing articles. He is the author of the "Programming Dashboard Widgets" eBook. You can reach him at tsoukalos@sch.gr.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.