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

Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »

Price Scanner via MacPrices.net

Sunday Sale: Take $150 off every 15-inch M3 M...
Amazon is now offering a $150 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1149 for models with 8GB of RAM and 256GB of storage: – 15″ M3 MacBook... Read more
Apple’s 24-inch M3 iMacs are on sale for $150...
Amazon is offering a $150 discount on Apple’s new M3-powered 24″ iMacs. Prices start at $1149 for models with 8GB of RAM and 256GB of storage: – 24″ M3 iMac/8-core GPU/8GB/256GB: $1149.99, $150 off... Read more
Verizon has Apple AirPods on sale this weeken...
Verizon has Apple AirPods on sale for up to 31% off MSRP on their online store this weekend. Their prices are the lowest price available for AirPods from any Apple retailer. Verizon service is not... Read more
Apple has 15-inch M2 MacBook Airs available s...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
May 2024 Apple Education discounts on MacBook...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $300 off the purchase of a new MacBook... Read more
Clearance 16-inch M2 Pro MacBook Pros in stoc...
Apple has clearance 16″ M2 Pro MacBook Pros available in their Certified Refurbished store starting at $2049 and ranging up to $450 off original MSRP. Each model features a new outer case, shipping... Read more
Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more

Jobs Board

Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.