Chapter 7. Clipboard Support

Because support for the clipboard is essential in any desktop application, AIR allows for access to the operating system clipboard in several data formats. AIR also provides support for many operations beyond the standard copying, cutting, and pasting of text within an application. The standard data formats within AIR let you work with many types of text data, bitmap data, and even file references. Another great feature of the clipboard support within AIR is that you can extend it and create your own custom clipboard data format to fit your AIR application.

Working with the Clipboard Data Types

Problem

You need to be able to see whether a specific type of data is present on the operating system clipboard.

Solution

Use the hasFormat method of the ClipboardFormats class to determine whether the desired format is defined by that class.

Discussion

The clipboard is designed to hold multiple types of data simultaneously. It is often prudent to store multiple formats of the same data when you store to the clipboard, because you may not know the preferred format of the application that may later use the clipboard data. AIR gives you the ability to work with the different data formats via many of the methods of the Clipboard class. To begin with, six default clipboard data formats are defined in AIR:

  • ClipboardFormats.TEXT_FORMAT: This format contains simple text data within the clipboard.

  • ClipboardFormats.HTML_FORMAT: This format contains formatted HTML data within the clipboard.

  • ClipboardFormats.RICH_TEXT_FORMAT: This format contains a ByteArray of Rich Text Format (RTF) data. There are no components yet that let you directly display RTF data within AIR, and in addition, there are no methods in place for converting this data into another format.

  • ClipboardFormats.URL_FORMAT: This format contains a URL within the clipboard.

  • ClipboardFormats.FILE_LIST_FORMAT: This format contains an array of file references on the file system within the clipboard.

  • ClipboardFormats.BITMAP_FORMAT: This format contains bitmap data within the clipboard.

Additionally, AIR lets you use custom formats defined by you, the developer, that are specific to your application. For example, you may have DashboardClipboardFormats.CHART_DATA_FORMAT to indicate you are copying and pasting chart data between application modules. When using custom formats, the data is retrieved as an object reference or serialized clone. See Creating Custom Clipboard Data Formats for more on custom formats.

One of the methods that uses these values is the hasFormat method of the Clipboard class. The hasFormat method on a clipboard instance accepts one of these format constants as a parameter and returns a Boolean value indicating whether any data of that format exists on the clipboard.

ActionScript

In ActionScript, you can easily access the operating system clipboard with the generalClipboard property of the Clipboard class. In the following example, you can select a data format and click the Check Clipboard button to determine whether that data is present on the clipboard.

<mx:WindowedApplication
    xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="vertical">

    <mx:Script>
          <![CDATA[
               import flash.desktop.ClipboardFormats;
               import flash.desktop.Clipboard;

               private function handleClick( event:MouseEvent ):void
               {
                     var systemClipboard:ClipBoard = Clipboard.generalClipboard;
                     if(systemClipboard.hasFormat( formatsBox.selectedItem.value ) ){
                          resultText.text = "There is " + 
                     formatsBox.selectedItem.label + " data on the clipboard.";
                     } else {
                          resultText.text = "There is not " +
                     formatsBox.selectedItem.label + " data on the clipboard.";
                     }
               }
          ]]>
    </mx:Script>

    <mx:Array id="formats">
          <mx:Object value="{ClipboardFormats.TEXT_FORMAT}" label="Text" />
          <mx:Object value="{ClipboardFormats.URL_FORMAT}" label="URL" />
          <mx:Object value="{ClipboardFormats.HTML_FORMAT}" label="HTML" />
          <mx:Object value="{ClipboardFormats.RICH_TEXT_FORMAT}" label="Rich Text" />
          <mx:Object value="{ClipboardFormats.BITMAP_FORMAT}" label="Bitmap" />
          <mx:Object value="{ClipboardFormats.FILE_LIST_FORMAT}" label="File List" />
    </mx:Array>

    <mx:ComboBox id="formatsBox" dataProvider="{formats}" />
    <mx:Button label="Check Clipboard" click="handleClick(event)" />
    <mx:Text id="resultText" />

