# Introduction to Writing Plugins for RKWard

## Introduction

Documentation as of &kapp; release 0.4.8.

This document describes how to write your own plugins. Note, that at the time of this writing, none of the concepts are set it stone. Therefore, this document should be regarded as an introduction to the current approach, and as a basis for discussion. All sorts of comments are welcome.

For questions and comments, please write to the &kapp; development mailing list.

You do not need to read this in order to use &kapp;. This document is about extending &kapp;. It is targeted at advanced users, or people willing to help improve &kapp;.

Writing a standard plugin is basically a four-step process:

- Placing a new Action in the menu-hierarchy
- Describing the looks and behavior of the plugin-GUI
- Defining, how R-code is to be generated from the settings, the user makes in the GUI
- Adding a help page to your plugin

Those will be dealt with in turn.

Some advanced concepts may be used in those four steps, but are dealt with in separate chapters, to keep things simple:

- GUI logic
- Embedding Plugins into Plugins
- Useful concepts for creating many series of similar plugins

Also, none of the chapters shows all options, but rather only the basic concepts. A complete reference of options is provided separately.

## Preliminaries: What are plugins in &kapp;? How do they work?

Of course the first question you might have is: What portions of &kapp; functionality is realized using plugins? Or: What can plugins do?

One way to answer this is: Deselect all .pluginmap-files under Settings->Configure &kapp;->Plugins, and see what's missing. A slightly more helpful answer: Most actual statistics functions accessible via the GUI are realized using plugins. Also, you can create fairly flexible GUIs for all kinds of operations using plugins.

The basic paradigm behind &kapp; plugins is the one we'll walk you through in this document: An xml-file describes what the GUI looks like. An additional PHP-file is used to generate R syntax from the GUI settings. That is, plugins do not really have to perform any statistical calculations. Rather plugins generate the R syntax needed to run those calculations. The R syntax is then sent to the R backend for evaluation, and typically a result is shown in the output window.

Read on in the next chapters to see how this is done.

## Creating menu entries

When you create a new plugin, you need to tell &kapp; about it. So the first thing to do, is to write a .pluginmap-file (or modify an existing one). The format of .pluginmap is XML. I'll walk you through an example (also of course, be sure you have &kapp; configured to load your pluginmap – Settings->Configure &kapp;->Plugins):

    <!DOCTYPE rkpluginmap>

The doctype is not really interpreted, but set it to "rkpluginmap" anyway.

    <document base_prefix="" namespace="rkward">

The "base_prefix"-attribute can be used, if all your plugins reside in a common directory. Basically, then, you can omit that directory from the filenames specified below. As you will see below, all plugins get a unique identifier. The "namespace" is a way to organize those ids, and make it less likely to create a duplicate identifier accidentally. Internally, basically the namespace and then a "::" gets prepended to all the identifiers you specify below. If unsure, leave these at "" and "rkward".

    	<components>

Components? Aren't we talking about plugins? Yes, but in the future, plugins will be no more than a special class of components. What we do here, then, is to register all components/plugins with &kapp;. Let's look at an example entry:

    		<component type="standard" id="independent_samples_t_test" file="means/ttests/independent_samples.xml" label="Independent Samples" />

First the "type"-attribute: Leave this to "standard" for now. Further types are not yet implemented. The "id" I've already hinted at. Each component has to be given a unique (in its namespace) identifier. Pick one that is easily recognizable. Avoid spaces and any special characters. Those are not banned, so far, but might have special meanings. With the "file" attribute, you specify where the description of the actual plugin itself is located. This is relative to the directory the .pluginmap-file is in, and the "base_prefix" above. Finally, give the component a label. This label will be shown whereever the plugin is placed in the menu (or in the future perhaps in other places as well).

Typically a .pluginmap-file will contain several components, so here are a few more:

    		<component type="standard" id="unimplemented_test" file="means/unimplemented.xml" />
    		<component type="standard" id="fictional_t_test" file="means/ttests/fictional.xml" label="This is a fictional t-test" />
    		<component type="standard" id="descriptive" file="descriptive.xml" label="Descriptive Statistics" />
    		<component type="standard" id="corr_matrix" file="corr_matrix.xml" label="Correlation Matrix" />
    		<component type="standard" id="simple_anova" file="simple_anova.xml" label="Simple Anova" />
    	</components>

Ok, this was the first step. &kapp; now knows those plugins exist. But how to invoke them? They need to be placed in a menu-hierarchy:

    	<hierarchy>
    		<menu id="analysis" label="Analysis" index="4">

Right below the <hierarchy>-tag, you start describing, in which menu, your plugins should go. With the above line, you basically say, that your plugin should be in the "Analysis" menu (not necessarily directly there, but in a submenu). The "Analysis" menu is standard in &kapp;, so it does not actually have to be created from scratch. However, if it did not exist yet, using the "label"-attribute you'd give it its name. The "index" attribute says, that the menu (if newly created) should be placed at the fourth position in the menubar. Finally, the "id" once again identifies this menu. This is needed, so several .pluginmap-files can place their plugins in the same menus. They do this by looking for a menu with the given "id". If the id does not yet exist, a new menu will be created. Otherwise the entries will be added to the existing menu.

    			<menu id="means" label="Means" index="1">

Basically the same thing here: Now we define a submenu to the "Analysis"-menu. It is to be called "Means".

    				<menu id="ttests" label="T-Tests">

And a final level in the menu-hierarchy: A sub-menu of the sub-menu "Means". Note, that if you omit the "index" parameter, the new entry will be placed below any already existing ones.

    					<entry component="independent_samples_t_test" />

Now, finally, this is the menu, we want to place the plugin in. The <entry>-tag signals, this actually is the real thing, instead of another submenu. The "component"-attribute refers to the "id" you gave the plugin/component above.

    					<entry component="fictional_t_test" />
    				</menu>
    				<entry component="fictional_t_test" />
    			</menu>
    			<menu id="frequency" label="Frequency" index="2"/>

In case you have lost track: This is another submenu to the "Analysis" menu. See the screenshot below. We'll skip some of what's not visible, marked with [...].

    				[...]
    			</menu>
    			<entry component="corr_matrix" index="4"/>
    			<entry component="descriptive" index="3"/>
    			<entry component="simple_anova" index="5"/>
    		</menu>

These are the final entries visible in the screenshots below. Note, that you don't need to define the entries in the order they should have in the menu. Use the "index"-attribute instead.

    		<menu id="plots" label="Plots" index="5">
    			[...]
    		</menu>

Of course you can also place your plugins in menus other than "Analysis".

    		<menu id="file" label="File" index="0">
    			[...]
    		</menu>

Even in standard-menus such as "File". All you need is the correct "id".

    	</hierarchy>
    </document>

That's how to do it. And this screenshot shows the result:

Menu hierarchy created by the code shown above Menu hierarchy created by the code shown above

Confused? The easiest way to get started is probably taking some of the existing .pluginmap files shipped with the distribution, and modifying them to your needs. Also, if you need help, don't hesitate to write to the development mailing list.

## Defining the GUI

In the previous chapter you've seen how to register a plugin with &kapp;. The most important ingredient was specifying the path to an XML file with a description of what the plugin actually looks like. In this chapter you'll learn how to create this XML file.

Once again we'll walk you through an example. The example is a (slightly simplified) version of the independent samples t-test.

    <!DOCTYPE rkplugin>

The doctype is not really interpreted, yet. Set it to rkplugin, anyway.

    <document>
    	<code file="t_test.php"/>

All plugins generate some code. Currently the only way to do so is using PHP, as detailed in the next chapter. This defines, where to look for the PHP-code. The filename is relative to the directory the plugin-xml is in.

    	<help file="t_test.rkh"/>

It is usually a good idea to also provide a help page for your plugin. The filename of that help page is given, here, relative to the directory, the plugin-xml is in. Writing help pages is documented here. If you do not provide a help file, omit this line.

    	<dialog label="Independent Samples T-Test">

As you know, plugins may have either a dialog or a wizard-interface or both. Here we start definining a dialog-interface. the label-attribute specifies the caption of the dialog.

    		<tabbook>
    			<tab label="Basic settings">

GUI-elements can be organized using a tabbook. Here we define a tabbook as the first element in the dialog. Use <tabbook>[...]</tabbook> to define the tabbook and then for each page in the tabbook use <tab>[...]</tab>. The "label"-attribute in the <tab>-element allows you to specify a caption for that page of the tabbook.

    				<row id="main_settings_row">

The <row> and <column> tags specify the layout of the GUI elements. Here you say, that you'd like to place some elements side-by-side (left to right). The "id"-attribute is not strictly necessary, but we'll use it later on, when adding a wizard interface to our plugin. The first element to place in the row, is:

    					<varselector id="vars"/>

Using this simple tag you create a list from which the user can select variables. You have to specify an id for this element, so RKWard knows how to find it. Note that you may NOT use a dot (.) in the "id" string.

    					<column>

Next, we nest a <column> inside the row. I.e. the following elements will be place above each other (top-to-bottom), and all will be to the right of the <varselector>.

    						<varslot type="numeric" id="x" source="vars" required="true" label="compare"/>
    						<varslot type="numeric" id="y" source="vars" required="true" label="against"/>

These elements are the counterpart to the <varselector>. They represent "slots" into which the user can put variables. You will note that the "source" is set to the same value as the "id" of the <varselector>. This means, the <varslot>s will each take their variables from the varselector. The <varslot>s also have to be given an "id". They may have a label, and they may be set to "required". This means that the submit-button will not be enabled until the <varslot> holds a valid value. Finally the "type"-attribute is not interpreted, yet, but it will be used to take care that only the correct types of variables will be allowed in the <varslot>.

    						<radio id="hypothesis" label="using test hypothesis">
    							<option value="two.sided" label="Two-sided"/>
    							<option value="greater" label="First is greater"/>
    							<option value="less" label="Second is greater"/>
    						</radio>

Here, you define a group of <radio>-exclusive buttons. The group has a "label" and an "id". Each <option> (button) has a label and is assigned a value. This is the value the <radio>-element will return when the option is selected.

    					</column>
    				</row>
    			</tab>

Each tag has to be closed. We've put all the elements we wanted (the two <varslots> and the <radio>) in the <column>. We put all elements we wanted (the <varselector> and the <column> with those elements) in the <row>. And we've put all the elements we wanted into the first page in the <tabbook>. We're not yet done defining the <tabbook> (more pages to come) and of course there's more to come in the <dialog>, too. But this screenshot is basically what we've done so far:

T test plugin T test plugin

Note that we have not specified the "Submit", "Close", etc. buttons or the code-view. Those elements get generated automatically. But of course we still have to define the second page of the <tabbook>:

    			<tab label="Options">
    				<checkbox id="varequal" label="assume equal variances" value=", var.equal=TRUE"/>

By default elements will be placed top-to-bottom like in a <column>. Since that is what we want here, we don't have to explicitly state a <row> or <column>-layout. The first element we define is a checkbox. Just like the <radio><option>s, the checkbox has a "label" and a "value". The "value" is what gets returned, if the checkbox is checked. Of course the checkbox also needs an "id".

    				<frame label="Confidence Interval" id="frame_conf_int">

Here's yet another layout-element: In order to signal that the two elements below belong together, we draw a <frame> (box). That frame may have a caption. Since the frame is just a passive layout-element, it does not need an "id", we still define one, here, as we'll refer to it later, when defining an additional wizard interface.

    					<checkbox id="confint" label="print confidence interval" value="1" checked="true"/>
    					<spinbox type="real" id="conflevel" label="confidence level" min="0" max="1" initial="0.95"/>
    				</frame>

Inside the <frame> we place another <checkbox> (using checked="true", we signal that checkbox should be checked by default), and a <spinbox>. The spinbox allows the user to select a value between "min" and "max" with the default/initial value "0.95". Setting the "type" to "real" signals that real numbers are accepted as opposed to type="integer" which would accept integers only.

    			</tab>
    		</tabbook>
    	</dialog>

That's all for the second page of the <tabbook>, all pages in the <tabbook> and all elements in the <dialog>. We're finished defining what the dialog looks like.

    </document>

Finally we close the <document>-tag, and that's it. The GUI is defined. You can save the file now. But how does R-syntax get generated from the GUI-settings? I'll deal with that in the next chapter. First, however, we'll look into adding a wizard interface, and some general considerations.

### Adding a wizard interface

Actually we don't have to define an additional <wizard>-interface, but here's how that would be done. To add a wizard interface, you'll add a <wizard> tag at the same level as the <dialog> tag:

    		<wizard label="Independent Samples T-Test">
    			<page id="firstpage">
    				<text>As a first step, select the two variables you want to compare against each other. And specify, which one you theorize to be greater. Select two-sided, if your theory does not tell you, which variable is greater.</text>
    				<copy id="main_settings_row/>
    			</page>

Some of this is pretty self explanatory: We add a <wizard> tag with a label for the wizard. Since a wizard can hold several pages that are shown one after another, we next define the first page, and put an explanatory text note in there. Then we use a <copy>-tag. What this does, is really it saves us having to define yet again, what we already wrote for the <dialog>: The copy tag looks for another tag with the same "id" earlier in the .xml. This happens to be defined in the <dialog> section, and is a <row> in which there are the <varselector>, <varslots> and the "hypothesis" <radio>-control. All of this is copied 1:1 and inserted right at the <copy> element.

Now to the second page:

    			<page id="secondpage">
    				<text>Below are some advanced options. It's generally safe not to assume the variables have equal variances. An appropriate correction will be applied then. Chosing "assume equal variances" may increase test-strength, however.</text>
    				<copy id="varequal"/>
    				<text>Sometimes it's helpful to get an estimate of the confidence interval of the difference in means. Below you can specify whether one should be shown, and which confidence-level should be applied (95% corresponds to a 5% level of significance).</text>
    				<copy id="frame_conf_int"/>
    			</page>
    		</wizard>

Much of the same thing here. We add some texts, and in between that <copy> further sections from the dialog interface.

You may of course make the wizard-interface look very different to the plain dialog, and not use the <copy> tag at all. Be sure, however, to assign corresponding elements the same "id" in both interfaces. This is not only used to transfer settings from the dialog-interface to the wizard-interface and back, when the user switches interfaces (which does not yet happen in the current version of RKWard), but also simplifies writing your code-template (see below).

### Some considerations on GUI design

This section contains some general considerations on which GUI elements to use where. If this is your first attempt of creating a plugin, feel free to skip over this section, as it isn't relevant to getting a basic GUI working. Come back here, later, to see, whether you can refine your plugin's GUI in some way or another.

#### <radio> vs. <checkbox> vs. <dropdown>

The three elements <radio>, <checkbox>, <dropdown>, all serve a similar function: To select one out of several options. Obviously, a checkbox only allows to chose between two options: checked or not checked, so you can't use it, if there are more than two options to chose from. But when to use which of the elements? Some rules of thumb:

If you find yourself creating a <radio> or <dropdown> with only two options, ask yourself, whether the question is essentially a yes / no type of question. E.g. a choice between "adjust results" and "do not adjust results", or between "remove missing values" and "keep missing values". In this case a <checkbox> is the best choice: It uses little space, will have the least words of labels, and is easiest to read for the user. There are very few situations where you should chose a <radio> over a <checkbox>, when there are only two options. An example of that might be: "Method of calculation: 'pearson'/'spearman'". Here, more methods might be thinkable, and they don't really form a pair of opposites.

Chosing between a <radio> and a <dropdown> is mostly a question of space. The <dropdown> has the advantage of using little space, even if there are a lot of options to chose from. On the other hand, a <radio> has the advantage of making all possible choices visible to the user at once, without clicking on the dropdown arrow. Generally, if there are six or more options to chose from, a <dropdown> is preferrable. If there are five or less options, a <radio> is the better choice.

## Generating R code from GUI settings

Now we have a GUI defined, but we still need to generate some R-code from that. For that, we need another text-file, "code.php", located in the same directory as the description.xml. You may or may not be familiar with PHP. Documentation on PHP can be found here: http://www.php.net. But for most purposes you will not need to know much about PHP at all, as we'll only use some very basic features..

For the independent samples t-test, the code.php file looks as follows (with comments in between):

    <?

This is a sort of opening tag in PHP. Everything between <? and ?> will be interpreted as PHP-code. Everything outside of these tags will simply be returned as plain text. See below for examples.

    function preprocess () {
    }

The PHP-file is organized into three separate functions: preprocess, calculate, and printout. This is because not all code is needed at all stages. Currently the preprocess-function is not really used in many places.

    function calculate () {
    ?>res <- t.test (<? getRK ("x"); ?>, <? getRK ("y"); ?>, "<? getRK ("hypothesis"); ?>"<? getRK ("varequal"); if (($conflevel = getRK_val ("conflevel")) != "0.95") echo (", conf.level=" . $conflevel); ?>)
    <?
    }

This function generates the actual R-syntax to be run from the GUI-settings. Let's look at this in detail: First we leave the PHP-mode (?>) and hence return

    res <- t.test (

as plain text. Next we need to fill in the value, the user selected as the first variable. Hence we enter PHP-mode again (<?) and call 'getRK ("x");'. This prints out the value of the GUI-element with id "x": our first <varslot>. Next we leave PHP-mode again, print a ', ', and do the same to fetch the value of the element "y" - the second <varslot>. For the hypothesis (the <radio>-group), and the equal variances-<checkbox>, the procedure is very similar.

It gets a little more tricky for the confidence level. For reasons of aestethics, we don't want to explicitly specify the confidence level to use, if it corresponds to the default value. Hence, instead of printing the value with 'getRK', we fetch it silently using 'getRK_val' and assign it to a PHP-variable. Then we check, whether that variable differs from "0.95" and if so print out an additional argument. Finally, we leave PHP-mode again, print a last ')', and that's it for the calculate-function.

    function printout () {
    ?>rk.header ("Independent samples t test")
    rk.print (res)
    <?
    }

And this was all there is to the printout function in most cases. rk.header () prints a standard headline for the results. You can also add some more information to this, if you like, e.g.:

    function printout () {
    ?>rk.header ("Independent samples t test", parameters=list ("Assume equal variances", <? getRK ("varequal"); ?>, "Confidence level", <? getRK ("conflevel"); ?>))
    rk.print (res)
    <?
    }

The list of parameters is given as pairs of "Description", "Value". This will also be printed in a standard way.

rk.print () utilizes the R2HTML package to provide HTML formatted output. Another helpful function is rk.results (), which can also output different kinds of result tables. If in doubt, however, just use rk.print (), and be done with.

Note that internally, the output is just a plain HTML document at this point of time. Therefore you might be tempted to add custom HTML using cat (). While this will work, please don't do this. The output format may change (e.g. to ODF) in the future, so it's best not to introduce HTML specific code. Rather keep things simple with rk.header (), rk.print (), and rk.results (). If those don't seem to satisfy your formatting needs, contact us on the mailing list for help.

Congratulations! You created your first plugin. Read on in the next chapters for more advanced concepts.

### Conventions, policies, and background

There are many ways to write R code for a certain task, and there are even more ways to generate this R code from PHP. How exactly you do it, is left up to you. Still there are a number of considerations that you should follow, and background information you should understand.

#### Understanding the local() environment

More often than not you will have to create one or more temporary R objects in the code generated by your plugin. Normally, you do not want those to be placed in the user's workspace, potentially even overwriting user variables. Hence, all plugin generated code is run in a local() environment (see R help page on function local()). This means, all variables you create are temporary and will not be saved permanently.

If the user explicitely asks for a variable to be saved, you will need to assign to that object with the "<<-" operator.

One important pitfall is using eval() to evaluate substitutes. Here, you need to note that eval will by default use the current environment for evaluation, i.e. the local one. This will work well most of the times, but if you define any temporary variables in the local environment, and you are trying to fetch user variables of the same name using eval, you will get errors. For example:

    # "objects" is the name of both a local temporary variable, and a user selected variable
    objects <- substitute (user.var1, user.var2, objects, user.var4)
    # this will fail: objects[3] is "the object named 'objects'", but this now refers to your
    # temporary variable, instead of the user variable
    third <- eval (objects[3])
    # instead, use this:
    third <- eval (objects[3], envir=globalenv())

To solve this, specify the evaluation environment explicitely, as shown above. This will generally be globalenv(), i.e. evaluate as if working in the global environment.

#### Code formatting

The most important thing is for your generated R code to work. But please also keep an eye on formatting. Some considerations:

Normal top-level R statements should be left aligned.

Statements in a lower block should be indented with one tab (see example below).

If you do very complex calculations, add a comment here and there, esp. to mark up logical sections.

For example, generated code might look like this. The same code without indentation or comments would be pretty hard to read, despite its modest complexity:

    # first determine the wobble and rotation
    my.wobble <- wobble (x, y)
    my.rotation <- wobble.rotation (my.wobble, z)

    # boggling method needs to be chosen according to rotation
    if (my.rotation > wobble.rotation.limit (x)) {
    	method <- "foo"
    	result <- boggle.foo (my.wobble, my.rotation)
    } else {
    	method <- "bar"
    	result <- boggle.bar (my.wobble, my.rotation)
    }

#### Dealing with complex options

Many plugins can do more than one thing. For instance, the "Descriptive Statistics" plugin can compute mean, range, sum, product, median, length, etc. However, typically the user will only chose to have some of those calculations performed. In this case, please try to keep the generated code as simple as possible. It should only contain portions relevant to the options that are actually selected. To achieve this, here is an example of a common design patterns as you would use it (in PHP):

    function calculate () { ?>
    x <- <? getRK ("x");
    results <- list () ?>
    <?
    	if (getRK_val ("domean")) { ?>
    results$'Mean value' <- mean (x)
    <?	}
    	if (getRK_val ("domedian")) { ?>
    results$'Median' <- median (x)
    <?	}
    	if (getRK_val ("dosd")) { ?>
    results$'Standard deviation' <- sd (x)
    <?	}
    	//...
    }

### Tips and tricks

Here are a few assorted tricks which may make writing plugins less tedious:

If you need the value of a GUI setting at several places in you plugin's code, consider assigning it to a PHP variable, and using that instead of fetching it again and again with getRK. This is faster, more readable, and less typing all at the same time:

    function calculate () {
    	if (getRK_val ("remove_nas") == "1") {
    		$narm = ", na.rm=TRUE";
    	} else {
    		$narm = "";	// na.rm=FALSE is the default in all functions below
    	}
    ?>
    # ...
    results$foo <- foo (x<? echo ($narm); ?>)
    results$bar <- bar (x<? echo ($narm); ?>)
    results$foobar <- foobar (x<? echo ($narm); ?>)
    # ...
    <?
    }

## Writing a help page

When your plugin basically works, the time has come to provide a help page. While typically you will not want to explain all the underlying concepts in depth, you may want to add some more explanation for some of the options, and link to related plugins and R functions.

You may recall putting this inside your plugin-xml (if you haven't put this in, do so now):

    	<document>
    		[...]
    		<help file="filename.rkh" />
    		[...]
    	</document>

Where, obviously, you'd replace "filename" with a more appropriate name. Now it's time to create this .rkh file. Here is a self-descriptive example:

    	<!DOCTYPE rkhelp>
    	<document>
    		<summary>
    	In this section, you'll put some short, very basic information about what the plugin does.
    	This section will always show up on the very top of the help page.
    		</summary>

    		<usage>
    	The usage section may contain a little more practical information. It does not explain all
    	the settings in detail (that's done in the "settings" section), however.

    	To start a new paragraph, insert an empty line, as shown above.
    	This line, in contrast, will be in the same paragraph.

    	In all sections you can insert some simple HTML code, such as <b>bold</b> or
    	<i>italic</i> text. Please keep formatting to the minimum needed, however.

    	The usage section is always the second section shown in a help page.
    		</usage>

    		<section id="sectionid" title="Generic section" short_title="Generic">
    	If you need to, you can add additional sections between the usage and settings sections.
    	However, usually, you will not need this while documenting plugins. The "id"-attribute
    	provides an anchor point to jump to this section from the navigation menu. The "short_title"
    	attribute provides a short title to use in the navigation bar. This is optional, by default
    	the main "title" will be used both as a heading to the section, and as the link name in the
    	navigation bar.

    	In any section you may want to insert links to further information. You do this by adding

    	<link href="URL">link name</link>

    	Where URL could be an external link such as http://rkward.sourceforge.net .
    	Several special URLs are supported in the help pages:

    	<link href="rkward://page/path/page_id"/>

    	This links to a top level rkward help page (not for a plugin).

    	<link href="rkward://component/[namespace/]component_id"/>

    	This links to the help page of another plugin. The [namespace/] part may be omitted
    	(in this case, rkward is assumed as the standard namespace, e.g.:
    	<link href="rkward://component/import_spss"/> or
    	<link href="rkward://component/rkward/import_spss"/> are equivalent).
    	The component_id is the same that you specified in the .pluginmap.

    	<link href="rkward://rhelp/rfunction"/>

    	Links to the R help page on "rfunction".

    	Note that the link names will be generated automatically for these types of links.
    		</section>

    		<settings>
    			<caption id="id_of_tab_or_frame"/>
    			<setting id="id_of_elementa">
    	Description of the GUI element identified by the given id
    			</setting>
    			<setting id="id_of_elementb" title="description">
    	Usually the title of the GUI element will be extracted from the
    	XML definition of the plugin, automatically. However,
    	for some GUI elements, this description may not be enough to identify them, reliably.
    	In this case, you can add an explicit title using the "title" attribute.
    			</setting>
    			<setting id="id_of_elementc">
    	Description of the GUI element identified by "id_of_elementc"
    			</setting>
    			[...]
    		</settings>

    		<related>
    	The related section typically just contains some links, such as:

    	<ul>
    		<li><link href="rkward://rhelp/mean"/></li>
    		<li><link href="rkward://rhelp/median"/></li>
    		<li><link href="rkward://component/related_component"/></li>
    	</ul>
    		</related>

    		<technical>
    	The technical section (optional, always last) may contain some technical details of the plugin
    	implementation, which are of interest only to RKWard developers. This is particularily relevant
    	for plugins that are designed to be embedded in many other plugins, and could detail, which
    	options are available to customize the embedded plugin, and which code sections contain which
    	R code.
    		</technical>
    	</document>

## GUI logic

All the basic concepts of creating a plugin for &kapp; have been described in the previous chapters. Those basic concepts should be sufficient for many - if not most - cases. However, sometimes you want more control over how your plugin's GUI behaves.

For instance, suppose you want to extend the t-test example used in this documentation to allow both: comparing a variable against another variable (as shown), and comparing a variable against a constant value. Now, one way of doing this would be to add a radio-control that switches between the two modes, and adding a spinbox to enter the constant value to compare against. Consider this simplified example:

    <!DOCTYPE rkplugin>
    <document>
    	<code file="code.php"/>

    	<dialog label="T-Test">
    		<row>
    			<varselector id="vars"/>
    			<column>
    				<varslot id="x" type="numeric" source="vars" required="true" label="compare"/>
    				<radio id="mode" label="Compare against">
    					<option value="variable" checked="true" label="another variable (select below)"/>
    					<option value="constant" label="a constant value (set below)"/>
    				</radio>
    				<varslot id="y" type="numeric" source="vars" required="true" label="variable"/>
    				<spinbox id="constant" initial="0" label="constant" />
    			</column>
    		</row>
    	</dialog>
    </document>

So far so good, but there are a number of problems with this GUI. First, both the varslot and the spinbox are always shown, whereas only one of the two is really used. Worse, the varslot always requires a valid selection, even if you compare against a constant. Obviously, if we create a multi-purpose GUI like this, we want more flexibility. Enter: the <logic>-section (inserted at the same level as <code>, <dialog>, or <wizard>).

    	[...]
    	<code file="code.php"/>

    	<logic>
    		<convert id="varmode" mode="equals" sources="mode.string" standard="variable" />
    		<convert id="constmode" mode="equals" sources="mode.string" standard="constant" />

    		<connect client="y.required" governor="varmode" />
    		<connect client="y.visible" governor="varmode" />

    		<connect client="constant.required" governor="constmode" />
    		<connect client="constant.visible" governor="constmode" />
    	</logic>

    	<dialog label="T-Test">
    	[...]

The first two lines inside the logic section are <conver> tags. Those basically provide two new boolean (on or off, true or false) properties, which can be used later on. The first property ("varmode") is true, whenever the upper radio-button is selected and the second whenever the lower radio-button is selected. How is this done?

First, under sources, the "source" properties to work on are listed (in this case only one each; you could list several as sources="mode.string;somethingelse", then varmode would only be true, if both mode.string and somethingelse are equal to the string "variable"). Note that in this case we don't just write "mode" (as we would in getRK("mode"), but "mode.string". This is actually the internal way a radio control works: It has a property "string", which holds its string value. getRK ("mode") is just a shorthand, and equivalent to getRK ("mode.string"). See the reference for all properties of the different GUI elements.

Second, we set the mode of conversion to mode="equals". This means, we want to check, whether the sources are equal to a certain value. Finally standard is the value to compare against, so with standard="variable", we check whether the property mode.string is equal to the string "variable" (the value of the upper radio option). If it is equal, then the property varmode is true, else it is false.

The next line is basically the same, but reversed. Here we define a property ("constmode") which becomes true, if the second radio option is selected.

Now to the real stuff: We <connect> the "varmode" property to two different properties. Firstly, to y.required. This specifies, whether the varslot "y" is required or not. Secondly, to y.visible, which controls whether the varslot "y" is shown or not. Hence, if the upper radio-option is selected, the varslot "y" is required, and visible. Else it is not required and hidden.

We do just the reverse for the spinbox. So in effect, either the varslot is shown and required, or the spinbox is shown and required - depending on which option is selected in the radio control. The GUI is changing itself according to the radio option. Try the example, if you like.

Once again, for a complete list of properties, refer to the reference. One more property, however, is special in that all GUI elements have it: "enabled". This is slightly less drastic that "visible". It does not show/hide the GUI element, but only enables/disables it. Disabled elements are typically shown grayed out, and do not react to user input.

## Embedding Plugins into Plugins

When writing plugins, you will often find that you're creating a number of plugins that only differ in some respects, but have a lot more in common. For instance, for plotting, there are a number of generic R options that can be used with mostly all types of plots. Should you create a GUI and PHP-template for those over and over again?

Obviously that would be quite a hassle. Fortunately, you don't have to do that. Rather you create the common functionality once, and later you can embed it into several plugins. In fact it is possible to embed any plugin into any other plugin, even if the original author of the embedded plugin never thought, somebody would want to embed their plugin into another one.

### Embedding inside a dialog

Ok, enough said. How does it work? Simple: Just use the <embed> tag. Here's a stripped down example:

    <dialog>
    	<tabbook>
    		<tab [...]>
    			[...]
    		</tab>
    		<tab label="Plot Options">
    			<embed id="plotoptions" component="rkward::plot_options"/>
    		</tab>
    		<tab [...]>
    			[...]
    		</tab>
    	</tabbook>
    </dialog>

What happens here, is that the entire GUI or the plot options plugin (except of course for the standard elements like submit-button, etc.) is embedded right into your plugin (try it!).

As you can see the syntax of the <embed>-tag is fairly simple. It takes an id as most elements. The parameter component specifies which plugin to embed, as defined in the .pluginmap file ("rkward::plot_options" is the result of concatenating the namespace "rkward", a separator "::", and the name of the component "plot_options").

### Code generation when embedding

So far so good, but what about the generated code? How are the code for the embedding and embedded plugin merged? In the embedding plugin's PHP-code, simply write something like this:

    function printout () {
    [...] ?>
    myplotfunction ([...]<? getRK ("plotoptions.code.printout"); ?>)
    <? [...]
    }

So essentially, we're fetching the code generated by the embedded plugin just like we're fetchting any other GUI setting. Here the string "plotoptions.code.printout" can be deparsed to: "The printout section of the generated code of the element with the id plotoptions" (plotoptions is the id we gave for the <embed>-tag above). And yes, if you want advanced control, you can even fetch the values of individual GUI elements inside the embedded plugin (but not the other way around, as the embedded plugin does not know anything about its surroundings).

### Embedding inside a wizard

If your plugin provides a wizard GUI, embedding works basically in the same way. You'll generally use:

    	<wizard [...]>
    		[...]
    		<page id="page12">
    			[...]
    		</page>
    		<embed id="plotoptions" component="rkward::plot_options"/>
    		<page id="page13">
    			[...]
    		</page>
    		[...]
    	</wizard>

If the embedded plugin provides a wizard interface, its pages will be inserted right between page12 and page13 of your plugin. If the embedded plugin provides a dialog interface only, a single new page will be added between your pages page12 and page13. The user will never notice.

### Less embedded embedding: Further options button

While embedding is cool, you should be careful not to overdo it. Too many functions inside a GUI just make it hard to find the relevant options. Of course, sometimes you may want to embed a great deal of options (like all the options to plot ()), but as those are really optional, you don't want them prominently in your GUI.

An alternative is to embed those options "as a button":

    <dialog>
    	<tabbook>
    		[...]
    		<tab label="Options">
    			[...]
    			<embed id="plotoptions" component="rkward::plot_options" as_button="true" label="Specify plotting options"/>
    		</tab>
    		[...]
    	</tabbook>
    </dialog>

In this case, a single push button will be added to your plugin, labelled "Specify plotting options". When you press that button, a separate dialog will come up, with all the options of the embedded plugin. Even while this embedded GUI is not visible most of the time, you can fetch its settings just as described above.

Caution: Probably the "button" approach should only ever be used for plugins that can never be invalid (for missing/bad settings). Otherwise the user would not be able to submit the code, but might have a hard time finding out, the reason for that is hidden behind some button.

### Embedding/defining incomplete plugins

Some plugins - and as a matter of fact, the plot_options used as an example above, is one of them - are not complete by themselves. They simply do not have the GUI elements to select some important values. They are meant to be used only embedded into other plugins.

In how far is the plot_options plugin incomplete? Well, for some option settings, it needs to know the name of the objects/expressions for the x and y axes (actually it will do fine if it only has either, but it needs at least one to function properly). However, it does not have a mechansim of selecting those objects, or entering them any other way. So how does it know about them?

In the logic section of the plot_options plugin there are two additional lines, not covered, yet:

    	<logic>
    		<external id="xvar" />
    		<external id="yvar" />

    		[...]
    	</logic>

This defines two additional properties in the plot_options plugin, whose sole purpose is to be connected to some (yet unknown) properties of the embedding plugin. In the plot_options plugin those two properties are simply used like any other, and for instance there are calls to getRK("xvar") in the plot_options PHP template.

Now, for the incomplete plugin there is no way of knowing, where it will be embedded, and what the relevant settings in the embedding plugin will be called. So we need to add two additional lines in the embedding plugin's logic section as well:

    	<logic>
    		[...]

    		<connnect client="plotoptions.xvar" governor="xvarslot.available" />
    		<connnect client="plotoptions.yvar" governor="yvarslot.available" />
    	</logic>

This is nothing new in principle, we've covered <connect> statements in the chapter of GUI logic. You simply connect the values in two varlots (called "xvarslot" and "yvarslot" in this example) to the receiving "external" properties of the embedded plugin. That's it. Everything else is taken care of automatically.

## Dealing with many similar plugins

Sometimes, you may wish to develop plugins for a series of similar functions. As an example, consider the distribution plots. These generate fairly similar code, and of course it's desirable to make the graphical interfaces look similar to each other. Finally large sections of the help files can be identical. Only a few parameters are different for each plugin.

The naive approach to this is to develop one plugin, then basically copy and paste the entire contents of the .php, .xml, and .rkh files, then changing the few portions that are different. However, what if sometime later you find a spelling mistake that has been copied and pasted to all plugins? What if you want to add support for a new feature? You'd have to visit all plugins again, and change each single one. A tiresome and tedious process.

A second approach would be to use embedding. However, in some cases this does not lend itself well to the problem at hand, mostly because the "chunks" you can embed are sometimes too large to be useful, and it places some constraints on the layout. For these cases, the concepts including .php files including .xml files and snippets can be very useful (but see the thoughts on when it is preferrable to use embedding).

One word of caution, before you begin reading, though: These concepts can help making it simpler to deal with many similar plugins, and can improve maintainability and readability of those plugins. However, overdoing it can easily lead to the reverse effect. Use with some caution.

### Using the PHP include statement

Perhaps one of the most important features of PHP is that you can easily include one script file inside another. The value of this becomes immediately obvious, if some sections of your PHP code are similar across plugins. You can simply define those sections in a separate .php file, and include this in all the plugin .php files. For example, as in:

    <?
    // this is a file called "common_functions.php"

    function doCommonStuff () {
    	// perhaps fetch some options, etc.
    	// ...
    ?>
    # This is R code you want in several different plugins
    <?
    }
    ?>

    <?
    // this is one of your regular plugin .php files

    // include the common functions
    include ("common_functions.php");

    function calculate () {
    	// do something
    	// ...

    	// insert the common code
    	doCommonStuff ();
    }
    ?>

Note that sometimes it's even more useful to reverse this, and define the "skeleton" of preproces(), calculate(), and printout() functions is a common file, and make these call back for those part which are different across plugins. E.g.:

    <?
    // this is a file called "common_functions.php"

    function calculate () {
    	// do some things which are the same in all plugins
    	// ...

    	// add in something that is different across plugins
    	getSpecifics ();

    	// ...
    }
    ?>

    <?
    // this is one of your regular plugin .php files

    // include the common functions
    include ("common_functions.php");

    // note: no calculate() function is defined in here.
    // it in the common_functions.php, instead.

    function getSpecifics () {
    	// print some R code
    }
    ?>

One issue you should be aware of when using this technique is variable scoping. See the PHP manual on the keyword "global".

This technique is heavily used in the distribution plot and distribution CLT plot plugins, so you may want to look there for examples.

### Including .xml files

Basically the same feature of including files that is standard in PHP is also available for use in the .xml and .rkh files. At any place in these files you can place an <include> tag as shown below. The effect is that the entire contents of that XML file (to be precise: everything within the <document> tag of that file) is included verbatim at this point in the file. Note that you can only include another XML file.

    <document>
    	[...]
    	<include file="another_xml_file.xml"/>
    	[...]
    </document>

The attribute "file" is the filename relative to the directory the current file is located in.

### Using <snippets>

While including files as shown in the previous section is fairly powerful, it become most useful when used in combination with <snippets>. Snippets are really smaller sections which you can insert at another point in the file. An example illustrates this best:

    <document>
    	<snippets>
    		<snippet id="note">
    			<frame>
    				<text>
    		This will be inserted at two places in the GUI
    				</text>
    			</frame>
    		</snippet>
    	</snippets>
    	<dialog label="test">
    		<column>
    			<insert snippet="note"/>
    			[...]
    			<insert snippet="note"/>
    		</column>
    	</dialog>
    </document>

Hence, you define the snippet at one place at the top of the xml file, and then you <insert> it at any place(s) you wish.

While this example is not too useful in itself, think about combining this with an <include>d .xml file. Note, that you can also place snippets for the .rkh file in the same file. You'd simply <include> the file there as well, and <insert> the relevant snippet:

    <!-- This is a file called "common_snippets.xml" -->
    <document>
    	<snippet id="common_options">
    		<spinbox id="something" [...]/>
    		[...]
    	</snippet>
    	<snippet id="common_note">
    		<text>An important note for this type of plugin</text>
    	</snippet>

    	<snippet id="common_help">
    		<setting id="something">This does something</setting>
    		[...]
    	</snippet>
    </document>

    <!-- This is the .xml file of the plugin -->
    <document>
    	<snippets>
    		<!-- Import the common snippets -->
    		<include file="common_snippets.xml"/>
    	</snippets>

    	<dialog label="test2">
    		<insert snippet="common_note"/>
    		<spinbox id="something_plugin_specific" [...] />
    		<insert snippet="common_options"/>
    	</dialog>
    </document>

Similar to inclusion in PHP, the reverse approach is often even more useful:

    <!-- This is a file called "common_layout.xml" -->
    <document>
    	<column>
    		<insert snippet="note">
    		[...]
    		<insert snippet="plugin_parameters">
    	</column>
    	[...]
    </document>

    <!-- This is the .xml file of the plugin -->
    <document>
    	<snippets>
    		<snippet id="note">
    			<text>The note used for this specific plugin</text>
    		</snippet>

    		<snippet id="plugin_parameters">
    			<frame label="Parameters specific to this plugin">
    				[...]
    			</frame>
    		</snippet>
    	</snippets>

    	<dialog label="test3">
    		<include file="common_layout.xml"/>
    	</dialog>
    </document>

Finally, it is also possible to <insert> snippets into other snippets, provided that: a) there is only one level of nesting, and b) the <snippets> section is placed at the top of the file (before a nested snippet is inserted); this is because <insert> statements are resolved from top to bottom.

### <include> and <snippets> vs. embedding

At first glance, <include> and <snippets> provides functionality rather similar to embedding: It allows to reuse some portions of code across plugins. So what's the difference between these approaches, and when should you use which?

The key difference between these concepts is that embeddable plugins are a more tight bundle. They combine a complete GUI, code to generate R code from this, and a help page. In contrast, include and insert allow much more fine grained control, but at the price of less modularity.

That is, a plugin embedding another plugin will typically not need to know much about the internal details of the embedded plugin. A prime example is the plot_options plugin. Plugins wishing to embed this do not necessarily need to know about all the options provided, or how they are provided. This is a good thing, as otherwise a change in the plot_options plugin might make it necessary to adjust all plugins embedding this (a lot). In contrast, include and insert really exposes all the internal details, and plugins using this will - for example - need to know the exact ids and perhaps even the type of the elements used.

Hence the rule of thumb is this: include and insert are great if the relevant options are only needed for a clearly limited group of plugins. Embedded plugins are better, if the group of plugins it may be useful to is not clearly defined, and if the functionality can easily be modularized. Another rule of thumb: If you can put the common portions into a single "chunk", then do so, and use embedding. If you need lots of small snippets to define the common portions - well, use <snippets>. A final way to look at it: If all plugins provide highly similar functionality, includes and inserts are probably a good idea. If they merely share one or two common "modules", embedding is likely better.

## Concepts for use in specialized plugins

This chapter contains information on some topics that are useful only to certain classes of plugins.

### Preview functionality for graphing plugins

A very useful feature for all plugins generating a plot / graph is to provide an automatically updating preview. To do so, you will need two things: Adding a <preview>-checkbox to your GUI definition, and adjusting the generated code for the preview. We will deal with both in turn.

Adding a <preview>-checkbox is simple. Just place the following somewhere in your GUI. It will take care of all the behind-the-scenes magic of creating a preview device, updaing the preview whenever the setting have changed, etc. Example:

    <document>
    	[...]
    	<dialog [...]>
    		[...]
    		<preview id="preview"/>
    		[...]
    	</dialog>
    	[...]
    </document>

And that's it for the GUI definition.

Adjusting the PHP template is a little more work. You will have to create a new function called "preview" in addition to the "preprocess", "calculate", etc. functions. This function should generate the code needed to produce the plot, and only that. Esp. no printing of headers, rk.graphics.on(), or similar calls. Below is an example of the typical pattern that you will use:

    <?php
    function preprocess () {
    	// the "somepackage" is needed to create the plot
    ?>
    require (somepackage)
    <? [...]
    }

    function calculate () {
    	// empty in this example
    }

    function printout () {
    	// all the real work is moved to a custom defined function doPrintout (), below

    	doPrintout (true);	// true in this case means: We want all the headers that should be printed in the output
    }

    function preview () {
    	// we call all stages of the general code. Only the printout () function need to be slightly different
    	preprocess ();
    	calculate ();
    	doPrintout (false);
    }

    function doPrintout ($final) {
    	// this function takes care of generating the code for the printout() section. If $final is set to true,
    	// it generates the full code, including headers. If $final is set to false, only the essentials will
    	// be generated.

    	if ($final) { ?>
    rk.header ("An example plot")

    rk.graph.on ()
    <	}
    	// only the following section will be generated for $final==false
    ?>
    try ({plot (5, 5)})
    <	if ($final) { ?>
    rk.graph.off ()
    	}
    <?
    }
    ?>

That's it, your plugin should now be preview-enabled.

### Context-dependent plugins

So far we have assumed, all plugins are always meaningful, and all placed in the main menu. However, some plugins are meaningful only (or additionally) in a certain context. For instance a plugin to export the contents of an R X11 graphics device is obviously most useful, when placed in the menu of an X11 device, not in the main menubar. Also, such a plugin should know about the device number that it should operate on, without having to ask the user about this.

We call such plugins context-dependent. Correspondingly, in the .pluginmap file, they are not (or not only) placed in the main <hierarchy> but rather into a <context> element. So far only two different contexts are supported (more will come later): x11 and file import. We'll deal with those in turn. Even if you are only interested in the import context, please also read the section on the x11 context, as this is slightly more elaborate.

#### X11 device context

To use a plugin in the context of an x11 device - that is place it in the menu bar of the window you get when you call "x11 ()" in the cosonle, first declare it as usual in the .pluginmap file:

    <document [...]>
    	<components>
    		[...]
    		<component id="my_x11_plugin" file="my_x11_plugin.xml" label="An X11 context plugin"/>
    		[...]
    	</components>

However, you do not need to define it in the hierarchy (you can, if it is also meaningful as a top-level plugin):

    	<hierarchy>
    		[...]
    	</hierarchy>

Instead, add a definition of the "x11" context, and add it to the menus there:

    	<context id="x11">
    		[...]
    		<menu id="edit">
    			[...]
    			<entry id="my_x11_plugin"/>
    		</menu>
    	</context>
    </document>

In the logic section of the plugin xml, you can now declare two <external> properties: "devnum" and "context". Context (if declared) will be set to "x11" when the plugin is invoked in this context. "devnum" will be set to the number of the graphics device to operate on. And that's all.

#### Import data context

Before reading this section, please make sure to read the section on the X11 device context, as that explains the basic concepts.

The "import" context is used to declare import file filter plugins. You simply place those in a context with id="import" in the .pluginmap file. However, there is one additional twist when declaring these plugins: In order to offer a unified file selection dialog for all supported file types, you need to declare one additional bit of information on your component:

    <document [...]>
    	<components>
    		[...]
    		<component id="my_xyz_import_plugin" file="my_xyz_import_plugin.xml" label="Import XYZ files">
    			<attribute id="format" value="*.xyz *.zyx" label="XYZ data files"/>
    		</component>
    		[...]
    	</components>
    	<hierarchy>
    		[...]
    	</hierarchy>
    	<context id="import">
    		[...]
    		<menu id="import">
    			[...]
    			<entry id="my_xyz_import_plugin"/>
    		</menu>
    	</context>
    	[...]
    </document>

The attribute line simply says, that the associate filename extensions for XYZ files are *.xyz or *.zyx, and that the filter should be labelled "XYZ data files" in the file selection dialog.

You can declare two <external> properties in your plugin. "filename" will be set to the selected file name, and "context" will be set to "import".

## Reference

### Types of properties / Modifiers

At some places in this introduction we've talked about "properties" of GUI elements or otherwise. In fact there are several different types of properties. Usually you do not need to worry about this, as you can use common sense to connect any property to any other property. However, internally, there are different types of properties. What this matters for, is when fetching some special values in the PHP-template. In getRK ("id") statements you can also specify some so called "modifiers" like so: getRK ("id.modifier"). This modifier will affect, in which way the value is printed. Read on for the list of properties, and the modifiers they each make available:

String properties

- The most simple type of property, used to simply hold a piece of text. It does not provide any modifiers. If you attempt to fetch modified values from the PHP template, it will return the usual value, and a warning will be written to the terminal you're running rkward from.

Boolean properties

- Properties that can either be on or off, true or false. For instance the properties created by <convert>-tags, also the property accompanying a <checkbox> (see below). The following values will be returned according to the given modifier:

  No modifier ("")

- By default the property will return the string "TRUE", if it is true, and "FALSE" otherwise. Boolean properties attached to a checkbox behave slightly differently, and return the strings you specified in the "value" and "value_unchecked" attributes.

"true"

- Return the string as if the property was true, even if it is false

"false"

- Return the string as if the property was false, even if it is true

"not"

- This actually returns another Boolean property, which is the reverse of the current (i.e. false if true, true if false)

"numeric"

- Return the string "1" if the property is true, or "0" if it is false

Integer properties

- A property designed to hold an integer value (but of course it still returns a numeric character string to the PHP-template). It does not accept any modifiers. Used in <spinbox>es (see below)

Real number properties

- A property designed to hold a real number value (but of course it still returns a numeric character string to the PHP-template). It does not accept any modifiers. Used in <spinbox>es (see below)

RObject properties

- A property designed a selection of one or more R objects. Used most porminently in varselectors and varslots. The following values will be returned according to the given modifier:

  No modifier ("")

- By default the property will the full name of the selected object. If more than one object is selected, the object names will be separated by linebreaks ("\n").

"shortname"

- Like above, but returns only short name(s) for the object(s). For instance an object inside a list would only be given the name it has inside the list, without the name of the list.

"label"

- Like above, but returns the &kapp; label(s) of the object(s) (if no label availabe, this is the same as shortname)

Code properties

- A property held by plugins that generated code. This is important for embedding plugins, in order to embed the code generated by the embedded plugin into the code generated by the embedding (top-level) plugin. The following values will be returned according to the given modifier:

  No modifier ("")

- Returns the full code, i.e. the sections "preprocess", "calculate", "printout", and (but not "preview") concatenated to one string.

"preprocess"

- Returns only the preprocess section of the code

"calculate"

- Returns only the calculate section of the code

"printout"

- Returns only the printout section of the code

"preview"

- Returns the preview section of the code

### General purpose elements to be used in any XML file (.xml, .rkh, .pluginmap)

<snippets>

- Allowed as a direct child of the <document> node and only there. Should be placed near the top of the file. See section on using snippets. Only one <snippets> element may be present. Optional, no attributes.

<snippet>

- Defines a single snippet. Allowed only as a direct child of the <snippets/> element. Attributes:

  <id>

- An identifier string for the snippet. Required.

<insert>

- Insert the contents of a <snippet>. Allowed anywhere. Attributes:

  <snippet>

- The identifier string of the snippet to insert. Required.

<include>

- Include the contents of another xml file (everything inside the <document> element of that file). Allowed anywhere. Attributes:

  <file>

- The filename, relative to the directory, the current file is in. Required.

### Elements to be used in the XML description of the plugin

Properties held by the elements are listed in a separate section.

#### General elements

<document>

- Needs to be present in each description.xml-file as the root-node. No special function. No attributes

<code>

- Defines where to look for the PHP template to the plugin. Use only once per file, as a direct child of the document-tag. Attributes:

  <file>

- Filename of the PHP template, relative to the directory the plugin-xml is in

<help>

- Defines where to look for the help file for the plugin. Use only once per file, as a direct child of the document-tag. Attributes:

  <file>

- Filename of the help file, relative to the directory the plugin-xml is in

<copy>

- Can be used as a child (direct or indirect) of the main layout elements, i.e. <dialog> and <wizard>. This is used to copy an entire block a xml elements 1:1. Attributes:

  <id>

- The id to look for. The <copy> tag will look for a previous XML element that has been given the same id, and copy it including all descendent elements.

<copy_element_tag_name>

- In some few cases, you will want an almost literal copy, but change the tag-name of the element to copy. The most important example of this is, when you want to copy an entire <tab> from a dialog interface to the <page> of a wizard interface. In this case, you'd set coyp_elemnent_tag_name="page" to do this conversion automatically.

#### Interface definitions

<dialog>

- Defines a dialog-type interface. Place the GUI-definition inside this tag. Use only once per file, as a direct child of the document-tag. At least one of "dialog" or "wizard" tags is required for a plugin. Attributes:

  <label>

- Caption for the dialog

<wizard>

- Defines a wizard-type interface. Place the GUI-definition inside this tag. Use only once per file, as a direct child of the document-tag. At least one of "dialog" or "wizard" tags is required for a plugin. Accepts only <page> or <embed>-tags as direct children. Attributes:

  <label>

- Caption for the wizard

#### Layout elements

All elements in this section accept an attribute id="identifierstring". This attribute is optional for all elements. It can be used, for example, to hide/disable the entire layout element and all the elements contained therein (see chaper GUI logic). The id-string may not contain "." (dot) or ";" (semicolon), and should generally be limited to alphanumeric characters and the underscore ("_"). Only the additional attributes are listed.

<page>

- Defines a new page inside a wizard. Only allowed as a direct child of a <wizard> element.

<row>

- All direct children of a "row" tag will be placed left-to-right.

<column>

- All direct children of a "column" tag will be placed top-to-bottom.

<stretch>

- By default, elements in the GUI take up all the space that's available. For instance, if you have two columns side by side, the left one is packed with elements, but the right one only contains a lonely <radio>, the <radio> control will expand vertically, even though it does not really need the available space, and it will look ugly. In this case you really want to add a "blank" below the <radio>. For this, use the <stretch> element. It will simply use up some space. Don't overuse this element, usually it's a good idea for GUI elements to get all the available space, only sometimes will the layout become spaced out. The <stretch> element does not take any arguments, not even an "id". Also you can place no children inside the <stretch> element (in other words, you'll only ever use it as "<stretch/>")

<frame>

- Draws a frame/box around its direct children. Can be used to visually group related options. Layout inside a frame is top-to-bottom, unless you place a <row> inside. Attributes:

  <label>

- Caption for the frame (optional)

<tabbook>

- Organizes elements in a tabbook. Accepts only <tab>-tags as direct children.

<tab>

- Defines a page in a tabbook. Place the GUI-definition for the tab inside this tag. May be used only as a direct child of a <tabbook> tag. A <tabbook> should have at least two defined tabs. Attributes:

  <label>

- Caption for the tab page (required)

<text>

- Shows the text enclosed in this tag in the GUI. Linebreaks are interpreted as hard linebreaks! Attributes:

  <type>

- Type of the text. One of "normal", "warning" or "error". This influences the look of the text (optional, defaults to normal)

#### Active elements

All elements in this section accept an attribute id="identifierstring". This attribute is required for all elements. Only the additional attributes are listed. The id-string may not contain "." (dots).

<varselector>

- Provides a list of availabe objects from which the user can select one or more. Requires one or more <varslot>s as a counterpart to be useful. Attributes:

  <label>

- Label for the varselector (optional, defaults to "Select variable(s)")

<varslot>

- Used in conjunction with a "varselector" to allow the user to select one or more variables. Attributes:

  <label>

- Label for the varslot (recommended, defaults to "Variable:")

<source>

- The varselector to fetch the selection from (required, unless you connect manually)

<required>

- Whether - for submitting the code - it is required that this varslot holds a valid value. See required-property (optional, defaults to false)

<multi>

- Whether the varslot holds only one (default, "false"), or several objects

<min_vars>

- Only meaningful if multi="true": Minimum number of vars to be selected for the selection to be considered valid (optional, defaults to "1")

<min_vars_if_any>

- Only meaningful if multi="true": Some varslots may be considered valid, if, for instance, the varslot is either empty, or holds at least two values. This specifies how many variables have to be selected if any at all (2 in the example). (optional, defaults to "1")

<max_vars>

- Only meaningful if multi="true": Maximum number of variables to select (optional, defaults to "0", which means no maximum)

<classes>

- If you specify one or more R classnames (separated by spaces (" ")), here, the varslot will only accept objects belonging to those classes (otional, use with great care, the user should not be prevented from making valid choices, and R has a lot of different classes!)

<types>

- If you specify one or more variables types (separated by spaced (" ")), here, the varslot will only accept objects of those types. Valid types are "unknown", "number", "string", "factor", "invalid". (Optional, use with great care, the user should not be prevented from making valid choices, and rkward does not always know the type of a variable)

<num_dimensions>

- The number of dimensions, an object needs to have. "0" (the default) means, any number of dimensions is acceptable. (optional, defaults to "0")

<min_length>

- The minimum length, an object needs to have in order to be acceptable. (optional, defaults to "0")

<max_length>

- The maximum length, an object needs to have in order to be acceptable. (optional, defaults to the largest integer number representable on the system)

<radio>

- Defines a group of radio-exclusive buttons (only one can be selected at a time). Requires at least two <option>-tags as direct children. No other tags are allowed as children. Attributes:

  <label>

- Label for the radio control (recommended, defaults to "Select one:")

<dropdown>

- Defines a group of options of which one and only one can be selected at the same time, using a dropdown list. This is functionaly equivalent to a <radio>, but looks different. Requires at least two <option>-tags as direct children. No other tags are allowed as children. Attributes:

  <label>

- Label for the dropdown list (recommended, defaults to "Select one:")

<option>

- Can only be used as a direct child of a <radio> or <dropdown> element. Represents one selectable option in a radio control or dropdown list. Specifying the "id" parameter for the <option> elements is optional (and in fact it's recommended, not to set an "id", unless you plan to really use it to disable single options). Only the parent element (<radio> or <dropdown>) needs one. Attributes:

  <label>

- Label for the option (required)

<value>

- The string value the parent element will return if this option is checked/selected (required)

<checked>

- Whether the option should be checked/selected by default "true" or "false". Only one button in a <radio> may be set to checked="true". If no option is set to checked, the first option in the parent element will be checked/selected automatically. (optional, default to "false")

<checkbox>

- Defines a checkbox, i.e. a single option that can either be set to on or off. Attributes:

  <label>

- Label for the checkbox (required)

<value>

- The value the checkbox will return if checked (required)

<value_unchecked>

- The value that will be returned if the checkbox is not checked (optional, defauls to "", i.e. an empty string)

<checked>

- Whether the option should be checked by default "true" or "false" (optional, default to "false")

<input>

- Defines a free text input field. Attributes:

  <label>

- Label for the input field (required)

<initial>

- Initial text of the text field (optional, defaults to "", i.e. an empty string)

<size>

- One of "small", "medium", or "large". "large" defines a multi-line input field, "small", and "medium" are single line fields (optional, defaults to "medium")

<required>

- Whether - for submitting the code - it is required that this input is not empty. See required-property (optional, defaults to false)

<browser>

- An element designed to select a single filename (or directory name). Note that this field will take any string, even though it is meant to be used for files, only:

  <label>

- Label for the browser (optinal, defaults to "Enter filename")

<initial>

- Initial text of the browser (optional, defaults to "", i.e. an empty string)

<type>

- One of "file", "dir", or "savefile". To select an existing file, existing directory, or non-existing file, respectively (optional, defaults to "file")

<filter>

- File type filter, e.g. ("*.txt *.csv" for .txt and .csv files. Try not to induce limits unless absolutely needed, though) (optional, defaults to "", i.e. all files)

<required>

- Whether - for submitting the code - it is required that the field is not empty. Note that this does not necessarily mean, the selected filename is valid! See required-property (optional, defaults to true)

<saveobject>

- An element designed to select the name of an R object to save to (i.e. generally not already existing, in contrast to a varslot):

  <label>

- Label for the input (optinal, defaults to "Save to:")

<initial>

- Initial text of the input (optional, defaults to "my.data")

<required>

- Whether - for submitting the code - it is required that the field holds a permissible object name. See required-property (optional, defaults to true)

<spinbox>

- A spinbox in which the user can select a numeric value, using either direct keyboard input or small up/down arrows. Attributes:

  <label>

- Label for the spinbox (recommend, default to "Enter value:")

<min>

- The lowest value the user is allowed to enter in the spinbox (optional, defaults to the lowest value technically representable in the spinbox)

<max>

- The largest value the user is allowed to enter in the spinbox (optional, defaults to the highest value technically representable in the spinbox)

<initial>

- The initial value shown in the spinbox (optional, defaults to "0")

<type>

- One of "real" or "integer". Whether the spinbox will accept real numbers or only integers (optional, defaults to "real")

<default_precision>

- Only meaningful if the spinbox is of type="real". Specifies the default number of decimal places shown in the spinbox (only this many trailing zeros will be shown). When the user presses the up/down arrows, this decimal place will be changed. The user may still be able to enter values with a higher precision, however (see below) (optional, defaults to "2")

<max_precision>

- The maximum number of digits that can be meaningfully represented (optional, defaults to "8")

<formula>

- This advanced element allows the user to select a formula/set of interactions from selected variables. For instance for a GLM, this element can be used to allow the user to specify the interaction-terms in the model. Attributes:

  <fixed_factors>

- The id of the varslot holding the selected fixed factors (required)

<dependent>

- The id of the varslot holding the selected dependent variable (required)

<embed>

- Embed a different plugin into this one (see chapter on embedding). Attributes:

  <component>

- The registered name of the component to embed (see chapter on registering components (required)

<as_button>

- If set to "true", only a pushbutton will be placed in the embedding GUI, the embedded GUI will only be shown (in a separate window) when the pushbutton is pressed (optional, default is "false")

<label>

- Only meaningful if as_button="true": The label of the button (recommend, default is "Options")

<preview>

- Checkbox to toggle preview functionality (see chapter on graph previews). Attributes:

  <label>

- Label of the box (optional, default is "Preview")

#### Logic section

<logic>

- The containing element for the logic section. All elements below are allowed only inside the <logic> element. Only one <logic> element is allowed per document, as a direct child of the <document> element. The logic section applies to both <dialog> and <wizard> GUIs in the same way.

<external>

- Creates a new (string) property that is supposed to be connected to an outside property if the plugin gets embedded. See section on "incomplete" plugins. Attributes:

  <id>

- The id of the new property (required)

<default>

- The default string value of the new property, i.e. the value used, if the property is not connected to an outside property (optional, defaults to an empty string)

<set>

- Set a property to a fixed value (of course, if you additionally connect the property to some other property, the value does not remain fixed). For instance, if you embed a plugin, but want to hide some of its elements, you might set the visibility property of those elements to false. Useful esp. for embedded/embedding plugins. Attributes:

  <id>

- The id of the property to set (required)

<to>

- The string value to set the property to (required). Note: For boolean properties such as visibility, enabledness, you'll typically set the to attribute to either to="true" or to="false".

<convert>

- Create a new boolean properties that depends on the state of one or more different properties. Attributes:

  <id>

- The id of the new property (required)

<sources>

- The ids of the properties this property will depend on. One or more properties may be specified, separated by ";" (required)

<mode>

- The mode of conversion/operation. One of "equals", "notequals", "range", "and", "or". If in mode equals, the property will only be true, if the value of all of its sources equals the attribute standard (see below). If in at mode notequals, the property will only be true, if the value of all of its sources are different from the attribute standard (see below). If in mode range, the sources have to be numeric (integer or real). The property will only be true, if all sources are in the range specified by the attributes min and max (see below). If in mode and, the sources have to be boolean properties. The property will only be true, if all the sources are true simultaniously. If in mode or, the sources have to be boolean properties. The property will only be true, if at least one of the sources is true. (required)

<standard>

- Only meaningful in modes equals or notequals: the string value to compare against (required if in one of these modes)

<min>

- Only meaningful in mode range: the minimum value to compare against (optional, defaults to the lowest floating point number representable on the machine)

<max>

- Only meaningful in mode range: the maximum value to compare against (optional, defaults to the largest floating point number representable on the machine)

<require_true>

- If set to "true", the property will become required, and will only be considered valid, if its state is true/on. Hence, if the property is false, it will block the submit button (optional, defaults to "false". Caution: If you use this, make sure the user can easily detect what's wrong, such as by showing an explanatory <text>)

<connect>

- Connects two properties. The client property will be changed whenever the governor property changes (but not the other way around!). Attributes:

  <client>

- The id of the client property, i.e. the property that will be adjusted (required)

<governor>

- The id of the governor property, i.e. the property that will adjusts the client property. This may include a modifier (required)

<reconcile>

- If "true", the client property will make adjust the governor property on connection in such a way that the governor property will only accept values that are also acceptable by the client (e.g. suppose the governor is a numeric property with min value "0", and the client is a numeric property with min value "100". The min of both properties will be adjusted to 100, if reconcile="true"). Generally works only for properties of the same basic type (optional, default to "false")

### Properties of plugin elements

All layout elements, and all active elements hold the following properties, accessible via "id_of_element.name_of_property":

visible

- Whether the GUI element is visible or not (boolean)

enabled

- Whether the GUI element is enabled or not (boolean)

required

- Whether the GUI element is required (to hold a valid setting) or not. If you set an element to not enabled/not visible, you should also set it to not required! (boolean)

In addition to this, some elements have additional properties you can connect to. Most active elements also have a "default" property whose value will be returned on calls to getRK ("..."), if no specific property was named, as described below.

<text>

- Default property is text

  text

- The text displayed (text)

<varselector>

- No default property

  available

- All objects available for selection. You probably do not want to use this. Used internally (RObject)

selected

- The objects currently selected. You probably do not want to use this. Used internally (RObject)

<varslot>

- Default property is "available"

  available

- All objects held in the varslot (RObject)

selected

- Of the objects held in the varslot, those that are currently selected. You probably do not want to use this. Used internally (RObject)

source

- A copy of the objects selected in the corresponding varselector. You probably do not want to use this. Used internally (RObject)

<radio>

- Default property is "string"

  string

- The value of the currently selected option (string)

number

- The number of the currently selected option (options are numbered top-to-bottom, starting at 0) (integer)

<dropdown>

- Default property is "string"

  string

- The value of the currently selected option (string)

number

- The number of the currently selected option (options are numbered top-to-bottom, starting at 0) (integer)

<option>

- No default property. "enabled" is the *only* proptery. It does not have the "visible" or "required" properties.

  enabled

- Whether this single option should be enabled or disabled. In most cases you will enable/disable the entire <radio< or <dropdown<, instead. But this can be used to dynamically set the enabledness of a single option inside a <radio< or <dropdown< (bool)

<checkbox>

- Default property is "state"

  state

- State of the checkbox (on or off). Note that useful modifiers of this property (as of all boolean properties) are "not" and "numeric" (see types of properties). (boolean)

<input>

- Default property is "text"

  text

- Current text in the input field (string)

<browser>

- Default property is "selection"

  selection

- Current text (selected file name) in the browser (string)

<saveobject>

- Default property is "selection"

  selection

- Current text (selected object name) (string)

<spinbox>

- Default property is either "int" or "real" depending on the spinbox's mode

  int

- Integer value held by the spinbox, or nearest integer, if in real mode (integer)

real

- Real value held by the spinbox (and integer, if in integer) (real)

<formula>

- Default property is "model"

  model

- The current model string (string)

table

- The data.frame holding the required variables. If variables from only one data.frame are used, the name of that data.frame is returned. Otherwise a new data.frame is constructed as required (string)

labels

- If variables from multiple data.frames are involved, their names may get mangled (for instance, if both data.frames contain a variable named "x"). This returns a list with the mangled names as indices and the descriptive label as value (string)

fixed_factors

- The fixed factors. You probably do not want to use this. Used internally (RObject)

dependent

- The dependent variable(s). You probably do not want to use this. Used internally (RObject)

<embed>

- No default property

  code

- The code generated by the embedded plugin (code)

<preview>

- Default property is "state"

  state

- Whether the preview box is checked (not necessarily whether the preview has already been shown) (boolean)

<convert>

- This element (used in the <logic> section) is special, in that is technically *is* a property, instead of just holding one or more properties. It is of boolean kind. Note that useful modifiers of this property (as of all boolean properties) are "not" and "numeric" (see types of properties)

### Elements for use in .pluginmap files

<document>

- Needs to be present in each .pluginmap file as the root-node (exactly once). Attributes:

  base_prefix

- Filenames specified in the pluginmap file are assumed to be relative to the directory of the .pluginmap-file + the prefix you specify here. Useful, esp., if all your components are located below a single subdirectory.

namespace

- A namespace for the component ids. When looking up components for embedding, the components will beretrievable via a string "namespace::component_id". Set to "rkward" for now.

<components>

- Needs to be present exactly once as a direct child of the <document> element. Contains the individual <component>-elements described below. No attributes.

<component>

- One or more <component> elements should be given as direct children of the <components> element (and only there). Registers a component/plugin with rkward. Attributes:

  type

- For future extension: The type of component/plugin. Always set to "standard" for now (the only type currently supported).

id

- The id by which this component can be retrieved (for placing it in the menu (see below), or for embedding). See <document/gt;-namespace above.

file

- Required at least for components of type="standard": The filename of the XML file describing the GUI.

label

- The label for this component, when placed in the menu hierarchy.

<attribute>

- Defines an attribute of a component. Only meaningful for import plugins so far. Only allowed as a direct child of <component>. Attributes:

  id

- Id of the attribute

value

- Value of the attribute

labels

- Label associated with the attribute

<hierarchy>

- Needs to be present exactly once as a direct child of the <document> element. Described where the components declared above should be placed in the menu hierarchy. Accepts only <menu> elements as direct children. No attributes.

<menu>

- One or more <menu> elements should be given as direct children of the <hierarchy> element. Declares a new (sub-)menu. If a menu by the given id (see below) already exists, the two menus are merged. The <menu> element is allowed either as a direct child of the <hierarchy> element (top level menu), or as the direct child on any other <menu> element (sub-menu). Conversely, the <menu> element accepts other <menu> elements or <entry> elements as children. Attributes:

  id

- An identifier string of the menu. Useful, when menu-definitions are read from several .pluginmap-files, to make sure plugins can be placed in the same menu(s). Some menu-ids such as "file" refer to predefined menus (in this case the "File" menu). Be sure to check with existing .pluginmap-files to use consistent ids.

label

- A label for the menu.

index

- Useful, when menu-definitions are read from several .pluginmap-files, to have control over the order in which (sub-)menus are placed inside a hierarchy level. Note that the index is not absolute (since more than one .pluginmap file may be read, more than one element at this hierarchy level may have the same id), but you can safely assume that an element with index="4" will be placed somewhere below an element which index="3" and above one with index="5" (optional, default is "-1", for add at end).

<entry>

- A menu entry, i.e. a menu-option to invoke a plugin. May be used only as a direct child of a <menu> element, accepts no child elements. Attributes:

  component

- The id of the component that should be invoked, when this menu entry is activated.

index

- See <menu index="..."> above.

<context>

- Declares the entries in a context. Only allowed as a direct child of the <document> tag. Accepts only <menu> tags as direct children. Attributes:

  id

- The id of the context. Only two contexts are implemented so far: "x11" and "import".

<require>

- Include another .pluginmap file. This .pluginmap file is only loaded once, even if it is <require>d from several other files. The most important use case is to include a pluginmap file, which declares some comopnents, which are embedded by components declared in this .pluginmap. <require>-elements are only allowed as direct children of the <document>-node. Attributes:

  file

- The filename of the .pluginmap to include. This is seen relative to the directory of the current .pluginmap file + the base_prefix (see above, <document>-element).

### Elements for use in .rkh (help) files

<document>

- Needs to be present in each .rkh file as the root-node (exactly once). No attributes.

<title>

- Title of the help page. This is not interpreted for help pages for a plugin (this takes the title from the plugin itself), only for stand-alone pages. No attributes. The text contained within the <title> tag will become the caption of the help page. May only be defined once, as a direct child of the <document> node.

<summary>

- A short summary of the help page (or what this plugin is used for). This will always be shown at the top of the help page. No attributes. The text contained within the <summary> tag will be displayed. Recommended but not required. May only be defined once, as a direct child of the <document> node.

<usage>

- A slightly more elaborate summary of the usage. This will always be shown directly after the <summary>. No attributes. The text contained within the <usage> tag will be displayed. Recommended for plugin help pages, but not required. May only be defined once, as a direct child of the <document> node.

<section>

- A general purposes section. May be used any number of times as a direct child of the <document> node. These sections are displayed in the order of their definition, but all after the <usage> section and before the <settings> section. The text contained within the <sectoin> tag will be displayed.

  id

- An identifier needed to jump to this section from the navigation bar (or a link). Needs to be unique within the file. Required, no default.

title

- The title (caption) of this section. Required, no default.

short_title

- A short title suitable to be displayed in the navigation bar. Optional, defaults to the full title.

<settings>

- Defines the section containing reference on the various GUI settings. Only meaningful and only used for plugin related help pages. Use as a direct child of the <document>. May contain only <setting> and <caption> elements as direct children. No attributes.

<setting>

- Explains a single setting in the GUI. Only allowed as a direct child of the <settings> element. The text contained within the element is displayed.

  id

- The id of the setting in the plugin .xml. Required, no default.

title

- An optional title for the setting. If omitted (omission is recommended in most cases), the title will be taken from the plugin .xml.

<caption>

- A caption to visually group several settings. May only be used as a direct child of the <settings> element.

  id

- The id of the corresponding element (typically a <frame>, <page> or <tab>) in the plugin .xml.

title

- An optional title for the caption. If omitted (omission is recommended in most cases), the title will be taken from the plugin .xml.

<related>

- Defines a section containing links to further related information. Will always be displayed after the <settings> section. Use as a direct child of the <document>. May contain only <setting> and <caption> elements as direct children. No attributes.

<technical>

- Defines a section containing technical information of no relevance to end users (such as internal structure of the plugin). Will always be displayed last in a help page. Use as a direct child of the <document>. May contain only <setting> and <caption> elements as direct children. No attributes.

<link>

- A link. Can be used in any of the sections described above.

  href

- The target url. Note that several rkward specific URLs are available. See section on writing help pages for details.

<various html tags>

- Most basic html tags are allowed within the sections. Please keep manual formatting to a minimum, however.

## Troubleshooting during plugin development

So you've read all the documentation, did everything right, and still can't get it to work? Don't worry, we'll work it out. First thing to do is: Run rkward in a terminal/console, and watch out for messages on the console. As a general rule of thumb, you should not see any output when your plugin gets invoked, or at any other time (other than the startup message). If there is one, it's likely related to your plugin. See if it gets you anywhere.

If everything seems fine on the console, try to increase the debug-level with `rkward --debug-level 3` (you may also use debug-level 4, or even 5, but as this always generates a lot of output, try a lower level at first). Not all messages shown at higher debug levels neccessarily indicate a problem, but chance are, your problem shows up somewhere between the messages.

If you still can't find out what's wrong, don't despair. We know this is complicated stuff, and - after all - possibly you've also come across a bug in &kapp;, and &kapp; needs to be fixed. Just write to the development mailing list, and tell us about the problem. We'll be happy to help you.

Finally, even if you found out how to do it on your own, but found the documentation to be not-so-helpful or even wrong in some respects, please tell us on the mailing list as well, so we can fix/improve the documentation.

&documentation.index;