<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Desktop &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/category/desktop/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 05 Dec 2018 17:00:48 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>
	<item>
		<title>Matlab toolstrip – part 2 (ToolGroup App)</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-2-toolgroup-app</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 05 Dec 2018 17:00:48 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[schema.prop]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8059</guid>

					<description><![CDATA[<p>Matlab users can create custom Apps with toolstrips and docked figures. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app">Matlab toolstrip – part 2 (ToolGroup App)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1" rel="bookmark" title="Matlab toolstrip &#8211; part 1">Matlab toolstrip &#8211; part 1 </a> <small>Matlab contains extensive toolstrip (ribbon) functionality that can be integrated in user programs (GUI). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A while ago I posted the first of my planned miniseries on the <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1" target="_blank">Matlab toolstrip (ribbon)</a>. Today I will expand that post by discussing how toolstrips can be added to Matlab GUIs. This post will remain at a high-level as the previous post, with followup posts drilling into the technical details of the toolstrip components (inner packages and classes).<br />
We can add a Matlab toolstrip to 3 types of Matlab GUI windows:</p>
<ol>
<li>To a Java-based Matlab figure (so-called &#8220;legacy&#8221; figures, created using GUIDE or the <i><b>figure</b></i> function)</li>
<li>To a container window of docked Java-based figures, typically called an &#8220;App&#8221; (marketing name) or &#8220;Tool Group&#8221; (internal technical name)</li>
<li>To a JavaScript/HTML-based Matlab figure (so called &#8220;web&#8221; figures, created using App Designer or the <i><b>uifigure</b></i> function)</li>
</ol>
<p>Today I will show how to add a basic dynamic toolstrip to a ToolGroup (App, window type #2):<br />
<center><figure style="width: 450px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_2c_animated.gif" alt="ToolGroup with clients and dynamic toolstrip" title="ToolGroup with clients and dynamic toolstrip" width="450" height="314" /><figcaption class="wp-caption-text">ToolGroup with clients and dynamic toolstrip</figcaption></figure></center><br />
<span id="more-8059"></span></p>
<h3 id="ToolGroup">Figure containers (&#8220;Tool Groups&#8221;)</h3>
<p>Most Matlab users are familiar with window types #1 and #3 (legacy and web-based figures), but type #2 may seem strange. In fact, it shouldn&#8217;t be: All the Matlab &#8220;Apps&#8221; and Desktop components use such a container of docked clients. For example, both the Matlab Editor and Desktop are containers of individual client windows (individual files in the Editor; Command Window, Workspace etc. in the desktop).<br />
Similarly, when we dock figures, they dock as client windows into a container called &#8220;Figures&#8221; (this can be controlled programmatically: see my <a href="https://www.mathworks.com/matlabcentral/fileexchange/16650-setfigdockgroup" rel="nofollow" target="_blank"><i><b>setFigDockGroup</b></i> utility</a> on the File Exchange). This is the basis for all Matlab &#8220;Apps&#8221;, as far as I am aware (some Apps may possibly use a different GUI container, after all there are ~100 Matlab Apps and I&#8217;m not familiar with all of them). Such Apps are basically stand-alone Tool Groups (client container windows) that contain one or more docked figures, a toolstrip, and a side-panel with controls (so-called &#8220;Data Browser&#8221;).<br />
Note: MathWorks uses confusing terminology here, using the same term &#8220;App&#8221; for both MathWorks-created GUIs containers (that have toolstrips, Data Browser and docked figures) and also user-created utilities on the File Exchange (that do not have these). Unfortunately, MathWorks has chosen not [yet] to release to the general public its set of tools that enable creating true &#8220;Apps&#8221;, i.e. those that have a toolstrip, Data Browser and docked figures.<br />
Today&#8217;s post will attempt to fill this gap, by showing how we can create user Apps that have a toolstrip and docked figures. I will ignore the Data Browser today, and will describe it in a future post. Since docking figures into a standalone user-created container is a solved problem (using my <a href="https://www.mathworks.com/matlabcentral/fileexchange/16650-setfigdockgroup" rel="nofollow" target="_blank"><i><b>setFigDockGroup</b></i> utility</a>), this post will focus on adding a toolstrip to such a container.<br />
A ToolGroup object (<code>matlab.ui.internal.desktop.ToolGroup</code>) is created either implicitly (by docking a figure into a group that has a new name), or explicitly (by invoking its constructor):</p>
<pre lang="matlab">
% Create a new non-visible empty App (Tool Group)
hToolGroup = matlab.ui.internal.desktop.ToolGroup('Toolstrip example on UndocumentedMatlab.com');
</pre>
<p>Some things only work properly after the app is displayed, so let&#8217;s display the ToolGroup (however, note that for improved performance it is better to do whatever customizations and GUI updates that you can before the app is made visible):</p>
<pre lang="matlab">
% Display the ToolGroup window
hToolGroup.open();
</pre>
<p><center><figure style="width: 435px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_2b.png" alt="Basic empty ToolGroup (without toolstrip or clients)" title="Basic empty ToolGroup (without toolstrip or clients)" width="435" height="347" /><figcaption class="wp-caption-text">Basic empty ToolGroup (without toolstrip or clients)</figcaption></figure></center><br />
An annoying quirk with ToolGroups is that they automatically close when their reference handle is deleted from Matlab memory. The specific behavior changes depending on the contents of the container and the Matlab release, but in general it&#8217;s safest to preserve the <code>hToolGroup</code> variable, to prevent the window from closing, when this variable goes out of scope, when the function (in which we create the ToolGroup) returns. There are many ways to persist this variable. Here&#8217;s one alternative, in which we persist it in itself (or rather, attached to its internal Java peer control):</p>
<pre lang="matlab">
% Store toolgroup reference handle so that app will stay in memory
jToolGroup = hToolGroup.Peer;
internal.setJavaCustomData(jToolGroup, hToolGroup);
</pre>
<p><b><i>internal.setJavaCustomData</i></b> is an undocumented Matlab function that adds a new custom property to a Java reference handle. In our case, it adds a <b>CustomData</b> property to the <code>jToolGroup</code> handle and sets its value to the Matlab <code>hToolGroup</code> handle. The source code for <b><i>internal.setJavaCustomData</i></b> is available in <i>%matlabroot%/toolbox/shared/controllib/general/+internal/setJavaCustomData.m</i> and is very simple: it essentially uses the old <code>schema</code>-based <a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" target="_blank"><i><b>schema.prop</b></i></a> method for adding new properties to handles. <code>Schema</code> is an old deprecated mechanism that is mostly replaced by the newer MCOS (Matlab Class Object System), but for some specific cases such as this it&#8217;s still very useful (the standard <a href="https://undocumentedmatlab.com/articles/adding-custom-properties-to-gui-objects" target="_blank"><i><b>addprop</b></i> function</a> can add new properties to Matlab GUI handles, but not to Java reference handles).<br />
Finally, let&#8217;s discard the Data Browser side panel (I&#8217;ll discuss it in a separate future post):</p>
<pre lang="matlab">
% Discard the Data-browser left panel
hToolGroup.disableDataBrowser();
</pre>
<h3 id="toolstrip">Adding a toolstrip to the ToolGroup</h3>
<p>Now that we have the basic container ready, let&#8217;s add a toolstrip. To simplify matters in this introductory post (after all, I have still not described the internal packages and classes that make up a toolstrip), we&#8217;ll use some of the tabs used in the <code>showcaseToolGroup</code> example that I discussed in <a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1" target="_blank">my previous post</a>. You can see the relevant source code in <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/*.m</i>, in case you want to jump ahead and customize your own toolstrip tabs, groups and buttons. In the code snippet below, we first create an empty <code>TabGroup</code>, then add toolstrip tabs into it, and finally add this <code>TabGroup</code> into our ToolGroup using its <i>addTabGroup(hTabGroup)</i> method:</p>
<pre lang="matlab">
% Create a new tab group
%hTabGroup = matlab.ui.internal.desktop.showcaseBuildTabGroup('swing');
hTabGroup = matlab.ui.internal.toolstrip.TabGroup();
hTab1 = matlab.ui.internal.desktop.showcaseBuildTab_Buttons('swing');
hTabGroup.add(hTab1);
%hTabGroup.add(matlab.ui.internal.desktop.showcaseBuildTab_Gallery());
hTabGroup.add(matlab.ui.internal.desktop.showcaseBuildTab_Layout('swing'));
% Select tab #1 (common)
hTabGroup.SelectedTab = hTab1;
% Add the tab group to the built-in toolstrip
hToolGroup.addTabGroup(hTabGroup);
</pre>
<p>We now have an &#8220;App&#8221; that has a toolstrip, but no clients (yet), and a hidden Data Browser side-panel:<br />
<center><img decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_2a.png" alt='ToolGroup "App" with a simple toolstrip (no clients yet)' title='ToolGroup "App" with a simple toolstrip (no clients yet)' width="80%" style="max-width:673px;" /></center><br />
Now let&#8217;s add some clients (docked figures):</p>
<h3 id="clients">Adding clients (docked figures) to the ToolGroup</h3>
<p>There are two easy variants for adding docked figures in a ToolGroup: The easiest is to use the ToolGroup&#8217;s <i>addFigure(hFigure)</i> method:</p>
<pre lang="matlab">
% Create a figure and dock it into the tool-group
hFig1 = figure('Name','3D');
surf(peaks);
hToolGroup.addFigure(hFig1);
</pre>
<p>The second variant enables to dock a figure that has a specific set of toolstrip tabs attached to it. These tabs will only display in the toolstrip when that particular figure has focus. We do this by creating a new TabGroup (just as we have done above), and then add the figure and TabGroup to the container using the ToolGroup&#8217;s <i>addClientTabGroup(hFigure,hTabGroup)</i> method:</p>
<pre lang="matlab">
% Create the 2nd figure
hFig2 = figure('Name','2D');
plot(rand(5)); drawnow
% Add a few tabs that are only relevant to this specific figure
hTabGroup2 = matlab.ui.internal.toolstrip.TabGroup();
hTab2 = matlab.ui.internal.desktop.showcaseBuildTab_Selections();
hTabGroup2.add(hTab2);
hTabGroup2.add(matlab.ui.internal.desktop.showcaseBuildTab_EditValue());
% Add the figure and tabs to the ToolGroup
hToolGroup.addClientTabGroup(hFig2, hTabGroup2);
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/Toolstrip_2c_animated.gif" alt="ToolGroup with clients and dynamic toolstrip" title="ToolGroup with clients and dynamic toolstrip" width="450" height="314" /><figcaption class="wp-caption-text">ToolGroup with clients and dynamic toolstrip</figcaption></figure></center><br />
In this example, the &#8220;Selection&#8221; and &#8220;Values&#8221; toolstrip tabs only appear when the 2nd figure (&#8220;2D&#8221;) has focus. A similar behavior exists in the Matlab Desktop and Editor, where some tabs are only shown when certain clients have focus.</p>
<h3 id="View">Removing the View tab</h3>
<p>Note that the &#8220;View&#8221; toolstrip tab (which enables setting the appearance of the docked figures: layout, tab positions (top/bottom/left/right), ordering etc.) is automatically added to the toolstrip and always appears last. We can remove this View tab using the ToolGroup&#8217;s <i>hideViewTab()</i> method. The tab will not immediately be removed, only when the toolstrip is repainted, for example, when we switch focus between the docked figures:</p>
<pre lang="matlab">
hToolGroup.hideViewTab;  % toolstrip View tab is still visible at this point
figure(hFig1);  % change focus to hFig1 - toolstrip is repainted without View tab
</pre>
<h3 id="conclusion">Conclusion</h3>
<p>It&#8217;s relatively easy to dock figures into a standalone &#8220;App&#8221; window that has a custom toolstrip, which can even be dynamically modified based on the figure which is currently in focus. Naturally, this has little benefit if we cannot customize the toolstrip components: labels, icons, control type, grouping and most importantly &#8211; callbacks. This topic deserves a dedicated post, which I plan to be the next in this miniseries. Stay tuned &#8211; hopefully the next post will not take me as long to publish as this post (I was quite busy recently)&#8230;</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app">Matlab toolstrip – part 2 (ToolGroup App)</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1" rel="bookmark" title="Matlab toolstrip &#8211; part 1">Matlab toolstrip &#8211; part 1 </a> <small>Matlab contains extensive toolstrip (ribbon) functionality that can be integrated in user programs (GUI). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-9-popup-figures" rel="bookmark" title="Matlab toolstrip – part 9 (popup figures)">Matlab toolstrip – part 9 (popup figures) </a> <small>Custom popup figures can be attached to Matlab GUI toolstrip controls. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app/feed</wfw:commentRss>
			<slash:comments>17</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab toolstrip &#8211; part 1</title>
		<link>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-toolstrip-part-1</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Mon, 03 Sep 2018 15:00:22 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented feature]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7952</guid>

					<description><![CDATA[<p>Matlab contains extensive toolstrip (ribbon) functionality that can be integrated in user programs (GUI). </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1">Matlab toolstrip &#8211; part 1</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app" rel="bookmark" title="Matlab toolstrip – part 2 (ToolGroup App)">Matlab toolstrip – part 2 (ToolGroup App) </a> <small>Matlab users can create custom Apps with toolstrips and docked figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>The Matlab toolstrip (ribbon) has been around officially <a href="https://blogs.mathworks.com/loren/2012/09/12/the-matlab-r2012b-desktop-part-1-introduction-to-the-toolstrip" rel="nofollow" target="_blank">since R2012a</a>, and unofficially for <a href="https://undocumentedmatlab.com/articles/matlab-installation-woes#Java" target="_blank">a couple of years earlier</a>. Since then, I blogged about the toolstrip only rarely (<a href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2" target="_blank">example</a>). I believe the time has come to start a short mini-series about this functionality, eventually showing how users can use toolstrips in their own custom applications.<br />
My plan is to start the miniseries with a discussion of the built-in showcase examples, followed by a post on the built-in classes that make up the toolstrip building-blocks. Finally, I&#8217;ll describe how toolstrips can be added to figures, not just in client/tool groups.</p>
<h3 id="showcase">Matlab&#8217;s internal showcase examples</h3>
<p>I start the discussion with a description of built-in examples for the toolstrip functionality, located in <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/</i>. The most important of these are <i>showcaseToolGroup.m</i> and <i>showcaseMPCDesigner.m</i>, both of which use Java-based (Swing) containers and controls. Readers who wish to integrate toolstrips into their app immediately, without waiting for my followup posts in this series, are welcome to dig into the examples&#8217; source-code and replicate it in their programs:</p>
<h5 id="showcaseToolGroup">1. <code>showcaseToolGroup</code></h5>
<pre lang="matlab">h = matlab.ui.internal.desktop.showcaseToolGroup</pre>
<p><center><img decoding="async" src="https://undocumentedmatlab.com/images/showcaseToolGroup.png" alt="showcaseToolGroup built-in example" title="showcaseToolGroup built-in example" width="80%" style="max-width:1028px; max-height:455px;" /></center><br />
<span id="more-7952"></span></p>
<h5 id="showcaseMPCDesigner">2. <code>showcaseMPCDesigner</code></h5>
<pre lang="matlab">
>> h = matlab.ui.internal.desktop.showcaseMPCDesigner
h =
  showcaseMPCDesigner with properties:
    ToolGroup: [1×1 matlab.ui.internal.desktop.ToolGroup]
       Dialog: [1×1 toolpack.component.TSTearOffPopup]
      Figure1: [1×1 Figure]
      Figure2: [1×1 Figure]
</pre>
<p><center><img decoding="async" src="https://undocumentedmatlab.com/images/showcaseMPCDesigner.png" alt="showcaseMPCDesigner built-in example" title="showcaseMPCDesigner built-in example" width="80%" style="max-width:994px; max-height:552px;" /></center></p>
<h5 id="showcaseHTML">3. <code>showcaseHTML</code> and <code>showcaseCEF</code></h5>
<p>In addition to these showcase examples, the folder also contains a <i>showcaseHTML.m</i> and <i>showcaseCEF.m</i> files, that are supposed to showcase the toolstrip functionality in JavaScript-based containers (browser webpage and uifigure apps, respectively). Unfortunately, on my system running these classes displays blank, although the toolstrip is indeed created, as seen below (if you find out how to make these classes work, please let me know):</p>
<pre lang="matlab">
>> h = matlab.ui.internal.desktop.showcaseHTML
building toolstrip hierarchy...
rendering toolstrip...
h =
  Toolstrip with properties:
               SelectedTab: [1×1 matlab.ui.internal.toolstrip.Tab]
              DisplayState: 'expanded'
    DisplayStateChangedFcn: @PropertyChangedCallback
                       Tag: 'toolstrip'
>> hs = struct(h)
Warning: Calling STRUCT on an object prevents the object from hiding its implementation details and should thus be avoided.
Use DISP or DISPLAY to see the visible public details of an object. See 'help struct' for more information.
(Type "warning off MATLAB:structOnObject" to suppress this warning.)
hs =
  struct with fields:
                         SelectedTab: [1×1 matlab.ui.internal.toolstrip.Tab]
                        DisplayState: 'expanded'
              DisplayStateChangedFcn: @PropertyChangedCallback
                 DisplayStatePrivate: 'expanded'
                        QABIdPrivate: '2741bf89'
               QuickAccessBarPrivate: [1×1 matlab.ui.internal.toolstrip.impl.QuickAccessBar]
       DisplayStateChangedFcnPrivate: @PropertyChangedCallback
         SelectedTabChangedListeners: [1×1 event.listener]
                                 Tag: 'toolstrip'
                                Type: 'Toolstrip'
                          TagPrivate: 'toolstrip'
    WidgetPropertyMap_FromMCOSToPeer: [3×1 containers.Map]
    WidgetPropertyMap_FromPeerToMCOS: [3×1 containers.Map]
                              Parent: [0×0 matlab.ui.internal.toolstrip.base.Node]
                            Children: [1×1 matlab.ui.internal.toolstrip.TabGroup]
                             Parent_: []
                           Children_: [1×1 matlab.ui.internal.toolstrip.TabGroup]
                                Peer: [1×1 com.mathworks.peermodel.impl.PeerNodeImpl]
                   PropertySetSource: [1 java.util.HashMap]
                    PeerModelChannel: '/ToolstripShowcaseChannel'
                   PeerEventListener: [1×1 handle.listener]
                 PropertySetListener: [1×1 handle.listener]
>> hs.Peer
ans =
PeerNodeImpl{id='4a1e4b08', type='Toolstrip', properties={displayState=expanded, hostId=ToolStripShowcaseDIV, tag=toolstrip, QABId=2741bf89}, parent=878b0e2b, children=[
    PeerNodeImpl{id='5bb9632c', type='TabGroup', properties={QAGroupId=ea9b628c, tag=, selectedTab=f90db10c}, parent=4a1e4b08, children=[
        PeerNodeImpl{id='f90db10c', type='Tab', properties={mnemonic=, tag=tab_buttons, title=BUTTONS}, parent=5bb9632c, children=[
            PeerNodeImpl{id='1ccc9246', type='Section', properties={collapsePriority=0.0, mnemonic=, tag=sec_push, title=PUSH BUTTON}, parent=f90db10c, children=[
                PeerNodeImpl{id='8323f06e', type='Column', properties={horizontalAlignment=left, width=0.0, tag=}, parent=1ccc9246, children=[
                    PeerNodeImpl{id='af368d7b', type='PushButton', properties={textOverride=, descriptionOverride=, mnemonic=, actionId=230d471b, iconOverride=, tag=pushV, iconPathOverride=}, parent=8323f06e, children=[]}]}
                PeerNodeImpl{id='a557a712', type='Column', properties={horizontalAlignment=left, width=0.0, tag=}, parent=1ccc9246, children=[
                    PeerNodeImpl{id='f0d6a9fc', type='EmptyControl', properties={tag=}, parent=a557a712, children=[]}
                    PeerNodeImpl{id='74bc4cd2', type='PushButton', properties={textOverride=, descriptionOverride=, mnemonic=, actionId=12d6a26a, iconOverride=, tag=pushH, iconPathOverride=}, parent=a557a712, children=[]}
                    PeerNodeImpl{id='bcb5a9d0', type='EmptyControl', properties={tag=}, parent=a557a712, children=[]}]}]}
            PeerNodeImpl{id='0e515319', type='Section', properties={collapsePriority=0.0, mnemonic=, tag=sec_dropdown, title=DROP DOWN BUTTON}, parent=f90db10c, children=[
                PeerNodeImpl{id='80482225', type='Column', properties={horizontalAlignment=left, width=0.0, tag=}, parent=0e515319, children=[
                    PeerNodeImpl{id='469f469a', type='DropDownButton', properties={textOverride=, descriptionOverride=, mnemonic=, actionId=c6ca7335, iconOverride=, tag=dropdownV, iconPathOverride=}, parent=80482225, children=[]}]}
                ...
</pre>
<p>Note: <code>showcaseCEF</code> has been removed in 2018, but is available in older Matlab releases.</p>
<h3 id="levels">Levels of toolstrip encapsulation</h3>
<p>Matlab currently has several levels of encapsulation for toolstrip components:</p>
<ul>
<li>Top-level m-file classes for showcasing the toolstrip functionality and creating toolstrips in Java-based containers and web-based apps &#8211; these are located in <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+desktop/</i></li>
<li>Mid-level m-file classes that contain the toolstrip building blocks (tabs, sections, controls) &#8211; these are located in <i>%matlabroot%/toolbox/matlab/toolstrip/+matlab/+ui/+internal/+toolstrip/</i></li>
<li>Low-level Java classes that implement the underlying user-interface for Java-based UI &#8211; these are located in <i>%matlabroot%/java/jar/toolstrip.jar</i>. I <a href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2#custom" target="_blank">discussed this briefly</a> in a post few years ago.</li>
</ul>
<p>The top- and mid-level m-file classes are provided with full source code that is quite well-documented internally (as m-file source-code comments). However, note that it is not officially documented or supported (i.e., <a href="https://undocumentedmatlab.com/articles/tag/semi-documented-feature" target="_blank">semi-documented</a> in this blog&#8217;s parlance).<br />
The low-level Java classes on the other hand are compiled without available source code &#8211; we can inspect these classes (e.g., using <a href="https://undocumentedmatlab.com/articles/uiinspect" target="_blank">uiinspect</a> or <a href="https://undocumentedmatlab.com/articles/checkclass" target="_blank">checkClass</a>), but we cannot see their original source-code. Luckily, the higher-level m-file classes provide us with plenty of hints and usage examples that we could use to tailor the appearance, functionality and integration of toolstrip components into our app.</p>
<h3 id="Widgets_toolbox">Robyn Jackey&#8217;s Widgets Toolbox</h3>
<p>Users who hesitate to mess around with the built-in toolstrip functionality may find interest in MathWorker Robyn Jackey&#8217;s <a href="https://www.mathworks.com/matlabcentral/fileexchange/66235-widgets-toolbox?focused=a9526a57-50fa-052b-7343-3cbce74b2095&#038;tab=example" rel="nofollow" target="_blank">Toolstrip look-alike</a>, which is part of his open-source <a href="https://www.mathworks.com/matlabcentral/fileexchange/66235-widgets-toolbox" rel="nofollow" target="_blank">Widgets Toolbox</a> on the Matlab File Exchange. Unlike other parts of Robyn&#8217;s toolbox, which use undocumented functionality, his Toolstrip class seems to use documented components (panels, uicontrols etc.), with just a small reliance on undocumented functionality (<code>matlab.ui.*</code> for example). This has a fair chance to continue working well into future releases, even if Matlab&#8217;s built-in toolstrip functionality changes:<br />
<center><img decoding="async" src="https://undocumentedmatlab.com/images/demoToolstrip_05.png" alt="Robyn Jackey's Toolstrip look-alike" title="Robyn Jackey's Toolstrip look-alike" width="80%" style="max-width:835px; max-height:83px;" /></center></p>
<h3 id="caution">Strong caution</h3>
<p>Over the years, Matlab&#8217;s internal toolstrip interface has changed somewhat, but not dramatically. This could change at any time, since the toolstrip uses deeply undocumented functionality. What I will demonstrate over the next few posts might stop working in R2019a, or in R2025b &#8211; nobody really knows, perhaps not even MathWorks at this stage. Something that we do know for a fact is that Matlab is slowly transitioning away from Java-based user interfaces to web-based (HTML/JavaScript/CSS) interfaces, and this could have a drastic effect on the toolstrip functionality/API. It seems reasonable to assume that even if MathWorks would one day open up the toolstrip functionality, this would only be for the new web-based uifigure apps (not legacy Java-based figures), and might well have a different API than the one that I&#8217;ll discuss in this miniseries. Still, users could use the unofficial/undocumented information that I present here in their own Java figures today and quite possibly also in near-term upcoming releases.<br />
Despite the many unknowns regarding future supportability/roadmap of the built-in toolstrip API, I believe that my readers are smart enough to decide for themselves whether they want to take the associated risks to improve their Matlab programs today, or wait until a documented API will possibly be provided sometime in the future. The choice is yours, as it always is when using undocumented tips from my blog.<br />
With this warning stated, let&#8217;s start having fun with Matlab&#8217;s built-in toolstrip!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1">Matlab toolstrip &#8211; part 1</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-3-basic-customization" rel="bookmark" title="Matlab toolstrip – part 3 (basic customization)">Matlab toolstrip – part 3 (basic customization) </a> <small>Matlab toolstrips can be created and customized in a variety of ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-2-toolgroup-app" rel="bookmark" title="Matlab toolstrip – part 2 (ToolGroup App)">Matlab toolstrip – part 2 (ToolGroup App) </a> <small>Matlab users can create custom Apps with toolstrips and docked figures. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-8-galleries" rel="bookmark" title="Matlab toolstrip – part 8 (galleries)">Matlab toolstrip – part 8 (galleries) </a> <small>Matlab toolstrips can contain customizable gallery panels of items. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-toolstrip-part-1/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Spicing up the Matlab Editor</title>
		<link>https://undocumentedmatlab.com/articles/spicing-up-the-matlab-editor?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=spicing-up-the-matlab-editor</link>
					<comments>https://undocumentedmatlab.com/articles/spicing-up-the-matlab-editor#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 29 Mar 2018 21:34:20 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Andreas Justin]]></category>
		<category><![CDATA[Editor]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7472</guid>

					<description><![CDATA[<p>Matlab's Editor and Workspace can be enhanced quite significantly using an open-source utility. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/spicing-up-the-matlab-editor">Spicing up the Matlab Editor</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/editormacro-assign-a-keyboard-macro-in-the-matlab-editor" rel="bookmark" title="EditorMacro &#8211; assign a keyboard macro in the Matlab editor">EditorMacro &#8211; assign a keyboard macro in the Matlab editor </a> <small>EditorMacro is a new utility that enables setting keyboard macros in the Matlab editor. this post details its inner workings....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-the-matlab-editor" rel="bookmark" title="Accessing the Matlab Editor">Accessing the Matlab Editor </a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/non-textual-editor-actions" rel="bookmark" title="Non-textual editor actions">Non-textual editor actions </a> <small>The UIINSPECT utility can be used to expand EditorMacro capabilities to non-text-insertion actions. This is how:...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/recovering-previous-editor-state" rel="bookmark" title="Recovering previous editor state">Recovering previous editor state </a> <small>Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I&#8217;d like to introduce guest blogger <a href="https://github.com/GavriYashar" rel="nofollow" target="_blank">Andreas Justin</a>, who will discuss some way-cool features in his Editor Plugin utility. Many of his feature implementations are not Editor-specific and can be reused in other Matlab-Desktop applications, for example dockable panels, and integration with Matlab&#8217;s main Preferences window.</i><br />
<i><b><u>Note</u>: I will be traveling to the USA in June, and to Spain in August. If you would like me to visit your location for onsite consulting or training, then please let me know.</b></i><br />
<i>Happy Easter/Passover!</i></p>
<h3 id="overview">Overview</h3>
<p><figure style="width: 128px" class="wp-caption alignright"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin3.gif" alt="Editor-plugin's cool logo" title="Editor-plugin's cool logo" width="128" height="128" /><figcaption class="wp-caption-text">Editor-plugin's cool logo</figcaption></figure>Compared to other IDE like IntellIJ, Eclipse and many more, Matlab&#8217;s editor seems somewhat outdated. Especially writing Object-Oriented code in Matlab is kind of a hassle. To make Matlab more user friendly, I&#8217;ve written a Java app that adds important features to the editor &#8211; Features such as navigating inside Class-code and in Inherited members; Searching through methods and instantly jumping to desired location; Reopening an editor that was closed by accident; Storing bookmarks between Matlab sessions; and Live Templates using commands directly written in the editor, replaced by pre-defined text.</p>
<p>The default Keyboard shortcuts listed below for the features can be customized. Most variables can be customized as well (I will point out which variables are not [yet] customizable).<br />
Most GUIs have a search field. Within this search field you can move the list or the tree up and down using arrow keys, or hit &lt;escape&gt; to return to editor. These search fields allow you to enter regular expressions to limit results shown in list or tree. Also, most GUIs are dockable.<br />
The Editor-Plugin utility is open-source. It is available <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin" rel="nofollow" target="_blank">on GitHub</a> and also mirrored <a href="https://www.mathworks.com/matlabcentral/fileexchange/58497-gavriyashar-matlab-editor-plugin" rel="nofollow" target="_blank">on the Matlab File Exchange</a>. A <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin/wiki/Setup" rel="nofollow" target="_blank">detailed setup guide</a> is provided on the utility&#8217;s <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin/wiki" rel="nofollow" target="_blank">wiki section in GitHub</a>.<br />
If you discover any problem or have any suggestion for improvement, please visit the utility&#8217;s <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin/issues" rel="nofollow" target="_blank">Issues section on GitHub</a>, where all open/closed issues can be tracked and discussed.<br />
A brief overview of some of the features is presented below. For a detailed explanation of these and other features (which are not listed below), please review the <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin/wiki/Features" rel="nofollow" target="_blank">Features section</a> of the utility&#8217;s wiki (you guessed it: on GitHub&#8230;).</p>
<style type="text/css" media="screen">
kbd {
    display: inline-block;
    padding: 3px 5px;
    font-size: 11px;
    line-height: 10px;
    color: #444d56;
    vertical-align: middle;
    background-color: #fafbfc;
    border: solid 1px #c6cbd1;
    border-bottom-color: #959da5;
    border-radius: 3px;
    box-shadow: inset 0 -1px 0 #959da5;
}
</style>
<h3 id="editing">Editing</h3>
<ul>
<li><b>Delete / duplicate lines</b> &#8211; <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>Y</kbd> or <kbd>D</kbd> allows you to delete or duplicate current line.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin1.gif" alt="Deleting/duplicating complete lines" title="Deleting/duplicating complete lines" width="90%" style="max-width:778px;"/></center></li>
<li><b>Move lines up or down</b> &#8211; <kbd>CTRL</kbd> + <kbd>ALT</kbd> + <kbd>UP</kbd> or <kbd>DOWN</kbd> allows you to move selected lines up or down.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin10.gif" alt="Moving complete lines" title="Moving complete lines" width="90%" style="max-width:750px;"/></center></li>
<li><b>Live (auto-replace) templates</b> &#8211; Live Templates are editor commands you can design to insert predefined code. Here&#8217;s an example for the command <code>%this%</code> (delivered within the package). When you type a command into the editor the string will get replaced by the predefined text. This predefined text may include variables depending on what you want to achieve. <code>%this%</code> was designed to insert the fully qualified name of the current class you&#8217;re in (or function, or script).<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin9.gif" alt="Auto-replace template" title="Auto-replace templates" width="90%" style="max-width:647px;"/></center></li>
<li><b>Clipboard Stack</b> &#8211; <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>V</kbd> opens the Clipboard Stack, where the last 10 copied/cut text are stored and can be directly inserted into the current editor position. The Clipboard Stack only stores text copied from editor.</li>
</ul>
<p><span id="more-7472"></span></p>
<h3 id="navigation">Navigation</h3>
<ul>
<li><b>Auto switch current folder and detail viewer</b> &#8211; Switching editor tabs will update the Desktop&#8217;s current folder and detail viewer. This behavior can be directly changed in the detail viewer bar.<br />
Use the new icons in the Desktop&#8217;s Current Folder panel: <img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin8.png" alt="Toggle detail viewer" title="Toggle detail viewer" width="16" height="16"/> to toggle detail viewer and <img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin2.png" alt="Toggle following the current editor file" title="Toggle following the current editor file" width="16" height="16"/> to toggle following the current editor file.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin6.gif" alt="Follow current editor file" title="Follow current editor file" width="90%" style="max-width:574px;"/></center></li>
<li><b>File Structure</b> &#8211; I personally use this one the most: <kbd>CTRL</kbd> + <kbd>F12</kbd> will show a GUI that let you search methods and properties including inherited ones.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin7.gif" alt="File structure analysis" title="File structure analysis" width="90%" style="max-width:803px;"/></center></li>
<li><b>Navigation History</b> &#8211; Every editor file that is opened is stored in the navigation history. Up to 50 editor file paths are stored. If you have a 5-Button Mouse, you can navigate through previous location (backward and forward).</li>
<li><b>Recently Closed</b> &#8211; <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>T</kbd> will show a GUI that allows you to reopen closed editors this or last session.</li>
<li><b>Bookmarks</b> &#8211; <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>F2</kbd> will show a GUI that allows you to name, search and delete bookmarks. Matlab has this nice feature to delete bookmarks after closing the editor. This feature will store all bookmarks. If an editor or Matlab is closed and opened later. All Bookmarks will be restored.<br />
This feature has some issues though. The most obvious first: if the source file has been changed outside of Matlab, the bookmark does not get updated, and may point to the wrong line, or gets deleted. Also on some Systems the default shortcut does not work. But there are workarounds.</li>
</ul>
<h3 id="others">Other useful features</h3>
<ul>
<li><b>Dockable Windows</b> &#8211; As mentioned before, most GUIs are dockable.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin5.gif" alt="Dockable Windows" title="Dockable Windows" width="90%" style="max-width:820px;"/></center></li>
<li><b>Preferences</b> &#8211; Preferences panel integrated in Matlab&#8217;s main Preferences window.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin-preferences.png" alt="Preferences panel integrated in Matlab's main Preferences window" title="Preferences panel integrated in Matlab's main Preferences window" width="90%" style="max-width:912px;"/></center></li>
<li><b>Execute current line</b> &#8211; <kbd>SHIFT</kbd> + <kbd>F9</kbd> allows you to execute the current line. This is equivalent to selecting the entire line, then clicking <kbd>F9</kbd>, and is similar in concept to the editor&#8217;s built-in ability to execute the current cell-block.<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin4.gif" alt="Execute current line" title="Execute current line" width="90%" style="max-width:795px;"/></center></li>
<li><b>VarDiff</b> &#8211; Select two variables in the workspace and compare them using Matlab&#8217;s internal comparison feature (adding a custom hook to the Workspace context-menu was <a href="/articles/customizing-workspace-context-menu" target="_blank">discussed by Yair</a> back in 2010).<br />
<center style="margin:7px;"><img decoding="async" src="https://undocumentedmatlab.com/images/Editor-plugin-Vardiff_context.png" alt="Variables comparison integrated in the Workspace browser" title="Variables comparison integrated in the Workspace browser" width="90%" style="max-width:392px;"/></center></li>
<li><b>KeyPressListener</b> &#8211; Allows you to create custom keyboard shortcuts for your own functions. A similar functionality was <a href="/articles/editormacro-assign-a-keyboard-macro-in-the-matlab-editor" target="_blank">discussed by Yair</a> back in 2009.</li>
</ul>
<p>As noted above, a detailed explanation of these and other features is provided in the <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin/wiki/Features" rel="nofollow" target="_blank">Features section</a> of the utility&#8217;s wiki. If you discover any problem or have any suggestion for improvement, please visit the utility&#8217;s <a href="https://github.com/GavriYashar/Matlab-Editor-Plugin/issues" rel="nofollow" target="_blank">Issues section on GitHub</a>, where issues can be tracked and discussed.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/spicing-up-the-matlab-editor">Spicing up the Matlab Editor</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/editormacro-assign-a-keyboard-macro-in-the-matlab-editor" rel="bookmark" title="EditorMacro &#8211; assign a keyboard macro in the Matlab editor">EditorMacro &#8211; assign a keyboard macro in the Matlab editor </a> <small>EditorMacro is a new utility that enables setting keyboard macros in the Matlab editor. this post details its inner workings....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/accessing-the-matlab-editor" rel="bookmark" title="Accessing the Matlab Editor">Accessing the Matlab Editor </a> <small>The Matlab Editor can be accessed programmatically, for a wide variety of possible uses - this article shows how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/non-textual-editor-actions" rel="bookmark" title="Non-textual editor actions">Non-textual editor actions </a> <small>The UIINSPECT utility can be used to expand EditorMacro capabilities to non-text-insertion actions. This is how:...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/recovering-previous-editor-state" rel="bookmark" title="Recovering previous editor state">Recovering previous editor state </a> <small>Recovering the previous state of the Matlab editor and its loaded documents is possible using a built-in backup config file. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/spicing-up-the-matlab-editor/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>The HotLinks feature</title>
		<link>https://undocumentedmatlab.com/articles/the-hotlinks-feature?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=the-hotlinks-feature</link>
					<comments>https://undocumentedmatlab.com/articles/the-hotlinks-feature#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Tue, 24 Oct 2017 12:43:13 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7128</guid>

					<description><![CDATA[<p>feature('HotLinks') can be used to temporarily disable hyperlinks and other markups in the Matlab console. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/the-hotlinks-feature">The HotLinks feature</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-function" rel="bookmark" title="Undocumented feature() function">Undocumented feature() function </a> <small>Matlab's undocumented feature function enables access to some internal experimental features...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-list" rel="bookmark" title="Undocumented feature list">Undocumented feature list </a> <small>A list of undocumented MATLAB features can be retrieved. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/legend-semi-documented-feature" rel="bookmark" title="Legend &#039;-DynamicLegend&#039; semi-documented feature">Legend &#039;-DynamicLegend&#039; semi-documented feature </a> <small>The built-in Matlab legend function has a very useful semi-documented feature for automatic dynamic update, which is explained here....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Back in 2010, I posted about <a href="/articles/undocumented-feature-function" target="_blank">Matlab&#8217;s undocumented <i><b>feature</b></i> function</a>. One of the features that I mentioned was <code>'HotLinks'</code>. A few days ago I had an occasion to remember this feature when a <a href="https://stackoverflow.com/questions/46676035/how-do-i-change-the-fontweight-of-table-titles-in-matlab" rel="nofollow" target="_blank">StackOverflow user complained</a> that the headers of <i><b>table</b></i> outputs in the Matlab console appear with HTML tags (&lt;strong&gt;) in his <i><b>diary</b></i> output. He asked whether it was possible to turn off this automated headers markup.<br />
There are several ways this problem can be solved, ranging from creating a custom table display function, to modifying the table&#8217;s internal <i>disp</i> method (<i>%matlabroot%/toolbox/matlab/datatypes/@tabular/disp.m</i>), to using this method&#8217;s second optional argument (<code>disp(myTable,false)</code>). Note that simply subclassing the <code>table</code> class to overload <i>disp()</i> will not work because the <code>table</code> class is Sealed, but we could instead subclass <code>table</code>&#8216;s superclass (<code>tabular</code>) just like <code>table</code> does.<br />
Inside the <i>disp.m</i> method mentioned above, the headers markup is controlled (around line 45, depending on your Matlab release) by <code>matlab.internal.display.isHot</code>. Unfortunately, there is no corresponding <i>setHot()</i> method, nor corresponding m- or p-code that can be inspected. But the term &#8220;Hot&#8221; rang a bell, and then I remembered my old post about the HotLinks feature, which is apparently reflected by <code>matlab.internal.display.isHot</code>.</p>
<pre lang="matlab">
feature('HotLinks',false);  % temporarily disable bold headers and hyperlinks (matlab.internal.display.isHot=false)
disp(myTable)
myTable        % this calls disp() implicitly
feature('HotLinks',true);   % restore the standard behavior (markup displayed, matlab.internal.display.isHot=true)
</pre>
<p>Searching for &#8220;isHot&#8221; or &#8220;HotLinks&#8221; under the Matlab installation folder, we find that this feature is used in hundreds of places (the exact number depends on your installed toolboxes). The general use appears to be to disable/enable output of hyperlinks to the Matlab console, such as when you display a Matlab class, when its class name is hyperlinked and so is the &#8220;Show all properties&#8221; message at the bottom. But in certain cases, such as for the <code>table</code> output above, the feature is also used to determine other types of markup (bold headers in this case).<br />
<span id="more-7128"></span></p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; feature<span style="color: #080;">(</span><span style="color:#A020F0;">'HotLinks'</span>,<span style="color: #33f;">0</span><span style="color: #080;">)</span>  <span style="color: #228B22;">% temporarily disable bold headers and hyperlinks</span>
&gt;&gt; groot
ans =
  Graphics Root with properties:
&nbsp;
          CurrentFigure: [0×0 GraphicsPlaceholder]
    ScreenPixelsPerInch: 96
             ScreenSize: [1 1 1366 768]
       MonitorPositions: [2×4 double]
                  Units: 'pixels'
&nbsp;
  Use GET to show all properties
&gt;&gt; feature<span style="color: #080;">(</span><span style="color:#A020F0;">'HotLinks'</span>,<span style="color: #33f;">1</span><span style="color: #080;">)</span>  <span style="color: #228B22;">% restore the standard behavior (markup displayed)</span>
&gt;&gt; groot
ans =
  Graphics <span style="color: #0000FF;"><u>Root</u></span> with properties:
&nbsp;
          CurrentFigure: [0×0 GraphicsPlaceholder]
    ScreenPixelsPerInch: 96
             ScreenSize: [1 1 1366 768]
       MonitorPositions: [2×4 double]
                  Units: 'pixels'
&nbsp;
  Show <span style="color: #0000FF;"><u>all properties</u></span></pre>
</div>
</div>
<p>There&#8217;s nothing really earth shuttering in all this, but the HotLinks feature could be useful when outputting console output into a diary file. Of course, if <i><b>diary</b></i> would have automatically stripped away markup tags we would not need to resort to such hackery. Then again, this is not the only problem with <i><b>diary</b></i>, which is <a href="/articles/couple-of-matlab-bugs-and-workarounds#comment-340803" target="_blank">long-overdue an overhaul</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/the-hotlinks-feature">The HotLinks feature</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-function" rel="bookmark" title="Undocumented feature() function">Undocumented feature() function </a> <small>Matlab's undocumented feature function enables access to some internal experimental features...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-feature-list" rel="bookmark" title="Undocumented feature list">Undocumented feature list </a> <small>A list of undocumented MATLAB features can be retrieved. Here's how... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/legend-semi-documented-feature" rel="bookmark" title="Legend &#039;-DynamicLegend&#039; semi-documented feature">Legend &#039;-DynamicLegend&#039; semi-documented feature </a> <small>The built-in Matlab legend function has a very useful semi-documented feature for automatic dynamic update, which is explained here....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/the-hotlinks-feature/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>User-defined tab completions &#8211; take 2</title>
		<link>https://undocumentedmatlab.com/articles/user-defined-tab-completions-take-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=user-defined-tab-completions-take-2</link>
					<comments>https://undocumentedmatlab.com/articles/user-defined-tab-completions-take-2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 12 Jul 2017 13:00:30 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6961</guid>

					<description><![CDATA[<p>Matlab has changed the mechanism that enables user-defined tab-completion of function inputs. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/user-defined-tab-completions-take-2">User-defined tab completions &#8211; take 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/setting-desktop-tab-completions" rel="bookmark" title="Setting desktop tab completions">Setting desktop tab completions </a> <small>The Matlab desktop's Command-Window tab-completion can be customized for user-defined functions...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/enabling-user-callbacks-during-zoom-pan" rel="bookmark" title="Enabling user callbacks during zoom/pan">Enabling user callbacks during zoom/pan </a> <small>Matlab zoom, pan and rotate3d modes hijack the user's figure callbacks, but this can be overridden. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/removing-user-preferences-from-deployed-apps" rel="bookmark" title="Removing user preferences from deployed apps">Removing user preferences from deployed apps </a> <small>An unsupported MathWorks Technical Solution explains how to remove private information from deployed (compiled) matlab applications. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Back in 2010, I posted about Matlab&#8217;s undocumented mechanism for <a href="/articles/setting-desktop-tab-completions" target="_blank">setting Matlab desktop tab-completions</a>. That mechanism used a couple of internal files (<i>TC.xml</i> and <i>TC.xsd</i>) to describe the various possible options that are auto-completed (or displayed in a small tooltip window) when the user clicks the &lt;Tab&gt; key on partially-entered function input parameters.<br />
<center><figure style="width: 408px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Using TabComplete for user-defined functions" src="https://undocumentedmatlab.com/images/tabcomplete.png" title="Using TabComplete for user-defined functions" width="408" height="147" /><figcaption class="wp-caption-text">Using TabComplete for user-defined functions</figcaption></figure></center><br />
Unfortunately, this mechanism apparently broke in R2016a and was replaced with a new mechanism, as explained below.<br />
The new mechanism relies on a file called <i>functionSignatures.json</i> which exists in every single folder that contains Matlab files that have functions whose input parameters ought to be tab-completable.<br />
The new mechanism offers far greater versatility and flexability in defining the input types and inter-relationsships compared to the old TC.*-based mechanism. Another important benefit is that we can now add custom user-defined <i>functionSignatures.json</i> files to our user folders, next to our m-files, without having to modify any Matlab system file.<br />
<span id="more-6961"></span><br />
Note that you may need to restart Matlab the first time that you create a <i>functionSignatures.json</i> file. But once it&#8217;s created, you can modify it within a Matlab session and the changes take effect immediately.<br />
Note: Credit for first posting about this new mechanism goes to <a href="https://www.mathworks.com/matlabcentral/answers/9046-autocomplete-of-filenames-for-function-input-params#answer_256591" rel="nofollow" target="_blank">Nicholas Mati</a>. I&#8217;ve known about this new mechanism for over a year, but I never found the time to write about it until now, so Nicholas gets credit for breaking the scoop. The discussion below uses and expands Nicholas&#8217; original post.</p>
<h3 id="syntax">Syntax</h3>
<p>The <i>functionSignatures.json</i> file has the general form:</p>
<pre lang="text">
{
	"FunctionName1":
	{
		"key1":"val1",
		"key2":"val2",
		"keyn":"valn"
	},
	"FunctionName2":
	{
		"key1":"val1",
		"key2":"val2",
		"keyn":"valn"
	}
}
</pre>
<p>A number of keys are supported including &#8220;<b>platform</b>&#8220;, &#8220;<b>setsAns</b>&#8220;, &#8220;<b>inputs</b>&#8220;, and &#8220;<b>outputs</b>&#8220;, although inputs and outputs are by far the most common (and presumably only inputs are relevant for tab-completion). These keys take an array of (or a single) object value(s). The objects typically take one of the following forms:</p>
<pre lang="text">
{"name":"variable_name", "kind":"kind_option", "type":"string_or_array_of_type"}
{"mutuallyExclusiveGroup":
	[
		...
	]
}
{"name":"varargin", "kind":"optional", "multiplicity":"append"}
</pre>
<p>The value for &#8220;kind&#8221; can be &#8220;required&#8221;, &#8220;optional&#8221;, &#8220;positional&#8221;, &#8220;flag&#8221;, &#8220;namevalue&#8221; or &#8220;platform&#8221; (and perhaps a few other lesser-used kinds):</p>
<ul>
<li>&#8220;<b>required</b>&#8221; means that the specified input is mandatory</li>
<li>&#8220;<b>optional</b>&#8221; means that it can be added or omitted</li>
<li>&#8220;<b>positional</b>&#8221; means that it&#8217;s an optional input but if it is specified then it must appear at the specified position relative to the previous (earlier) inputs</li>
<li>&#8220;<b>flag</b>&#8221; means that it&#8217;s an optional input flag, from a predefined list of one or more single-token strings. For example, in <code>regexp(s1,s2,'once')</code> the last input arg (<code>'once'</code>) is such a flag.</li>
<li>&#8220;<b>namevalue</b>&#8221; means that it follows Matlab&#8217;s standard practice of using P-V pairs (parameter name followed by its value). For example, <code>func('propName',propValue)</code></li>
<li>&#8220;<b>platform</b>&#8221; indicates that this input is only available on the specified platform(s)</li>
</ul>
<p>These &#8220;kind&#8221;s are all explained below.<br />
The value for &#8220;type&#8221; can be a string such as &#8220;char&#8221; or &#8220;numeric&#8221; or &#8220;filepath&#8221;, or a more complicated JSON array (see below).<br />
In addition to &#8220;name&#8221;, &#8220;kind&#8221; and &#8220;type&#8221;, we can also define a &#8220;default&#8221; value (e.g. <code>"default":"false"</code>) and a &#8220;display&#8221; string. While these are [currently] not used by Desktop tab-completion, they might be used by other components such as the JIT compiler or the Editor, if not today then perhaps in a future release.<br />
Note that while pure JSON format does not accept comments, Matlab&#8217;s <i>functionSignatures.json</i> does accept C++-style comments, as discovered by Heiko in a <a href="/articles/user-defined-tab-completions-take-2#comment-410166">comment below</a>. To add a comment, simply add <code>// comment text</code> at the end of any line, or <code>/* comment text */</code> anywhere within a line.</p>
<h3 id="examples">Usage examples</h3>
<p>Multiple examples of <i>functionSignatures.json</i> files can be found in subfolders of <i>%matlabroot%/toolbox/matlab</i>. For example, here&#8217;s the tab-completion definition for the <i><b>visdiff</b></i> function, which displays a visual comparison between two files, and resides in <i>%matlabroot%/toolbox/shared/comparisons/functionSignatures.json</i>:</p>
<pre lang="text">
{
"visdiff":
{
    "inputs":
    [
        {"name":"filename1", "kind":"required",   "type":"filepath"},
        {"name":"filename2", "kind":"required",   "type":"filepath"},
        {"name":"type",      "kind":"positional", "type":"choices={'text', 'binary'}"}
    ]
}
}
</pre>
<p>As can be seen in this example, the first and second inputs are expected to be a filename, whereas the third input is one of the two predefined strings &#8216;text&#8217; or &#8216;binary&#8217;. This third input has &#8220;kind&#8221;:&#8221;positional&#8221;, meaning that it is optional, but if it is provided then it must be in the 3rd position and cannot appear sooner. Moreover, if the user specifies any input argument to the &#8220;right&#8221; of a positional input, then the positional argument becomes required, not optional.<br />
Whereas a &#8220;positional&#8221; parameter has a specific position in the args list (#3 in the case of <i><b>visdiff</b></i> above), an &#8220;optional&#8221; parameter may appear anywhere in the list of inputs.<br />
Here&#8217;s a more complex example, for the built-in <i><b>regexprep</b></i> function (in <i>%matlabroot%/toolbox/matlab/strfun/functionSignatures.json</i>). This example shows how to limit the input to certain data types and how to specify optional input flags with pre-defined choices:</p>
<pre lang="text">
"regexprep":
{
	"inputs":
	[
		{"name":"str",               "kind":"required",  "type":[["char"], ["cell"], ["string"]]},
		{"name":"expression",        "kind":"required",  "type":[["char"], ["cell"], ["string"]]},
		{"name":"replace",           "kind":"required",  "type":[["char"], ["cell"], ["string"]]},
		{"name":"optMatch",          "kind":"flag",      "display":"", "type":[["char", "choices={'all','once'}"], ["numeric", "scalar"]],   "default":"'all'"},
		{"name":"optWarnings",       "kind":"flag",      "display":"", "type":["char", "choices={'nowarnings','warnings'}"],                 "default":"'nowarnings'"},
		{"name":"optCase",           "kind":"flag",      "display":"", "type":["char", "choices={'matchcase','ignorecase','preservecase'}"], "default":"'matchcase'"},
		{"name":"optEmptyMatch",     "kind":"flag",      "display":"", "type":["char", "choices={'noemptymatch','emptymatch'}"],             "default":"'noemptymatch'"},
		{"name":"optDotAll",         "kind":"flag",      "display":"", "type":["char", "choices={'dotall','dotexceptnewline'}"],             "default":"'dotall'"},
		{"name":"optStringAnchors",  "kind":"flag",      "display":"", "type":["char", "choices={'stringanchors','lineanchors'}"],           "default":"'stringanchors'"},
		{"name":"optSpacing",        "kind":"flag",      "display":"", "type":["char", "choices={'literalspacing','freespacing'}"],          "default":"'literalspacing'"}
	],
	"outputs":
	[
		{"name":"newStr", "type":[["char"], ["cell"], ["string"]]}
	]
},
</pre>
<p>Here&#8217;s an even more complex example, this time for the <i><b>codegen</b></i> function (in <i>%matlabroot%/toolbox/coder/matlabcoder/functionSignatures.json</i>, part of the Matlab Coder toolbox). This example shows how to limit the filenames to certain extensions and how to specify name-value input pairs:</p>
<pre lang="text">
"codegen":
{
	"inputs":
	[
		{"name":"compile_only",  "kind":"flag",       "type":"choices={'-c'}"},
		{"name":"config_flag",   "kind":"flag",       "type":"choices={'-config:mex','-config:lib','-config:dll','-config:exe','-config:hdl'}"},
		{"name":"debug",         "kind":"flag",       "type":"choices={'-g'}"},
		{"name":"report",        "kind":"flag",       "type":"choices={'-report'}"},
		{"name":"launchreport",  "kind":"flag",       "type":"choices={'-launchreport'}"},
		{"name":"file",          "kind":"flag",       "type":"filepath=*.m,*.mlx,*.c,*.cpp,*.h,*.o,*.obj,*.a,*.so,*.lib,*.tmf", "multiplicity":"append"},
		{"name":"-d",            "kind":"namevalue",  "type":"folderpath"},
		{"name":"-I",            "kind":"namevalue",  "type":"folderpath"},
		{"name":"-globals",      "kind":"namevalue"},
		{"name":"-o",            "kind":"namevalue",  "type":[["char"], ["filepath"]]},
		{"name":"-O",            "kind":"namevalue",  "type":"choices={'enable:inline','disable:inline','enable:blas','disable:blas','enable:openmp','disable:openmp'}"},
		{"name":"-args",         "kind":"namevalue",  "type":[["identifier=variable"], ["char"]]},
		{"name":"-config",       "kind":"namevalue",  "type":[["identifier=variable"], ["char"]]},
		{"name":"verbose",       "kind":"flag",       "type":"choices={'-v'}"},
		{"name":"singleC",       "kind":"flag",       "type":"choices={'-singleC'}"},
		{"name":"-test",         "kind":"namevalue",  "type":"identifier=function"}
	]
},
</pre>
<h3 id="types">Argument types</h3>
<p>As noted above, we use <code>"type":...</code> to specify the expected data type of each parameter. This can be a simple string such as &#8220;char&#8221;, &#8220;cellstr&#8221;, &#8220;numeric&#8221;, &#8220;table&#8221;, &#8220;categorical&#8221;, &#8220;filepath&#8221;, &#8220;folderpath&#8221;, &#8220;matlabpath&#8221;, class name, or a more complicated JSON array. For example:</p>
<ul>
<li><code>"type":["numeric","scalar"]</code></li>
<li><code>"type":["numeric","numel=3",">=4"]</code></li>
<li><code>"type":[["char"], ["cellstr"], ["numeric"], ["logical","vector"]]</code></li>
<li><code>"type":[["char", "choices={'-ascii'}"]]</code></li>
<li><code>"type":[["filepath"], ["matlabpath=*.m,*.mlx"], ["char"]]</code></li>
<li><code>"type":"identifier=variable,function,localfunction,package,classdef"</code></li>
<li><code>"type":"matlab.graphics.axis.Axes"</code></li>
<li><code>"type":"choices={'yes','no','maybe'}"</code></li>
</ul>
<p>We can even specify on-the-fly Matlab computation that returns a cell-array of values, for example a list of available fonts via <code>"type":"choices=listfonts"</code>. A more complex example is the definition of the <i><b>rmfield</b></i> function, where the possible input choices for the second input arg (highlighted) depend on the struct that is provided in the first input arg (by running the <i><b>fieldnames</b></i> function on it):</p>
<pre lang="text" highlight="6">
"rmfield":
{
	"inputs":
	[
		{"name":"s",     "kind":"required", "type":"struct"},
		{"name":"field", "kind":"required", "type":"choices=fieldnames(s)"}
	],
	"outputs":
	[
		{"name":"s", "type":"struct"}
	]
},
</pre>
<h3 id="alternatives">Alternative inputs</h3>
<p>Multiple alternative inputs can be specified in the <i>functionSignatures.json</i> file. The easiest way to do so is to simply create multiple different definitions for the same function, one beneath the other. Matlab&#8217;s tab-completion parser is smart enough to combine those definitions and proceed with the most appropriate one based on the user-entered inputs.<br />
For example, in the same Coder file above we find 6 alternative definitions. If (for example) we start typing <code>coder('-ecoder',</code> and click &lt;Tab&gt;, Matlab would automatically auto-complete the second input to &#8220;false&#8221;, and then another &lt;Tab&gt; click would set the third input to the required &#8216;-new&#8217; parameter (see highlighted lines below):</p>
<pre lang="text" highlight="34-37">
...
"coder":
{
	"inputs":
	[
		{"name":"projectname", "kind":"required", "type":"filepath=*.prj"}
	]
},
"coder":
{
	"inputs":
	[
		{"name":"-open", "kind":"namevalue", "type":"filepath=*.prj"}
	]
},
"coder":
{
	"inputs":
	[
		{"name":"-build", "kind":"namevalue", "type":"filepath=*.prj"}
	]
},
"coder":
{
	"inputs":
	[
		{"name":"-new", "kind":"namevalue", "type":[["filepath=*.prj"], ["char"]]}
	]
},
"coder":
{
	"inputs":
	[
		{"name":"ecoderFlag",  "kind":"required", "type":"choices={'-ecoder'}"},
		{"name":"ecoderValue", "kind":"required", "type":[["logical"], ["choices={'false'}"]]},
		{"name":"newFlag",     "kind":"required", "type":"choices={'-new'}"},
		{"name":"newvalue",    "kind":"required", "type":[["filepath=*.prj"], ["char"]]}
	]
},
"coder":
{
	"inputs":
	[
		{"name":"tocodeFlag",  "kind":"required", "type":"choices={'-tocode'}"},
		{"name":"tocodevalue", "kind":"required", "type":"filepath=*.prj"},
		{"mutuallyExclusiveGroup":
			[
				[],
				[
					{"name":"scriptFlag", "kind":"required", "type":"choices={'-script'}"},
					{"name":"scriptname", "kind":"required", "type":[["filepath=*.m"], ["char"]]}
				]
			]
		}
	]
}
</pre>
<p>This example also shows, in the last definition for the <i><b>coder</b></i> function, another mechanism for specifying alternative inputs, using &#8220;<b>mutuallyExclusiveGroup</b>&#8221; (aka &#8220;MEGs&#8221;). A MEG is defined using an array of options, enclosed in square brackets (<code>[]</code>). Each of the MEG options is exclusive to each of the others, meaning that we can only work with one of them and not the others. This is equivalent to duplicating the definition as we saw above, and saves us some copy-paste (in some cases a lot of copy-pastes, especially with multiple and/or nested MEGs). However, MEGs have a major drawback of reduced readability. I believe that in most cases we only have a single MEG and few input args, and in such cases it makes more sense to use repeated function defs rather than a MEG. The Matlab signature files contain numerous usage examples for either of these two mechanisms.</p>
<h3 id="platform">Platform dependencies</h3>
<p>If a specific function (or a specific signature variant) depends on the running platform, this can be specified via the &#8220;platform&#8221; directive. For example, the <i><b>winopen</b></i> function only works on Windows, but not on Linux/Mac. Its corresponding signature definition is:</p>
<pre lang="text" highlight="3">
"winopen":
{
	"platform":"win32,win64",
	"inputs":
	[
		{"name":"filename", "kind":"required", "type":"filepath"},
		{"name":"varargin", "kind":"optional", "multiplicity":"append"}
	]
}
</pre>
<p>Platform dependence could also be specified at the parameter level, not just the entire function level. For example, in the <i><b>xlsread</b></i> function (defined in <i>%matlabroot%/toolbox/matlab/iofun/functionSignatures.json</i>), we see that the usage variant <code>xlsread(filename,-1)</code> is only available on Windows (note that the numeric value is defined as <code>"&lt;=-1"</code>, not necessarily -1), and so is the &#8220;functionHandle&#8221; input (which is called <i>processFcn</i> in the documentation &#8211; for some reason that escapes me the names of many input args do not match in the documentation and functionSignature):</p>
<pre lang="text" highlight="8,14">
"xlsread":
{
	"inputs":
	[
		{"name":"filename", "kind":"required", "type":"filepath=*.xls,*.xlsx,*.xlsb,*.csv"},
		{"mutuallyExclusiveGroup":
			[
				{"name":"openExcel", "kind":"required", "display":"", "type":["numeric", "<=-1"], "platform":"win64,win32"},
				{"name":"xlRange",   "kind":"required", "type":["char", "@(x) isempty(x) || ~isempty(strfind(x, ':'))"], "default":"''"},
				[
					{"name":"sheet",          "kind":"positional", "type":[["char", "choices=matlab.internal.language.introspective.tabcompletion.xlsread_vsheet(filename)"], ["numeric", ">=1"]], "default":"1"},
					{"name":"xlRange",        "kind":"positional", "type":"char", "default":"''"},
					{"name":"basic",          "kind":"positional", "display":"", "type":["char", "choices={'basic',''}"]},
					{"name":"functionHandle", "kind":"positional", "type":"function_handle", "platform":"win64,win32"}
				]
			]
		}
	],
        ...
</pre>
<h3 id="parsing">Parsing errors</h3>
<p>The new mechanism is not very user-friendly when you get something wrong. In the best case, it issues a cryptic error message (see below), and in the worst case it simply ignores the changes and the user has no idea why the new custom tab-completion is not working as intended.<br />
The most likely causes of such problems are:</p>
<ul>
<li>The most common problem is that you placed the <i>functionSignatures.json</i> file in a different folder than the Matlab function. For example, if the myFunction() function is defined in <i>myFunction.m</i>, then the tab-completion of this function MUST be located in a <i>functionSignatures.json</i> file that resides in the same folder, not anywhere else on the Matlab path. In other words, the Matlab path is NOT relevant for tab-completion.</li>
<li>Your <i>functionSignatures.json</i> file does not follow the [extremely strict] syntax rules above, to the letter. For example, forgetting the top or final curly braces, forgetting a comma or adding an extra one, or not closing all brackets/braces properly.</li>
<li>You mistyped one or more of the input parameters, types or options.</li>
</ul>
<p>In case of a parsing error, you&#8217;d see a red error message on the Matlab console the next time that you try to use tab-completion:<br />
<code><font color="red">Error parsing JSON data; Boost reports "<unspecified file>(189): expected ',' or ']'"</font></code>.<br />
Unfortunately the error message only tells us the problematic line location within the <i>functionSignatures.json</i> file, but not the file&#8217;s location, so if we haven&#8217;t recently edited this file we&#8217;d need to find it in the relevant folder. For example:</p>
<pre lang="matlab">edit(fullfile(fileparts(which('myFunction')), 'functionSignatures.json')</pre>
<p>Moreover, when a JSON syntax error (such as the one above) occurs, the <i>entire</i> file is not parsed, not just the definition that caused the error.<br />
Another limitation of tab-completion is that it does not work while the main Matlab thread is working (e.g., during a <i><b>uiwait</b></i> or <i><b>waitfor</b></i>). This may be somewhat misleading since most editor/debugging actions do work.<br />
Arguably, this new tab-completion mechanism could be made more programmer-friendly. Perhaps this will improve in a future Matlab release.<br />
<b><u>Addendum</u></b>: MathWorks has now made this functionality supported and documented. <a href="https://www.mathworks.com/help/matlab/matlab_prog/customize-code-suggestions-and-completions.html" rel="nofollow" target="_blank">Read about it here</a>.<br />
For a related mechanism, see my article on <a href="/articles/class-object-tab-completion-and-improper-field-names" target="_blank">tab-completion for class properties and methods</a> from 2014, which is apparently still relevant and functional.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/user-defined-tab-completions-take-2">User-defined tab completions &#8211; take 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/setting-desktop-tab-completions" rel="bookmark" title="Setting desktop tab completions">Setting desktop tab completions </a> <small>The Matlab desktop's Command-Window tab-completion can be customized for user-defined functions...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/enabling-user-callbacks-during-zoom-pan" rel="bookmark" title="Enabling user callbacks during zoom/pan">Enabling user callbacks during zoom/pan </a> <small>Matlab zoom, pan and rotate3d modes hijack the user's figure callbacks, but this can be overridden. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/removing-user-preferences-from-deployed-apps" rel="bookmark" title="Removing user preferences from deployed apps">Removing user preferences from deployed apps </a> <small>An unsupported MathWorks Technical Solution explains how to remove private information from deployed (compiled) matlab applications. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/creating-a-simple-udd-class" rel="bookmark" title="Creating a simple UDD class">Creating a simple UDD class </a> <small>This article explains how to create and test custom UDD packages, classes and objects...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/user-defined-tab-completions-take-2/feed</wfw:commentRss>
			<slash:comments>15</slash:comments>
		
		
			</item>
		<item>
		<title>Working with non-standard DPI displays</title>
		<link>https://undocumentedmatlab.com/articles/working-with-non-standard-dpi-displays?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=working-with-non-standard-dpi-displays</link>
					<comments>https://undocumentedmatlab.com/articles/working-with-non-standard-dpi-displays#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 09 Nov 2016 21:47:27 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6736</guid>

					<description><![CDATA[<p>Matlab uses logical (scaled)  pixel positions. With high-DPI displays, this might cause problems, but it is easy to retrieve the physical (unscaled) pixel values. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/working-with-non-standard-dpi-displays">Working with non-standard DPI displays</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar" rel="bookmark" title="Customizing the standard figure toolbar, menubar">Customizing the standard figure toolbar, menubar </a> <small>The standard figure toolbar and menubar can easily be modified to include a list of recently-used files....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/faster-findjobj" rel="bookmark" title="Faster findjobj">Faster findjobj </a> <small>the ubiquitous findjobj utility has been significantly improved for speed for the most common use case. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/findjobj-find-underlying-java-object" rel="bookmark" title="FindJObj &#8211; find a Matlab component&#039;s underlying Java object">FindJObj &#8211; find a Matlab component&#039;s underlying Java object </a> <small>The FindJObj utility can be used to access and display the internal components of Matlab controls and containers. This article explains its uses and inner mechanism....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>With high-density displays becoming increasingly popular, some users set their display&#8217;s DPI to a higher-than-standard (i.e., >100%) value, in order to compensate for the increased pixel density to achieve readable interfaces. This OS setting tells the running applications that there are fewer visible screen pixels, and these are spread over a larger number of physical pixels. This works well for most cases (at least on recent OSes, it was a bit buggy in non-recet ones). Unfortunately, in some cases we might actually want to know the screen size in physical, rather than logical, pixels. Apparently, Matlab root&#8217;s <b>ScreenSize</b> property only reports the logical (scaled) pixel size, not the physical (unscaled) one:</p>
<pre lang="matlab">
>> get(0,'ScreenSize')   % with 100% DPI (unscaled standard)
ans =
        1       1      1366       768
>> get(0,'ScreenSize')   % with 125% DPI (scaled)
ans =
        1       1      1092.8     614.4
</pre>
<p>The same phenomenon also affects other related properties, for example <b>MonitorPositions</b>.<br />
Raimund Schlüßler, a reader on this blog, was kind enough to point me to this problem and its workaround, which I thought worthy to share here: To get the physical screen-size, use the following builtin Java command:</p>
<pre lang="matlab">
>> jScreenSize = java.awt.Toolkit.getDefaultToolkit.getScreenSize
jScreenSize =
java.awt.Dimension[width=1366,height=768]
>> width = jScreenSize.getWidth
width =
        1366
>> height = jScreenSize.getHeight
height =
        768
</pre>
<p>Also see the related recent article on <a href="/articles/graphic-sizing-in-matlab-r2015b" rel="nofollow" target="_blank">an issue with the DPI-aware feature starting with R2015b</a>.</p>
<h3 id="travels">Upcoming travels &#8211; London/Belfast, Zürich &#038; Geneva</h3>
<p>I will shortly be traveling to consult some clients in Belfast (via London), Zürich and Geneva. If you are in the area and wish to meet me to discuss how I could bring value to your work, then please email me (altmany at gmail):</p>
<ul>
<li><b>Belfast</b>: Nov 28 &#8211; Dec 1 (flying via London)</li>
<li><b>Zürich</b>: Dec 11-12</li>
<li><b>Geneva</b>: Dec 13-15</li>
</ul>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/working-with-non-standard-dpi-displays">Working with non-standard DPI displays</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-standard-figure-toolbar-menubar" rel="bookmark" title="Customizing the standard figure toolbar, menubar">Customizing the standard figure toolbar, menubar </a> <small>The standard figure toolbar and menubar can easily be modified to include a list of recently-used files....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/faster-findjobj" rel="bookmark" title="Faster findjobj">Faster findjobj </a> <small>the ubiquitous findjobj utility has been significantly improved for speed for the most common use case. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/findjobj-find-underlying-java-object" rel="bookmark" title="FindJObj &#8211; find a Matlab component&#039;s underlying Java object">FindJObj &#8211; find a Matlab component&#039;s underlying Java object </a> <small>The FindJObj utility can be used to access and display the internal components of Matlab controls and containers. This article explains its uses and inner mechanism....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/working-with-non-standard-dpi-displays/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Handling red Java console errors</title>
		<link>https://undocumentedmatlab.com/articles/handling-red-java-console-errors?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=handling-red-java-console-errors</link>
					<comments>https://undocumentedmatlab.com/articles/handling-red-java-console-errors#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 29 Jun 2016 17:00:51 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6468</guid>

					<description><![CDATA[<p>Red Java errors are sometimes displayed in the Matlab console. They can be removed  or avoided in a variety of means. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/handling-red-java-console-errors">Handling red Java console errors</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/converting-java-vectors-to-matlab-arrays" rel="bookmark" title="Converting Java vectors to Matlab arrays">Converting Java vectors to Matlab arrays </a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a" rel="bookmark" title="Matlab callbacks for Java events in R2014a">Matlab callbacks for Java events in R2014a </a> <small>R2014a changed the way in which Java objects expose events as Matlab callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/the-java-import-directive" rel="bookmark" title="The Java import directive">The Java import directive </a> <small>The import function can be used to clarify Java code used in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-java-collections-in-matlab" rel="bookmark" title="Using Java Collections in Matlab">Using Java Collections in Matlab </a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Anyone who has worked with non-trivial Matlab GUIs knows that from time to time we see various red Java stack-trace errors appear in the Matlab console (Command Window). These errors do not appear often when using documented Matlab controls, but they do from time to time. The errors appear significantly more frequently when working with undocumented Java-based hacks that I often show on this blog, and especially when working with complex controls such as <i><b>uitable</b></i> or <i><b>uitree</b></i>. Such controls have a very large code-base under the hood, and the Matlab code and data sometimes clashes with the asynchronous Java methods that run on a separate thread. Such clashes and race conditions often lead to red Java stack-trace errors that are spewed onto the Matlab console. For example:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace; color:red;">
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at com.jidesoft.plaf.basic.BasicCellSpanTableUI.paint(Unknown Source)
	at javax.swing.plaf.ComponentUI.update(Unknown Source)
	at javax.swing.JComponent.paintComponent(Unknown Source)
	at com.jidesoft.grid.CellStyleTable.paintComponent(Unknown Source)
	at javax.swing.JComponent.paint(Unknown Source)
	at javax.swing.JComponent.paintToOffscreen(Unknown Source)
	...
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 >= 0
	at java.util.Vector.elementAt(Unknown Source)
	at javax.swing.table.DefaultTableColumnModel.getColumn(Unknown Source)
	at com.jidesoft.grid.ContextSensitiveTable.getCellRenderer(Unknown Source)
	at com.jidesoft.grid.CellSpanTable.getCellRenderer(Unknown Source)
	at com.jidesoft.grid.TreeTable.getActualCellRenderer(Unknown Source)
	at com.jidesoft.grid.GroupTable.getCellRenderer(Unknown Source)
	at com.jidesoft.grid.JideTable.b(Unknown Source)
	at com.jidesoft.grid.CellSpanTable.calculateRowHeight(Unknown Source)
	...
</pre>
</div>
</div>
<p>In almost all such Java error messages, the error is asynchronous to the Matlab code and does not interrupt it. No error exception is thrown (or can be trapped), and the Matlab code proceeds without being aware that anything is wrong. In fact, in the vast majority of such cases, nothing is visibly wrong &#8211; the program somehow overcomes the reported problem and there are no visible negative effects on the GUI. In other words, these error messages are harmless and can almost always be ignored. Still, if we could only stop those annoying endless red stack-trace messages in the Matlab console!<br />
<span id="more-6468"></span><br />
Note that today&#8217;s post only discusses untrappable <i>asynchronous</i> Java error messages, not <i>synchronous</i> errors that can be trapped in Matlab via <i><b>try-catch</b></i>. These synchronous errors are often due to programmatic errors (e.g., bad method input args or an empty reference handle) and can easily be handled programmatically. On the other hand, the asynchronous errors are non-trappable, so they are much more difficult to isolate and fix.<br />
In many of the cases, the error occurs when the control&#8217;s underlying data model is changed by the Matlab code, and some of the controls&#8217;s Java methods are not synced with the new model by the time they run. This can be due to internal bugs in the Matlab or Java control&#8217;s implementation, or to simple race conditions that occur between the Matlab thread and the Java Event Dispatch Thread (EDT). As <a href="/articles/matlab-and-the-event-dispatch-thread-edt" target="_blank">noted here</a>, such race conditions can often be solved by introducing a simple delay into the Matlab code:</p>
<pre lang="matlab" highlight="2">
javaControl.doSomething();
pause(0.05); drawnow;
javaControl.doSomethingElse();
</pre>
<p>In addition, asking Matlab to run the Java component&#8217;s methods on the EDT can also help solve race conditions:</p>
<pre lang="matlab">javaControl = javaObjectEDT(javaControl);</pre>
<p>Unfortunately, sometimes both of these are not enough. In such cases, one of the following ideas might help:</p>
<ul>
<li>Add <code>fprintf(' \b')</code> to your Matlab code: this seemingly innocent hack of displaying a space &#038; immediately erasing it with backspace, appears to force the Java engine to flush its event queue and synchronize things, thereby avoiding the annoying Java console errors. I know it sounds like adding a sprinkle of useless black magic to the code, but it does really work in some cases!
<pre lang="matlab" highlight="3">
javaControl.doSomething();
pause(0.05); drawnow;  % this never hurt anyone!
fprintf(' \b');
javaControl.doSomethingElse();
</pre>
</li>
<li>It is also possible to directly access the console text area and remove all the text after a certain point. Note that I strongly discourage messing around with the console text in this manner, since it might cause problems with Matlab&#8217;s internals. Still, if you are adventurous enough to try, then here&#8217;s an example:
<pre lang="matlab">
jCmdWinDoc = com.mathworks.mde.cmdwin.CmdWinDocument.getInstance;
currentPos = cmdWinDoc.getLength;
javaControl.doSomething();
pause(0.05); drawnow;  % this never hurt anyone!
javaControl.doSomethingElse();
pause(0.1);  % let the java error time to display itself in the console
jCmdWinDoc.remove(currentPos, cmdWinDoc.getLength-currentPos);
</pre>
</li>
<li>When all else fails, consider simply clearing the Matlab console using the Matlab <i><b>clc</b></i> command a short while after updating the Java control. This will erase the red Java errors, along with everything else in the console, so naturally it cannot be freely used if you use the console to display useful information to the user.</li>
</ul>
<p>It should be emphasized: not all of these suggested remedies work in all cases; in some cases some of them work, and in other cases others might work. There does not seem to be a general panacea to this issue. The main purpose of the article was to list the possible solutions in a single place, so that users could try them out and select those that work for each specific case.<br />
Do you know of any other (perhaps better) way of avoiding or hiding such asynchronous Java console errors? If so, then please post a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/handling-red-java-console-errors">Handling red Java console errors</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/converting-java-vectors-to-matlab-arrays" rel="bookmark" title="Converting Java vectors to Matlab arrays">Converting Java vectors to Matlab arrays </a> <small>Converting Java vectors to Matlab arrays is pretty simple - this article explains how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events-in-r2014a" rel="bookmark" title="Matlab callbacks for Java events in R2014a">Matlab callbacks for Java events in R2014a </a> <small>R2014a changed the way in which Java objects expose events as Matlab callbacks. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/the-java-import-directive" rel="bookmark" title="The Java import directive">The Java import directive </a> <small>The import function can be used to clarify Java code used in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-java-collections-in-matlab" rel="bookmark" title="Using Java Collections in Matlab">Using Java Collections in Matlab </a> <small>Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/handling-red-java-console-errors/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Viewing saved profiling results</title>
		<link>https://undocumentedmatlab.com/articles/viewing-saved-profiling-results?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=viewing-saved-profiling-results</link>
					<comments>https://undocumentedmatlab.com/articles/viewing-saved-profiling-results#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 18 May 2016 18:00:37 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Semi-documented function]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6421</guid>

					<description><![CDATA[<p>We can easily use saved profiling results to analyze, view and compare profiling results of multiple runs. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/viewing-saved-profiling-results">Viewing saved profiling results</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/function-call-timeline-profiling" rel="bookmark" title="Function call timeline profiling">Function call timeline profiling </a> <small>A new utility enables to interactively explore Matlab function call timeline profiling. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage" rel="bookmark" title="Profiling Matlab memory usage">Profiling Matlab memory usage </a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3" rel="bookmark" title="Undocumented Profiler options part 3">Undocumented Profiler options part 3 </a> <small>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Many Matlab users know and utilize <a href="http://www.mathworks.com/help/matlab/matlab_prog/profiling-for-improving-performance.html" rel="nofollow" target="_blank">Matlab&#8217;s built-in Profiler tool</a> to identify performance bottlenecks and code-coverage issues. Unfortunately, not many are aware of the Profiler&#8217;s programmatic interface. In past articles as well as my performance book I <a href="/articles/undocumented-profiler-options-part-3" target="_blank">explained</a> how we can use this programmatic interface to save profiling results and analyze it offline. In fact, I took this idea further and even created a utility (<a href="/articles/function-call-timeline-profiling" target="_blank"><i><b>profile_history</b></i></a>) that displays the function call timeline in a standalone Matlab GUI, something that is a sorely missed feature in the built-in profiler:<br />
<center><a target="_blank" href="/images/profile_history.png"><img decoding="async" alt="Function call timeline profiling (click for full-size image)" src="https://undocumentedmatlab.com/images/profile_history.png" title="Function call timeline profiling (click for full-size image)" width="100%" style="max-width: 658px;" /></a><br />
Function call timeline profiling (click for full-size image)</center><br />
Today I will discuss a related undocumented feature of the Profiler: loading and viewing pre-saved profiling results.<br />
<span id="more-6421"></span></p>
<h3 id="output">Programmatic access to profiling results</h3>
<p>Matlab&#8217;s syntax for returning the detailed profiling results in a data struct is clearly documented in the <a href="http://www.mathworks.com/help/matlab/ref/profile.html#bux4pud-1" rel="nofollow" target="_blank"><i><b>profile</b></i> function&#8217;s doc page</a>. Although the documentation does not explain the resulting struct and sub-struct fields, they have meaningful names and we can relatively easily infer what each of them means (I added a few annotation comments for clarity):</p>
<pre lang="matlab">
>> profile('on','-history')
>> surf(peaks); drawnow
>> profile('off')
>> profData = profile('info')
profData =
      FunctionTable: [26x1 struct]
    FunctionHistory: [2x56 double]
     ClockPrecision: 4.10517962829241e-07
         ClockSpeed: 2501000000
               Name: 'MATLAB'
           Overhead: 0
>> profData.FunctionTable(1)
ans =
          CompleteName: 'C:\Program Files\Matlab\R2016a\toolbox\matlab\specgraph\peaks.m>peaks'
          FunctionName: 'peaks'
              FileName: 'C:\Program Files\Matlab\R2016a\toolbox\matlab\specgraph\peaks.m'
                  Type: 'M-function'
              Children: [1x1 struct]
               Parents: [0x1 struct]
         ExecutedLines: [9x3 double]
           IsRecursive: 0
    TotalRecursiveTime: 0
           PartialData: 0
              NumCalls: 1
             TotalTime: 0.0191679078068094
>> profData.FunctionTable(1).Children
ans =
        Index: 2   % index in profData.FunctionTable array
     NumCalls: 1
    TotalTime: 0.00136415141013509
>> profData.FunctionTable(1).ExecutedLines   % line number, number of calls, duration in secs
ans =
         43      1      0.000160102031282782
         44      1      2.29890096200918e-05
         45      1      0.00647592190637408
         56      1      0.0017093970724654
         57      1      0.00145036019621044
         58      1      0.000304193859437286
         60      1      4.39254290955326e-05
         62      1      3.44835144301377e-05
         63      1      0.000138755093778411
>> profData.FunctionHistory(:,1:5)
ans =
     0     0     1     1     0   % 0=enter, 1=exit
     1     2     2     1     6   % index in profData.FunctionHistory array
</pre>
<p>As we can see, this is pretty intuitive so far.</p>
<h3 id="viewing">Loading and viewing saved profiling results</h3>
<p>If we wish to save these results results in a file and later load and display them in the Profiler&#8217;s visualization browser, then we need to venture deeper into undocumented territory. It seems that while retrieving the profiling results (via <i><b>profile</b>(&#8216;info&#8217;)</i>) is fully documented, doing the natural complementary action (namely, loading this data into the viewer) is not. For the life of me I cannot understand the logic behind this decision, but that&#8217;s the way it is.<br />
Luckily, the <a href="/articles/legend-semi-documented-feature#Semi-documented" target="_blank">semi-documented built-in function</a> <i><b>profview</b></i> does exactly what we need: <i><b>profview</b></i> accepts 2 input args (function name and the <code>profData</code> struct) and displays the resulting profiling info. The first input arg (function name) accepts either a string (e.g., <code>'peaks'</code> or <code>'view>isAxesHandle'</code>), or the numeric value 0 which signifies the home (top-level) page:</p>
<pre lang="matlab">
profView(0, profData);  % display profiling home (top-level) page
profview('peaks', profData);  % display a specific profiling page
</pre>
<p>I use the 0 input value much more frequently than the string inputs, because I often don&#8217;t know which functions exactly were profiled, and starting at the home page enables me to easily drill-down the profiling results interactively.</p>
<h3 id="viewing">Loading saved profiling results from a different computer</h3>
<p>Things get slightly complicated if we try to load saved profiling results from a different computer. If the other computer has exactly the same folder structure as our computer, and all our Matlab functions reside in exactly the same disk folders/path, then everything will work out of the box. The problem is that in general the other computer will have the functions in different folders. When we then try to load the <code>profData</code> on our computer, it will not find the associated Matlab functinos in order to display the line-by-line profiling results. We will only see the profiling data at the function level, not line level. This significantly reduces the usefulness of the profiling data. The Profiler page will display the following error message:<br />
<center><span style="background: #FFC0C0;"><code>This file was modified during or after profiling. Function listing disabled.</code></span></center><br />
We can solve this problem in either of two ways:</p>
<ol>
<li>Modify our <code>profData</code> to use the correct folder path on the local computer, rather than the other computer&#8217;s path (which is invalid on the local computer). For example:
<pre lang="matlab">
% Save the profData on computer #1:
profData = profile('info');
save('profData.mat', 'profData');
% Load the profData on computer #2:
fileData = load('profData.mat');
profData = fileData.profData;
path1 = 'N:\Users\Juan\programs\myProgram';
path2 = 'C:\Yair\consulting\clients\Intel\code';
for idx = 1 : numel(profData.FunctionTable)
   funcData = profData.FunctionTable(idx);
   funcData.FileName     = strrep(funcData.FileName,     path1, path2);
   funcData.CompleteName = strrep(funcData.CompleteName, path1, path2);
   profData.FunctionTable(idx) = funcData;
end
% note: this loop can be vectorized if you wish
</pre>
</li>
<li>As an alternative, we can modify Matlab&#8217;s <i>profview.m</i> function (<i>%matlabroot%/toolbox/matlab/codetools/profview.m</i>) to search for the function&#8217;s source code in the current Matlab path, if the specified direct path is not found (note that changing <i>profview.m</i> may require administrator priviledges). For example, the following is the code from R2016a&#8217;s <i>profview.m</i> file, line #506:
<pre lang="matlab" highlight="3-5,7-9">
    % g894021 - Make sure the MATLAB code file still exists
    if ~exist(fullName, 'file')
        [~,fname,fext] = fileparts(fullName);  % Yair
        fname = which([fname fext]);           % Yair
        if isempty(fname)                      % Yair
            mFileFlag = 0;
        else                                   % Yair
            fullName = fname;                  % Yair
        end                                    % Yair
    end
</pre>
</li>
</ol>
<p>These two workarounds complement each other: the first workaround does not require changing any installed Matlab code, and so is platform- and release-independent, but would require rerunning the code snippet for each and every profiling data file that we receive from external computers. On the other hand, the second workaround is a one-time operation that should work for multiple saved profiling results, although we would need to redo it whenever we install Matlab.</p>
<h3 id="customizations">Additional <i><b>profview</b></i> customizations</h3>
<p>Modifying the <i>profview.m</i> function can be used for different improvements as well.<br />
For example, several years ago <a href="/articles/undocumented-profiler-options-part-2" target="_blank">I explained</a> how this function can be modified to display 1 ms timing resolutions, rather than the default 10 mS.<br />
Another customization that I often do after I install Matlab is to change the default setting of truncating function lines longer than 40 characters &#8211; I typically modify this to 60 or 80 (depending on the computer monitor&#8217;s size&#8230;). All we need to do is to update the <code>truncateDisplayName</code> sub-function within <i>profview.m</i> as follows (taken from R2016a again, line #1762):</p>
<pre lang="matlab" highlight="3">
function shortFileName = truncateDisplayName(longFileName,maxNameLen)
%TRUNCATEDISPLAYNAME  Truncate the name if it gets too long
maxNameLen = max(60,maxNameLen);  % Yair
shortFileName = escapeHtml(longFileName);
if length(longFileName) > maxNameLen,
    shortFileName = char(com.mathworks.util.FileUtils.truncatePathname( ...
        shortFileName, maxNameLen));
end
</pre>
<p>You can see additional undocumented profiling features in the &#8220;Related posts&#8221; section below, as well as in Chapter 2 of my book &#8220;<a href="/books/matlab-performance" target="_blank"><i>Accelerating MATLAB Performance</i></a>&#8220;.<br />
Do you have any other customization to the profiling results? If so, please share it in a comment.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/viewing-saved-profiling-results">Viewing saved profiling results</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/function-call-timeline-profiling" rel="bookmark" title="Function call timeline profiling">Function call timeline profiling </a> <small>A new utility enables to interactively explore Matlab function call timeline profiling. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/profiling-matlab-memory-usage" rel="bookmark" title="Profiling Matlab memory usage">Profiling Matlab memory usage </a> <small>mtic and mtoc were a couple of undocumented features that enabled users of past Matlab releases to easily profile memory usage. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-4" rel="bookmark" title="Undocumented Profiler options part 4">Undocumented Profiler options part 4 </a> <small>Several undocumented features of the Matlab Profiler can make it much more useful - part 4 of series. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-profiler-options-part-3" rel="bookmark" title="Undocumented Profiler options part 3">Undocumented Profiler options part 3 </a> <small>An undocumented feature of the Matlab Profiler can report call history timeline - part 3 of series. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/viewing-saved-profiling-results/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Programmatic shortcuts manipulation &#8211; part 2</title>
		<link>https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=programmatic-shortcuts-manipulation-part-2</link>
					<comments>https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 30 Dec 2015 16:42:52 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Toolstrip]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6169</guid>

					<description><![CDATA[<p>Non-standard shortcut controls and customizations can easily be added to the Matlab desktop. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2">Programmatic shortcuts manipulation &#8211; part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-1" rel="bookmark" title="Programmatic shortcuts manipulation &#8211; part 1">Programmatic shortcuts manipulation &#8211; part 1 </a> <small>Matlab Desktop shortcuts can be programmatically accessed and customized. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/command-window-text-manipulation" rel="bookmark" title="Command Window text manipulation">Command Window text manipulation </a> <small>Special control characters can be used to format text output in Matlab's Command Window. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization" rel="bookmark" title="Matlab toolstrip – part 4 (control customization)">Matlab toolstrip – part 4 (control customization) </a> <small>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Today I will expand <a target="_blank" href="/articles/programmatic-shortcuts-manipulation-part-1">last week&#8217;s post</a> on customizing Matlab Desktop&#8217;s shortcuts. I will show that we can incorporate non-standard controls, and add tooltips and user callbacks in undocumented ways that are not available using the interactive Desktop GUI.<br />
<center><figure style="width: 584px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Custom shortcut controls" src="https://undocumentedmatlab.com/images/Shortcuts4c.png" title="Custom shortcut controls" width="584" height="182" /><figcaption class="wp-caption-text">Custom shortcut controls</figcaption></figure></center><br />
<span id="more-6169"></span><br />
Today&#8217;s article will focus on the new toolstrip interface of Matlab release R2012b and later; adaptation of the code to R2012a and earlier is relatively easy (in fact, simpler than the toolstrip-based code below).</p>
<h3 id="panel">Displaying the Shortcuts panel</h3>
<p>Before we begin to modify shortcuts in the Toolstrip&#8217;s shortcuts menu, we need to ensure that the Shortcuts panel is visible and active (in current focus), otherwise our customizations will be ignored or cause an error. There is probably a more direct way of doing this, but a simple way that I found was to edit the current Desktop&#8217;s layout to include a directive to display the Shortcuts tab, and then load that layout:</p>
<pre lang='matlab'>
jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
hMainFrame = com.mathworks.mde.desk.MLDesktop.getInstance.getMainFrame;
jToolstrip = hMainFrame.getToolstrip;
isOk = jToolstrip.setCurrentTab('shortcuts');
if ~isOk  % i.e., Shortcuts tab is NOT displayed
    % Save the current Desktop layout
    jDesktop.saveLayout('Yair');  pause(0.15);
    % Update the layout file to display the Shortcuts tab
    filename = fullfile(prefdir, 'YairMATLABLayout.xml');
    fid = fopen(filename, 'rt');
    txt = fread(fid, '*char')';
    fclose(fid);
    txt = regexprep(txt,'(ShowShortcutsTab=)"[^"]*"','');
    txt = regexprep(txt,'(<layout [^>]*)>','$1 ShowShortcutsTab="yes">');
    fid = fopen(filename, 'wt');
    fwrite(fid,txt);
    fclose(fid);
    % Load the modified layout
    jDesktop.restoreLayout('Yair');  pause(0.15);
    % The shortcuts tab should now be visible, so transfer focus to that tab
    jToolstrip.setCurrentTab('shortcuts');
end
</pre>
<h3 id="custom">Custom controls</h3>
<p>As I explained in <a target="_blank" href="/articles/programmatic-shortcuts-manipulation-part-1#in-session">last week&#8217;s post</a>, we can use <code>scUtils.addShortcutToBottom</code> to add a simple push-button shortcut to the relevant category panel within the Shortcuts toolstrip tab. To add custom controls, we can simply add the controls to the relevant shortcut category panel container (a <code>com.mathworks.toolstrip.components.TSPanel</code> object). The standard shortcuts are typically placed in the Shortcuts tab&#8217;s second <code>TSPanel</code> (&#8220;general&#8221;), and other categories have <code>TSPanel</code>s of their own.<br />
Now here&#8217;s the tricky part about <code>TSPanel</code>s: we cannot directly add components to the sectino panel (that would be too easy&#8230;): the section panels are composed of an array of internal <code>TSPanel</code>s, and we need to add the new controls to those internal panels. However, these panels only contain 3 empty slots. If we try to add more than 3 components, the 4th+ component(s) will simply not be displayed. In such cases, we need to create a new <code>TSPanel</code> to display the extra components.<br />
Here then is some sample code to add a combo-box (drop-down) control:</p>
<pre lang='matlab'>
% First, get the last internal TSPanel within the Shortcuts tab's "general" section panel
% Note: jToolstrip was defined in the previous section above
jShortcutsTab = jToolstrip.getModel.get('shortcuts').getComponent;
jSectionPanel = jShortcutsTab.getSectionComponent(1).getSection.getComponent;  % the TSPanel object "general"
jContainer = jSectionPanel.getComponent(jSectionPanel.getComponentCount-1);
% If the last internal TSPanel is full, then prepare a new internal TSPanel next to it
if jContainer.getComponentCount >= 3
    % Create a new empty TSPanel and add it to the right of the last internal TSPanel
    jContainer = com.mathworks.toolstrip.components.TSPanel;
    jContainer.setPreferredSize(java.awt.Dimension(100,72));
    jSectionPanel.add(jContainer);
    jSectionPanel.repaint();
    jSectionPanel.revalidate();
end
% Create the new control with a custom tooltip and callback function
optionStrings = {'Project A', 'Project B', 'Project C'};
jCombo = com.mathworks.toolstrip.components.TSComboBox(optionStrings);
jCombo = handle(javaObjectEDT(jCombo), 'callbackproperties'));
set(jCombo, 'ActionPerformedCallback', @myCallbackFunction);
jCombo.setToolTipText('Select the requested project');
% Now add the new control to the internal TSPanel
jContainer.add(jCombo);
jContainer.repaint();
jContainer.revalidate();
</pre>
<p><center><figure style="width: 555px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Custom shortcut controls" src="https://undocumentedmatlab.com/images/Shortcuts4a.png" title="Custom shortcut controls" width="555" height="236" /><figcaption class="wp-caption-text">Custom shortcut controls</figcaption></figure></center><br />
Matlab&#8217;s internal <code>com.mathworks.toolstrip.components</code> package contains many embeddable controls, including the following (I emphasized those that I think are most useful within the context of the Shortcuts panel): <code><b>TSButton</b></code>, <code><b>TSCheckBox</b></code>, <code><b>TSComboBox</b></code>, <code>TSDropDownButton</code> (a custom combo-box component), <code>TSFormattedTextField</code>, <code>TSLabel</code>, <code><b>TSList</b></code>, <code><b>TSRadioButton</b></code>, <code>TSScrollPane</code>, <code><b>TSSlider</b></code>, <code><b>TSSpinner</b></code>, <code>TSSplitButton</code>, <code>TSTextArea</code>, <code><b>TSTextField</b></code>, and <code><b>TSToggleButton</b></code>. These controls are in most cases simple wrappers of the corresponding Java Swing controls. For example, <code>TSSpinner</code> extends the standard Swing <a target="_blank" rel="nofollow" href="https://docs.oracle.com/javase/tutorial/uiswing/components/spinner.html"><code>JSpinner</code> control</a>. In some cases, the controls are more complex: for example, the <code>TSSplitButton</code> is similar to Matlab&#8217;s <a target="_blank" href="/articles/uisplittool-uitogglesplittool"><i><b>uisplittool</b></i> control</a>.<br />
<center><figure style="width: 430px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Toolstrip controls" src="https://undocumentedmatlab.com/images/Toolstrip_components.png" title="Toolstrip controls" width="430" height="140" /><figcaption class="wp-caption-text">Toolstrip controls</figcaption></figure></center><br />
In fact, these controls can be used even outside the toolstrip, embedded directly in our Matlab figure GUI, using the <a target="_blank" href="/articles/javacomponent"><i><b>javacomponent</b></i> function</a>. For example:</p>
<pre lang='matlab'>
dataModel = javax.swing.SpinnerNumberModel(125, 15, 225, 0.5);  % defaultValue, minValue, maxValue, stepSize
jSpinner = com.mathworks.toolstrip.components.TSSpinner(dataModel);
jSpinner = handle(javaObjectEDT(jSpinner), 'CallbackProperties');
[hjSpinner, hContainer] = javacomponent(jSpinner, [10,10,60,20], gcf);
</pre>
<p>You can find additional interesting components within the <i>%matlabroot%/java/jar/toolstrip.jar</i> file, which can be opened in any zip file utility or Java IDE. In fact, whatever controls that you see Matlab uses in its Desktop toolstrip (including galleries etc.) can be replicated in custom tabs, sections and panels of our own design.<br />
Matlab Desktop&#8217;s interactive GUI only enables creating simple push-button shortcuts having string callbacks (that are <i><b>eval</b></i>&#8216;ed in run-time). Using the undocumented programmatic interface that I just showed, we can include more sophisticated controls, as well as customize those controls in ways that are impossible via the programmatic GUI: add tooltips, set non-string (function-handle) callbacks, enable/disable controls, modify icons in run-time etc.<br />
For example (intentionally showing two separate ways of setting the component properties):</p>
<pre lang='matlab'>
% Toggle-button
jTB = handle(javaObjectEDT(com.mathworks.toolstrip.components.TSToggleButton('Toggle button')), 'CallbackProperties')
jTB.setSelected(true)
jTB.setToolTipText('toggle me!')
jTB.ActionPerformedCallback = @(h,e)doSomething();
jContainer.add(jTB);
% Check-box
jCB = handle(javaObjectEDT(com.mathworks.toolstrip.components.TSCheckBox('selected !')), 'CallbackProperties');
set(jCB, 'Selected', true, 'ToolTipText','Please select me!', 'ActionPerformedCallback',{@myCallbackFunction,extraData});
jContainer.add(jCB);
</pre>
<p>(resulting in the screenshot at the top of this post)<br />
<u><b>Important note</b></u>: none of these customizations is saved to file. Therefore, they need to be redone programmatically for each separate Matlab session. You can easily do that by calling the relevant code in your <i>startup.m</i> file.<br />
If you wish me to assist with any customization of the Desktop shortcuts, or any other Matlab aspect, then <a target="_blank" href="/contact">contact me</a> for a short consultancy.<br />
Happy New Year everybody!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2">Programmatic shortcuts manipulation &#8211; part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-1" rel="bookmark" title="Programmatic shortcuts manipulation &#8211; part 1">Programmatic shortcuts manipulation &#8211; part 1 </a> <small>Matlab Desktop shortcuts can be programmatically accessed and customized. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/command-window-text-manipulation" rel="bookmark" title="Command Window text manipulation">Command Window text manipulation </a> <small>Special control characters can be used to format text output in Matlab's Command Window. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-5-icons" rel="bookmark" title="Matlab toolstrip – part 5 (icons)">Matlab toolstrip – part 5 (icons) </a> <small>Icons can be specified in various ways for toolstrip controls and the app window itself. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-toolstrip-part-4-control-customization" rel="bookmark" title="Matlab toolstrip – part 4 (control customization)">Matlab toolstrip – part 4 (control customization) </a> <small>Matlab toolstrip components (controls) can be customized in various ways, including user-defined callbacks. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2/feed</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Programmatic shortcuts manipulation &#8211; part 1</title>
		<link>https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-1?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=programmatic-shortcuts-manipulation-part-1</link>
					<comments>https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-1#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 23 Dec 2015 11:08:05 +0000</pubDate>
				<category><![CDATA[Desktop]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Icons]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Internal component]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6146</guid>

					<description><![CDATA[<p>Matlab Desktop shortcuts can be programmatically accessed and customized. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-1">Programmatic shortcuts manipulation &#8211; part 1</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2" rel="bookmark" title="Programmatic shortcuts manipulation &#8211; part 2">Programmatic shortcuts manipulation &#8211; part 2 </a> <small>Non-standard shortcut controls and customizations can easily be added to the Matlab desktop. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/command-window-text-manipulation" rel="bookmark" title="Command Window text manipulation">Command Window text manipulation </a> <small>Special control characters can be used to format text output in Matlab's Command Window. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-type-selection-components" rel="bookmark" title="Plot-type selection components">Plot-type selection components </a> <small>Several built-in components enable programmatic plot-type selection in Matlab GUI - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/r2009b-keyboard-bindings" rel="bookmark" title="R2009b keyboard bindings">R2009b keyboard bindings </a> <small>The new Matlab release R2009b includes the ability to customize keyboard bindings for the editor and Command Window. However, there are still some uses for the EditorMacro utility and its variants....</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>User-defined shortcuts can interactively be added to the Matlab Desktop to enable easy access to often-used scripts (e.g., clearing the console, running a certain program, initializing data etc.). Similarly, we can place shortcuts in the help browser to quickly access often-used pages. Unfortunately, both of these shortcut functionalities, like many other functionalities of the Matlab Desktop and related tools (Editor, Browser, Profiler etc.), have no documented programmatic access.<br />
Such programmatic access is often useful. For example, a large company for which I consult is using centralized updates to users&#8217; shortcuts, in order to manage and expose new features for all Matlab users from a central location. It is easy to send updates and manage a few users, but when your organization has dozens of Matlab users, centralized management becomes a necessity. It&#8217;s a pity that companies need to resort to external consultants and undocumented hacks to achieve this, but I&#8217;m not complaining since it keeps me occupied&#8230;<br />
<center><figure style="width: 320px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Shortcuts in Matlab R2012a and earlier" src="https://undocumentedmatlab.com/images/Shortcuts1_R2010a.png" title="Shortcuts in Matlab R2012a and earlier" width="320" height="190" /><figcaption class="wp-caption-text">Shortcuts in Matlab R2012a and earlier</figcaption></figure><br />
<figure style="width: 585px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Shortcuts in Matlab R2012b and newer" src="https://undocumentedmatlab.com/images/Shortcuts1_R2016a.png" title="Shortcuts in Matlab R2012b and newer" width="585" height="180" /><figcaption class="wp-caption-text">Shortcuts in Matlab R2012b and newer</figcaption></figure><br />
</center><br />
Today&#8217;s post will describe &#8220;regular&#8221; shortcuts &#8211; those that are simple clickable buttons. Next week I will show how we can extend this to incorporate other types of shortcut controls, as well as some advanced customizations.<br />
<span id="more-6146"></span></p>
<h3 id="xml">The <i>shortcuts.xml</i> file</h3>
<p>It turns out that the shortcults toolbar (on R2012a and earlier) or toolstrip group (on R2012b onward) is a reflection of the contents of the <i>[prefdir &#8216;\shortcuts.xml&#8217;]</i> file (depending on your version, the file might be named somewhat differently, i.e. <i>shortcuts_2.xml</i>). This file can be edited in any text editor, Matlab&#8217;s editor included. So a very easy way to programmatically affect the shortcuts is to update this file. Here is a sample of this file:</p>
<pre lang='xml'>
<?xml version="1.0" encoding="utf-8"?>
<favoritesroot version="2">
   <title>My Shortcuts</title>
   <favoritecategory>
      <name>Help Browser Favorites</name>
      <favorite>
         <label>Help Using the Desktop</label>
         <icon>Help icon</icon>
         <callback>helpview([docroot '/mapfiles/matlab_env.map'], 'matlabenvironment_desktop');</callback>
         <editable>true</editable>
      </favorite>
   </favoritecategory>
   <favorite>
      <label>CSSM</label>
      <icon>Help icon</icon>
      <callback>disp('No callback specified for this shortcut')</callback>
      <editable>true</editable>
   </favorite>
   <favorite>
      <label>UndocML</label>
      <icon>MATLAB icon</icon>
      <callback>web('undocumentedMatlab.com')</callback>
      <editable>true</editable>
   </favorite>
   <favorite>
      <label>My favorite program</label>
      <icon>C:\Yair\program\icon.gif</icon>
      <callback>cd('C:\Yair\program'); myProgram(123);</callback>
      <editable>true</editable>
   </favorite>
   ...
</favoritesroot>
</pre>
<p>The file is only loaded once during Matlab startup, so any changes made to it will only take effect after Matlab restarts.</p>
<h3 id="in-session">Updating the shortcuts in the current Matlab session</h3>
<p>We can update the shortcuts directly, in the current Matlab session, using the builtin <code>com.mathworks.mlwidgets.shortcuts.­ShortcutUtils</code> class. This class has existed largely unchanged for numerous releases (at least as far back as R2008b).<br />
For example, to add a new shortcut to the toolbar:</p>
<pre lang='matlab'>
name = 'My New Shortcut';
cbstr = 'disp(''My New Shortcut'')';  % will be eval'ed when clicked
iconfile = 'c:\path\to\icon.gif';  % default icon if it is not found
isEditable = 'true';
scUtils = com.mathworks.mlwidgets.shortcuts.ShortcutUtils;
category = scUtils.getDefaultToolbarCategoryName;
scUtils.addShortcutToBottom(name,cbstr,iconfile,category,isEditable);
</pre>
<p>The shortcut&#8217;s icon can either be set to a specific icon filepath (e.g., &#8216;C:\Yair\program\icon.jpg&#8217;), or to one of the predefined names: &#8216;Help icon&#8217;, &#8216;Standard icon&#8217;, &#8216;MATLAB icon&#8217; or &#8216;Simulink icon&#8217;. The <code>editable</code> parameter does not seem to have a visible effect that I could see.<br />
The category name can either be set to the default name using <code>scUtils.getDefaultToolbarCategoryName</code> (&#8216;Shortcuts&#8217; on English-based Matlab R2012b onward), or it can be set to any other name (e.g., &#8216;My programs&#8217;). To add a shortcut to the Help Browser (also known as a &#8220;Favorite&#8221;), simply set the category to <code>scUtils.getDefaultHelpCategoryName</code> (=&#8217;Help Browser Favorites&#8217; on English-based Matlab installations); to add the shortcut to the &#8216;Start&#8217; button, set the category to &#8216;Shortcuts&#8217;. When you use a non-default category name on R2012a and earlier, you will only see the shortcuts via Matlab&#8217;s &#8220;Start&#8221; button (as seen in the screenshot below); on R2012b onward you will see it as a new category group within the Shortcuts toolstrip (as seen in the screenshot above). For example:</p>
<pre lang='matlab'>
scUtils = com.mathworks.mlwidgets.shortcuts.ShortcutUtils;
scUtils.addShortcutToBottom('clear', 'clear; clc', 'Standard icon', 'Special commands', 'true');
</pre>
<p><center><figure style="width: 450px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Custom category in Matlab R2010a" src="https://undocumentedmatlab.com/images/Shortcuts2_R2010a.png" title="Custom category in Matlab R2010a" width="450" height="527" /><figcaption class="wp-caption-text">Custom category in Matlab R2010a</figcaption></figure></center><br />
To remove a shortcut, use the <i>removeShortcut(category,shortcutName)</i> method (note: this method does not complain if the specified shortcut does not exist):</p>
<pre lang='matlab'>scUtils.removeShortcut('Shortcuts', 'My New Shortcut');</pre>
<p>The <i>addShortcutToBottom()</i> method does not override existing shortcuts. Therefore, to ensure that we don&#8217;t add duplicate shortcuts, we must first remove the possibly-existing shortcut using <i>removeShortcut()</i> before adding it. Since <i>removeShortcut()</i> does not complain if the specific shortcut is not found, we can safely use it without having to loop over all the existing shortcuts. Alternately, we could loop over all existing category shortcuts checking their label, and adding a new shortcut only if it is not already found, as follows:</p>
<pre lang='matlab'>
scUtils = com.mathworks.mlwidgets.shortcuts.ShortcutUtils;
category = scUtils.getDefaultToolbarCategoryName;
scVector = scUtils.getShortcutsByCategory(category);
scArray = scVector.toArray;  % Java array
foundFlag = 0;
for scIdx = 1:length(scArray)
   scName = char(scArray(scIdx));
   if strcmp(scName, 'My New Shortcut')
      foundFlag = 1; break;
      % alternatively: scUtils.removeShortcut(category, scName);
   end
end
if ~foundFlag
   scUtils.addShortcutToBottom(scName, callbackString, iconString, category, 'true');
end
</pre>
<p>As noted above, we can add categories by simply specifying a new category name in the call to <i>scUtils.addShortcutToBottom()</i>. We can also add and remove categories directly, as follows (beware: when removing a category, it is removed together with all its contents):</p>
<pre lang='matlab'>
scUtils.addNewCategory('category name');
scUtils.removeShortcut('category name', []);  % entire category will be deleted
</pre>
<h3 id="FEX">Shortcut tools on the Matlab File Exchange</h3>
<p>Following <a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/2802233/programmatically-configure-matlab">my advice on StackOverflow</a> back in 2010, Richie Cotton wrapped the code snippets above in a user-friendly utility (set of independent Matlab functions) that can now be found on the <a target="_blank" rel="nofollow" href="http://www.mathworks.com/matlabcentral/fileexchange/27567-shortcut-tools">Matlab File Exchange</a> and on <a target="_blank" rel="nofollow" href="http://4dpiecharts.com/2010/08/23/a-shortcut-to-success/">his blog</a>. Richie tested his toolbox on Matlab releases as old as R2008b, but the functionality may also work on even older releases.</p>
<h3 id="panel">Shortcuts panel embedded in Matlab GUI</h3>
<p>Shortcuts are normally visible in the toolbar and the Matlab start menu (R2012a and earlier) or the Matlab Desktop&#8217;s toolstrip (R2012b onward). However, using <code>com.mathworks.mlwidgets.shortcuts.ShortcutTreePanel</code>, the schortcuts can also be displayed in any user GUI, complete with right-click context-menu:</p>
<pre lang='matlab'>
jShortcuts = com.mathworks.mlwidgets.shortcuts.ShortcutTreePanel;
[jhShortcuts,hPanel] = javacomponent(jShortcuts, [10,10,300,200], gcf);
</pre>
<p><center><figure style="width: 323px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Shortcuts panel in Matlab figure GUI" src="https://undocumentedmatlab.com/images/Shortcuts3.png" title="Shortcuts panel in Matlab figure GUI" width="323" height="296" /><figcaption class="wp-caption-text">Shortcuts panel in Matlab figure GUI</figcaption></figure></center></p>
<h3 id="followup">Stay tuned&#8230;</h3>
<p>Next week I will expand the discussion of Matlab shortcuts with the following improvements:</p>
<ol>
<li>Displaying non-standard controls as shortcuts: checkboxes, drop-downs (combo-boxes) and toggle-buttons</li>
<li>Customizing the shortcut tooltip (replacing the default tooltip that simply repeats the callback string)</li>
<li>Customizing the shortcut callback (rather than using an <i><b>eval</b></i>-ed callback string)</li>
<li>Enabling/disabling shortcuts in run-time</li>
</ol>
<p>Merry Christmas everyone!</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-1">Programmatic shortcuts manipulation &#8211; part 1</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-2" rel="bookmark" title="Programmatic shortcuts manipulation &#8211; part 2">Programmatic shortcuts manipulation &#8211; part 2 </a> <small>Non-standard shortcut controls and customizations can easily be added to the Matlab desktop. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/command-window-text-manipulation" rel="bookmark" title="Command Window text manipulation">Command Window text manipulation </a> <small>Special control characters can be used to format text output in Matlab's Command Window. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-type-selection-components" rel="bookmark" title="Plot-type selection components">Plot-type selection components </a> <small>Several built-in components enable programmatic plot-type selection in Matlab GUI - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/r2009b-keyboard-bindings" rel="bookmark" title="R2009b keyboard bindings">R2009b keyboard bindings </a> <small>The new Matlab release R2009b includes the ability to customize keyboard bindings for the editor and Command Window. However, there are still some uses for the EditorMacro utility and its variants....</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/programmatic-shortcuts-manipulation-part-1/feed</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
	</channel>
</rss>