</mx:WindowedApplication>

JavaScript

In the following JavaScript example, a select list is populated in a method that executes when the application is loaded. This method populates the select list with the various default clipboard data types. The user can click the Check Clipboard button, which will call a method that executes the air.Clipboard.generalClipboard.hasFormat method to determine whether the data is present on the clipboard. This will then update the result div with the result.

<html>
<head>
    <title>Entry 7.1 - JavaScript</title>

    <script type="text/javascript" src="AIRAliases.js"></script>
    <script type="text/javascript">
          function populateSelectOptions() {
               document.formatForm.formats.options[0] = new Option( "Text", 
air.ClipboardFormats.TEXT_FORMAT );
               document.formatForm.formats.options[1] = new Option( "URL", 
air.ClipboardFormats.URL_FORMAT );
               document.formatForm.formats.options[2] = new Option( "HTML", 
air.ClipboardFormats.HTML_FORMAT );
               document.formatForm.formats.options[3] = new Option( "Rich Text", 
air.ClipboardFormats.RICH_TEXT_FORMAT );
               document.formatForm.formats.options[4] = new Option( "Bitmap", //

air.ClipboardFormats.BITMAP_FORMAT );
               document.formatForm.formats.options[5] = new Option( "File List", 
air.ClipboardFormats.FILE_LIST_FORMAT );
          }
          function handleClick( event ) {
               var resultDiv = document.getElementById( 'result' );
               var selectedOption = 
document.formatForm.formats.options[document.formatForm.formats.selectedIndex];
               if( air.Clipboard.generalClipboard.hasFormat( selectedOption.value ) 
) {
                     resultDiv.innerHTML = "There is " +selectedOption.text + " data 
on the clipboard.";
               } else {
                     resultDiv.innerHTML = "There is not " +selectedOption.text + " 
data on the clipboard.";
               }
          }
    </script>
</head>

<body onload="populateSelectOptions()" style="text-align:center;">

    <form name="formatForm">
          <select name="formats"></select><br />
          <input type="button" value="Check Clipboard" onclick="handleClick(event)" />
    </form>
    <div id="result"></div>

</body>
</html>

Adding Data to the Operating System Clipboard

Problem

You need to add data to the operating system clipboard so that it can be accessed by other applications on the user’s computer.

Solution

Use the Clipboard class, which contains a reference to the operating system clipboard in the generalClipboard property. In this reference, you can call the setData method to add data to the clipboard.

Discussion

The static property generalClipboard of the Clipboard class contains an instance of the Clipboard class that represents the operating system clipboard and lets you perform get and set operations, among others. To set data onto the operating system clipboard, you use the setData method of this instance.

The setData method takes three parameters: the format of the data, the actual data, and an optional Boolean that indicates whether the data is serializable (defaults to true).

ActionScript

To set data on the operating system clipboard in ActionScript, you need to call the Clipboard.generalClipboard.setData method and pass in both the data and the data format. For example:

Clipboard.generalClipboard.setData( ClipboardFormats.TEXT_FORMAT, "Sample Text" );

This would place the words Sample Text onto the clipboard so that it is accessible from other applications.

In an actual Flex application, you could retrieve this text dynamically from a control. In the following example, you are given a text input where you can enter text to copy. After you enter the text, you can click the Copy button, and the text will be added to the operating system clipboard in the TEXT_FORMAT clipboard data format.

<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

    <mx:Script>
          <![CDATA[

               import flash.desktop.Clipboard;
               import flash.desktop.ClipboardFormats

               private function handleCopyClick(event:MouseEvent):void
               {
                     Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, 
textInput.text);
               }

          ]]>
    </mx:Script>

    <mx:TextInput id="textInput" />
    <mx:Button id="copyButton" label="Copy" click="handleCopyClick(event)"/>

</mx:WindowedApplication>

JavaScript

To use the setData method of the Clipboard class within JavaScript, you need to pass in the data type as well as the actual data to be added to the clipboard. For example:

air.Clipboard.generalClipboard.setData( air.ClipboardFormats.TEXT_FORMAT, "Sample 
Text" );

This would place the words Sample Text onto the clipboard so that it is accessible from other applications.

In an actual application, you can pull this information dynamically from a control. In this example, the user is given a text input where you can enter text to be copied to the clipboard. When you click the Copy button, this text will be added to the operating system clipboard in the TEXT_FORMAT clipboard data format.

<html>
    <head>
        <title>Copy to Clipboard</title>

        <script type="text/javascript" src="AIRAliases.js"></script>
        <script type="text/javascript">

               function handleCopyClick(event) {
                     var textInput = document.getElementById('userInput'),
                     air.Clipboard.generalClipboard.setData(air.ClipboardFormats.TEXT_FORMAT, 
textInput.value);
               }

        </script>
    </head>

    <body>
        <input id="userInput" type="text" />
        <input id="copyButton" type="submit" value="Copy" 
onclick="handleCopyClick(event)" />
    </body>
</html>

Retrieving Data from the Operating System Clipboard

Problem

You need to be able to access data from the operating system clipboard.

Solution

Use the static getData method of the Clipboard class to retrieve data from any Clipboard instance.

Discussion

The getData method takes two parameters: the data type of the data you are requesting and an optional parameter that defines the ClipboardTransferMode used to access that data, indicating whether the data comes back as a reference or as a serialized copy. The second parameter is not used with the default data formats that are defined in the ClipboardFormats class but is used only when accessing application-defined formats.

ActionScript

In ActionScript, you can retrieve data from the clipboard by calling the getData method on an instance of the Clipboard class. For example:

Clipboard.generalClipboard.getData( ClipboardFormats.FILE_LIST_FORMAT );

This example retrieves the clipboard data from the operating system clipboard that is in the file list format.

In this example, the user can click the Get Data button, and if there is FILE_LIST_FORMAT data present on the clipboard, it will be retrieved and used to populate the List control. The names of the files will also be traced to the console. Also, note in this example you want to work only with copies of the files, not the originals. Because of this, the transfer mode is set to CLONE_ONLY. For more information on transfer modes with the clipboard, see Creating Custom Clipboard Data Formats.

<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

    <mx:Script>
          <![CDATA[
               import mx.collections.ArrayCollection;
               import flash.desktop.Clipboard;
               import flash.desktop.ClipboardFormats;
               import flash.desktop.ClipboardTransferMode;

               [Bindable]
               private var files:ArrayCollection = new ArrayCollection();

               private function handleGetDataClick(event:MouseEvent):void {
                     if(Clipboard.generalClipboard.hasFormat(Clipboard
Formats.FILE_LIST_FORMAT)) {
                          var items:Array = Clipboard.generalClipboard.getData( 
ClipboardFormats.FILE_LIST_FORMAT, ClipboardTransferMode.CLONE_ONLY) as Array;
                          files = new ArrayCollection( items );
                          for each (var aFile:File in items) {
                                trace( "[FILE REFERENCE]: " + aFile.name );
                          }
                     }
               }

          ]]>
    </mx:Script>

    <mx:Button id="getData" label="Get Data" click="handleGetDataClick(event)" />
    <mx:Label text="File List on Clipboard" />
    <mx:List id="results" dataProvider="{files}" labelField="nativePath"/>

</mx:WindowedApplication>

JavaScript

In JavaScript, you can access data from the clipboard by calling the getData method of the Clipboard class. For example:

air.Clipboard.generalClipboard.getData( air.ClipboardFormats.FILE_LIST_FORMAT );

This example will return an array of file references that represents the files that have been added to the operating system clipboard.

In the following example, the application has a single button. When the button is clicked, data in the FILE_LIST_FORMAT is retrieved from the clipboard if it is present. There is a div with an id of result. The native paths of the referenced files will be added to this div. In addition, the names of the files will be traced to the console. Also, note in this example you want to work with copies of the files only, not the originals. Because of this, the transfer mode is set to CLONE_ONLY. For more information on transfer modes with the clipboard, see Creating Custom Clipboard Data Formats.

<html>
    <head>
        <title>Retrieve Data from Clipboard</title>
        <link href="sample.css" rel="stylesheet" type="text/css"/>

        <script type="text/javascript" src="AIRAliases.js"></script>
        <script type="text/javascript">
            function handleGetDataClick(event) {
                     result.innerHTML = "";
                     if(air.Clipboard.generalClipboard.hasFormat
(air.ClipboardFormats.FILE_LIST_FORMAT)) {
                          var items = new Array();
                          items =
air.Clipboard.generalClipboard.getData(air.ClipboardFormats.FILE_LIST_FORMAT,air.Cl
ipboardTransferMode.CLONE_ONLY);
                          for (index = 0; index < items.length; index++) {
                              var aFile = items[index];
                              result.innerHTML += aFile.nativePath + " <br/> ";
                                air.trace("[FILE REFERENCE]:" + aFile.name);
                          }
                     } else {
                          result.innerHTML = "No File References on Clipboard"
;                    }
               }
        </script>
    </head>

    <body>
        <input type="button" value="Get Data" onclick="handleGetDataClick(event)" />
        <div id="result"></div>
    </body>
</html>

Clearing Data from a Clipboard

Problem

You need to be able to clear a certain type of data from the operating system clipboard.

Solution

Use the clearData method to clear a specific type of data from an instance of the Clipboard class, or use the clear method to remove data of all types from an instance of the Clipboard class.

Discussion

In many cases you may need to clear a specific type of data from the operating system clipboard. In those cases you can rely on the two methods provided by the Clipboard class: clear and clearData.

ActionScript

You can clear all the data from a clipboard with ActionScript by calling the clear method. For example:

Clipboard.generalClipboard.clear();

This would clear all the data on the operating system clipboard from your AIR application. If you need to clear only a specific data type, you can use the clearData method. For example:

Clipboard.generalClipboard.clearData( ClipboardFormats.BITMAP_FORMAT );

In the following example, you are able to select a specific clipboard data format and clear the selected format from the operating system clipboard by using the clearData method:

<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

    <mx:Script>
          <![CDATA[

               import flash.desktop.Clipboard;
               import flash.desktop.ClipboardFormats;

               private function handleClearFormatClick(event:MouseEvent):void {
                     Clipboard.generalClipboard.clearData(format.selectedItem.value 
as String);
               }

          ]]>
    </mx:Script>

    <mx:ComboBox id="format">
          <mx:dataProvider>
               <mx:Array>
                     <mx:Object value="{ClipboardFormats.TEXT_FORMAT}" label="Text" />
                     <mx:Object value="{ClipboardFormats.URL_FORMAT}" label="URL" />
                     <mx:Object value="{ClipboardFormats.HTML_FORMAT}" label="HTML" />
                     <mx:Object value="{ClipboardFormats.RICH_TEXT_FORMAT}" 
label="Rich Text" />
                     <mx:Object value="{ClipboardFormats.BITMAP_FORMAT}" 
label="Bitmap" />
                     <mx:Object value="{ClipboardFormats.FILE_LIST_FORMAT}" 
label="File List" />
               </mx:Array>
          </mx:dataProvider>
    </mx:ComboBox>

    <mx:Button label="Clear Format Data" click="handleClearFormatClick(event)" />

</mx:WindowedApplication>

JavaScript

To clear all the data from an instance of the Clipboard class within JavaScript, you need to call the clear method. For example:

air.Clipboard.generalClipboard.clear()

This would clear all the data on the operating system clipboard from your AIR application. Likewise, if you need to clear only a specific format, you can use the clearData method and pass in the format you want removed:

air.Clipboard.generalClipboard.clearData( air.ClipboardFormats.BITMAP_FORMAT );

In the following example, you are able to select a specific clipboard data format and clear the selected format from the operating system clipboard by using the clearData method:

<html>
    <head>
        <title>Entry 7.4 - Clear Data From Clipboard</title>
        <script type="text/javascript" src="AIRAliases.js"></script>
        <script type="text/javascript">
            function populateSelectOptions() {
                     document.formatForm.formats.options[0] = new Option( "Text", 
air.ClipboardFormats.TEXT_FORMAT );
                     document.formatForm.formats.options[1] = new Option( "URL", 
air.ClipboardFormats.URL_FORMAT );
                     document.formatForm.formats.options[2] = new Option( "HTML", 
air.ClipboardFormats.HTML_FORMAT );
                     document.formatForm.formats.options[3] = new Option( "Rich 
Text", air.ClipboardFormats.RICH_TEXT_FORMAT );
                     document.formatForm.formats.options[4] = new Option( "Bitmap", 
air.ClipboardFormats.BITMAP_FORMAT );
                     document.formatForm.formats.options[5] = new Option( "File 
List", air.ClipboardFormats.FILE_LIST_FORMAT );
               }

               function handleClearFormatClick(event) {
                     var selectedOption = document.formatForm.formats.options[
document.formatForm.formats.selectedIndex];
                     air.Clipboard.generalClipboard.clearData(selectedOption.value);
               }
        </script>
    </head>

    <body onload="populateSelectOptions()">
          <form name="formatForm">
               <select name="formats"></select><br />
               <input type="button" value="Clear Format" 
onclick="handleClearFormatClick(event)" />
          </form>

    </body>
</html>

Using Deferred Rendering with Clipboard Data

Problem

You want clipboard data to be rendered (or created) when it is pasted instead of when it is copied.

Solution

Use the setDataHandler method, which doesn’t store the actual data in the clipboard but rather references a method for rendering the data.

Discussion

In cases where rendering the clipboard data requires a large amount of system resources or where the data is changing on a regular basis, you may want the data to be rendered when it is pasted instead of when it is copied to the clipboard. To accomplish this in AIR, you can use the setDataHandler method.

This method works in a similar manner to the setData method, except instead of passing in the actual data, you pass in a function that will render the data. This function is called only when the data is needed. The first time the data is requested, the function is called, and the return value of the function populates the clipboard with the correct data. Subsequent calls to that data return that value. The function will not called again until the data is copied and requested again. It is important to remember this so as to not have undesired effects when working with stale data. Also noteworthy is that when data of a particular format is set using both the setData method and the setDataHandler method, setData takes priority. In this case, the handler function is never called when retrieving the data.

ActionScript

In this Flex example, there are three user interface elements: a Copy button, a Paste button, and a text element to contain the result text:

<mx:Button label="Copy" click="handleCopyClick(event)" />
<mx:Button label="Paste" click="handlePasteClick(event)" />
<mx:Text id="resultText" />

When the user clicks the Copy button, the current application time is stored, and the data is added to the clipboard with deferred rendering:

import flash.desktop.Clipboard;
import flash.desktop.ClipboardFormats;
import flash.utils.getTimer;

private var timeCopied:int;

private function handleCopyClick( event:MouseEvent ):void {
    timeCopied = getTimer();
    Clipboard.generalClipboard.setDataHandler( ClipboardFormats.TEXT_FORMAT, 
dataHandler );
}

private function dataHandler():String {
    return "[Time Copied]: " + timeCopied + " [Time First Pasted]: " + getTimer();
}

When the user clicks the Paste button, the data is retrieved from the clipboard using deferred rendering. It lists both the time when the data was pasted as well as the time the data was pasted.

private function handlePasteClick( event:MouseEvent ):void {
    var data:String = Clipboard.generalClipboard.getData( Clipboard
Formats.TEXT_FORMAT ) as String;
    resultText.text = data;
}

If you click the Paste button twice, you will notice that the result stays the same. This is because the dataHandler method is called only the first time the data is requested. If you wanted the method to be called each time the Paste button was clicked, you would need to call the setDataHandler method again at the end of the handlePasteClick method.

JavaScript

In this example, there are three user interface elements: a Copy button, a Paste button, and a result div that will display the result text:

<input type="button" value="Copy" onclick="handleCopyClick(event)" /><br />
<input type="button" value="Paste" onclick="handlePasteClick(event)" />
<div id="result"></div>

When the application loads, the value of appStartTime is set to the current time. This value is used to calculate the number of milliseconds since the application launched. Another variable, timeClicked, is also created when the application launches.

var appStartTime = new Date();
var timeClicked;

When the user clicks the Copy button, the timeClicked variable is set to the current time and the data is added to the clipboard with deferred rendering.

function handleCopyClick(event) {
    timeClicked = new Date();
    air.Clipboard.generalClipboard.setDataHandler( 
air.ClipboardFormats.TEXT_FORMAT, dataHandler );
}

function dataHandler() {
    var data =  "[TIME COPIED]: " + ( timeClicked.getTime() -
appStartTime.getTime() );
    data +=  " [TIME First PASTED]: " + ( new Date().getTime() -
appStartTime.getTime() );
    return data;
}

When the user clicks the Paste button, the data is retrieved from the clipboard using deferred rendering, and the result from the clipboard is displayed in the result div. It lists both the time when the data was pasted as well as the time the data was pasted.

function handlePasteClick(event) {
    var result = document.getElementById( 'result' );
    result.innerHTML = air.Clipboard.generalClipboard.getData( 
air.ClipboardFormats.TEXT_FORMAT );
}

If you click the Paste button twice, you will notice that the result stays the same, because the dataHandler method is called only the first time the data is requested. If you wanted the method to be called each time the Paste button is clicked, you need to call the setDataHandler method again at the end of the handlePasteClick method.

Creating Custom Clipboard Data Formats

Problem

You want to use a data format for the clipboard that is not one of the five default formats defined in ClipboardFormats.

Solution

Create a custom Clipboard data format using the built-in support for custom formats within AIR.

Discussion

In some situations, the standard clipboard data formats do not meet the needs of your application. For these situations, you can take advantage of the custom data formats of the Clipboard class.

To create a custom data format in AIR, you need a string that identifies your format. You will pass this to the Clipboard methods instead of a constant from the ClipboardDataFormats class. The only limitation on this string is that it cannot begin with air:. The AIR documentation suggests you use your application ID as the prefix for the format. For example:

com.oreilly.aircookbook.MyApplication:customdata

This helps to ensure your custom data format identifier will not match any other custom data formats from other AIR applications.

Transfer Modes

When you are dealing with custom data formats, you use the third parameter of the setData and setDataHandler methods to control how your data is placed on the clipboard. Essentially, there are two ways to place your data: as a copy and as a reference to the original object. Most any object can be added to the clipboard as a reference, but classes that are copied onto the clipboard must be serializable. If your class is serializable, you can pass true to the third parameter of these methods, and your data will be placed on the clipboard as a copy. If you pass false, it will be passed as a reference.

The transfer mode is not just important when pasting data, but it also plays a key role in retrieving data. getData has a third parameter that lets you indicate whether you want a copy of the data or a reference to the original data. The values for this parameter are defined as constants in the ClipboardTransferMode class.

  • ClipboardTransferMode.ORIGINAL_ONLY: This mode takes only a reference of the data. If this is passed as the third parameter of the getData method, the method will take the original only. If only the copy of the data is available, no data will be returned.

  • ClipboardTransferMode.CLONE_ONLY: This mode takes only a copy of the clipboard data. If only the reference to the original object is available, no data will be returned.

  • ClipboardTransferMode.ORIGINAL_PREFERRED: In this mode, the getData method is requesting a reference to the original object, but if a copy is all that is available, the method will take that value.

  • ClipboardTransferMode.CLONE_PREFERRED: In this mode, the getData method is requesting a copy of the original data. It will be returned if available. If only a reference to the original is available, the method will still use that value.

In some cases, it might not be apparent which transfer mode is appropriate. However, this value can become extremely important when working with clipboard data in the file list format. This could mean the difference between deleting a file and deleting a copy of a file. Unless you are performing actual file system operations, you will probably want to use ClipboardTransferMode.CLONE_ONLY when working with file list format data.

Sharing Data Between AIR Applications

If you want this custom data format to be available to other AIR applications, the data must be passed as a copy. When using a reference to the original data, you can paste the data only within the same AIR application.

ActionScript

The first step to creating a custom data format in ActionScript is to define your data. For your data class to be serializable, it must implement the IExternalizable interface. This requires that you define two methods, readExternal and writeExternal, which allow your data class to be broken down into binary data and copied onto the clipboard.

In the writeExternal method, you use the methods of the IDataOutput interface to write your data into binary form. Each standard ActionScript data type has a corresponding method that enables you to write the data. Be sure to pay attention to the order the data is written in this method. This order must be repeated in the readExternal method.

For the readExternal method, you use the read methods of the IDataInput interface to read your data back into your class. They do not need to be in the same order as they were written in the writeExternal method. For example:

package{

    import flash.utils.IExternalizable;
    import flash.utils.IDataInput;
    import flash.utils.IDataOutput;
    import flash.net.registerClassAlias;

    [Bindable]
    public class Person implements IExternalizable {

          public var firstName:String;
          public var lastName:String;
          public var age:int;

          public function Person() {
               registerClassAlias( "Person", Person );
          }

          public function readExternal(input:IDataInput):void {
               firstName = input.readUTF();
               lastName = input.readUTF();
               age = input.readInt();
          }

          public function writeExternal(output:IDataOutput):void {
               output.writeUTF(firstName);
               output.writeUTF(lastName);
               output.writeInt(age);
          }

    }
}

In this example, the custom data defines a person. It has the properties firstName, lastName, and age. Because the data has been defined, you can now add it to the clipboard as a custom data format. For this example, you will be using the following Flex user interface:

<mx:Label text="Input Data" fontSize="20" fontWeight="bold" />

<mx:Label text="First Name" />
<mx:TextInput id="firstName" />
<mx:Label text="Last Name" />
<mx:TextInput id="lastName" />
<mx:Label text="Age" />
<mx:TextInput id="age" />

<mx:HBox>
    <mx:Button label="Copy" click="handleCopyClick(event)" />
    <mx:Button label="Paste" click="handlePasteClick(event)" />
    <mx:Button label="Clear All Data" click="handleClearClick(event)" />
</mx:HBox>

<mx:Label text="Result" fontSize="20" fontWeight="bold" />

<mx:Label text="First Name" />
<mx:TextInput id="resultFirstName" enabled="false"/>
<mx:Label text="Last Name" />
<mx:TextInput id="resultLastName" enabled="false"/>
<mx:Label text="Age" />
<mx:TextInput id="resultAge" restrict="0-9" enabled="false"/>

The application should allow the user to fill in the fields on the top with the first name, last name, and age of the person. Then, if you click the Copy button, the data will be added to the clipboard through a custom data type identified by the string person. Next, if you click the Paste button, that data will be retrieved from the clipboard and used to populate the values in the lower form. The handleCopyClick method handles adding the data to the clipboard.

public function handleCopyClick( event:MouseEvent ):void {
    var data:Person = new Person();
    data.firstName = firstName.text;
    data.lastName = lastName.text;
    data.age = parseInt( age.text );
    var setResult:Boolean = Clipboard.generalClipboard.setData( "person", data, 
true );
}

First, an instance of the data class Person is created. Then its properties are assigned the values of their respective text inputs. Finally, the data is added to the operating system clipboard with the setData method. The data is passing a copy of itself because the value true was passed as the third parameter indicating that the data is to be serialized.

public function handlePasteClick(event:MouseEvent):void {
     var result:Person = Clipboard.generalClipboard.getData
( "person", ClipboardTransferMode.CLONE_PREFERRED ) as Person;
     if (result) {
        resultFirstName.text = result.firstName;
        resultLastName.text = result.lastName;
        resultAge.text = result.age.toString();
     }
}

The handlePasteClick method gets the data from the clipboard using the same identifier that was used to set it on the clipboard. It also indicates that it wants a copy of the data if available as opposed to the original object. Finally, the values of the lower form are set. After using the Paste button, you can use the Clear All Data button to clear all the data from the form fields as well as the clipboard. Note that if you clear the clipboard, attempting to paste will cause the player to throw an “end of file” error, because there is no relevant data to be read. It is prudent to have error handling in place in the form of a try...catch block, because simply checking with hasFormat is not sufficient.

public function handleClearClick( event:MouseEvent ):void {
    firstName.text = "";
    lastName.text = "";
    age.text = "";
    resultFirstName.text = "";
    resultLastName.text = "";
    resultAge.text = "";
    Clipboard.generalClipboard.clearData( "person" );
}

JavaScript

The following user interface demonstrates the custom clipboard data formats within JavaScript. It consists of two forms, one to enter the data and one to display the data from the clipboard. In addition, it contains three buttons that enable you to copy, paste, and clear data.

<h2>Enter Data</h2>
<form name="dataForm">
    First Name: <input name="firstName" /><br />
    Last Name: <input name="lastName" /><br />
    Age: <input name="age" />
</form>
<input type="button" value="Copy" onclick="handleCopyClick(event)" />
<input type="button" value="Paste" onclick="handlePasteClick(event)" />
<input type="button" value="Clear All Data" onclick="handleClearClick(event)" />

<h2>Results</h2>
<form name="resultForm">
    First Name: <input name="firstName" disabled="true" /><br />
    Last Name: <input name="lastName" disabled="true" /><br />
    Age: <input name="age" disabled="true" />
</form>

The work of placing the custom data onto the clipboard is handled by the handleCopyClick method. This method creates a new object, person, and assigns the firstName, lastName, and age properties to it. Then, the data is placed on the operating system clipboard by using the setData method and the unique identifier of person.

function handleCopyClick( event ) {
    var person = {};
    person.firstName = document.dataForm.firstName.value;
    person.lastName = document.dataForm.lastName.value;
    person.age = document.dataForm.age.value;
    air.Clipboard.generalClipboard.setData( "person", person, true );
}

The handlePasteClick method handles the actual retrieving of the custom clipboard data. This method creates a new object to hold the results of the getData method. Then, the getData method is called while passing in the unique identifier used to place the date on the clipboard. Finally, the results are placed in their respective form fields.

function handlePasteClick( event ) {
    var result = {};
    if(air.Clipboard.generalClipboard.hasFormat( "person")) {
          result = air.Clipboard.generalClipboard.getData( "person", 
air.ClipboardTransferMode.ORIGINAL_PREFERRED );
          document.resultForm.firstName.value = result.firstName;
          document.resultForm.lastName.value = result.lastName;
          document.resultForm.age.value = result.age;
    }
}

Finally, the Clear All Data button lets you clear all the form fields as well as the custom data from the clipboard.

function handleClearClick ( event ) {
    document.dataForm.firstName.value = "";
    document.dataForm.lastName.value = "";
    document.dataForm.age.value = "";
    document.resultForm.firstName.value = "";
    document.resultForm.lastName.value = "";
    document.resultForm.age.value = "";
    air.Clipboard.generalClipboard.clearData( "person" );
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset