Context-Sensitive Help

Wednesday, August 5th, 2009

A recent CSSM thread about implementing a system-wide GUI help system got me working on a post to present Matlab’s built-in hidden/unsupported mechanism for context-sensitive help. There are many different ways in which such a system can be implemented (read that thread for some ideas), so Matlab users are by no means limited to Matlab’s built-in implementation. However, the built-in system certainly merits consideration for its simplicity and usefulness.

We start with Matlab’s cshelp function (%matlabroot%\toolbox\matlab\uitools\cshelp.m). cshelp is semi-documented, meaning that it has a help section but no doc, online help or official support. This useful function was grandfathered (made obsolete) in Matlab 7.4 (R2007a) for an unknown reason and to my knowledge without any replacement. cshelp is entirely based on m-code (no hidden internal or Java code) and is surprisingly compact and readable.

cshelp basically attaches two new properties (CSHelpMode and CSHelpData) to the specified figure (this is done using the schema.prop mechanism which will be described in a separate post), temporarily disables all active uicontrols, modifies the figure’s WindowButtonDownFcn callback and sets the mouse cursor (using setptr – another semi-documented function) to an arrow with a question mark.

Clicking any object in the figure’s main area (beneath the toolbar), causes the modified WindowButtonDownFcn callback to run whatever is stored in the figure’s HelpFcn property (string, @function_handle or {@function_handle, params, …} format). Here is a simple example taken from CSSM (thanks Jérôme):

Hfcn = 'str=get(gco,''type''); title([''Type :'' str])';
set(gcf,'HelpFcn',Hfcn);
th = 0:0.314:2*pi;
plot(th,sin(th),'r-','linewidth',4);
uicontrol('units','normalized', 'position',[.45 .02 .1 .05]);
cshelp(gcf);
set(gcf,'CSHelpMode','on');

Simple context-sensitive help system

Simple context-sensitive help system

In order to exit CSHelp mode, the figure’s CSHelpMode property must be set to ‘off’. However, remember that all the figure’s uicontrols are disabled in CSHelp mode. Therefore, the user may use one or more of the following methods (other tactics are also possible, but the ones below seem intuitive):

  • Set the figure’s KeyPressFcn callback property to catch events (e.g., <ESC> key presses) and reset the CSHelpMode property from within the callback
  • Reset the CSHelpMode property at the end of the HelpFcn callback
  • Add a CS Help entry/exit option to the figure’s Help main menu
  • Add a CS Help entry/exit button to the figure toolbar

The following code sample implements all of these suggested tactics (the code to synchronize the states of the menu item and toolbar button is not presented):

% Set the <ESC> key press to exit CSHelp mode
keyFcn = ['if strcmp(get(gcbf,''CurrentKey''),''escape''), ' ...
             'set(gcbf,''CSHelpMode'',''off''); ' ...
          'end'];
set(gcf,'keyPressFcn',keyFcn);
 
% Exit CSHelp mode at the end of the CSHelp callback
helpFcn = 'title([''Type :'' get(gco,''type'')]); set(gcbf,''CSHelpMode'',''off'');';
set(gcf,'HelpFcn',helpFcn);
 
% Add a CSHelp button to the figure toolbar
% Note: retrieve the button icon from the CSHelp cursor icon
hToolbar = findall(allchild(gcf),'flat','type','uitoolbar');
oldPtr = getptr(gcf);
ptrData = setptr('help');
set(gcf, oldPtr{:});
icon(:,:,1) = ptrData{4}/2;  % Convert into RGB TrueColor icon
icon(:,:,2) = ptrData{4}/2;
icon(:,:,3) = ptrData{4}/2;
cbFcn = 'set(gcbf,''CSHelpMode'',get(gcbo,''state''))';
csName = 'Context-sensitive help';
uitoggletool(hToolbar,'CData',icon, 'ClickedCallback',cbFcn, 'TooltipString',csName);
 
% Add a CSHelp menu option to the Help main menu
% Note: unlike other main menus, the Help menu tag is empty, so
% ^^^^  findall(gcf,'tag','figMenuHelp') is empty... Therefore,
%       we find this menu by accessing the Help/About menu item
helpAbout = findall(gcf,'tag','figMenuHelpAbout');
helpMenu = get(helpAbout,'parent');
cbFcn = ['if strcmp(get(gcbo,''Checked''),''on''), ' ...
             'set(gcbo,''Checked'',''off''); ' ...
         'else, ' ...
             'set(gcbo,''Checked'',''on''); ' ...
         'end; ' ...
         'set(gcbf,''CSHelpMode'',get(gcbo,''checked''))'];
uimenu(helpMenu,'Label',csName,'Callback',cbFcn,'Separator','on');

Figure with context-sensitive help action in the main toolbar & menu

Figure with context-sensitive help action in the main toolbar & menu

cshelp has an additional optional argument, accepting another figure handle. This handle, if specified and valid, indicates a parent figure whose CSHelpMode, HelpFcn and HelpTopicMap properties should be shared with this figure (this is done using the handle.listener mechanism which will be described in a separate post). This option is useful when creating a multi-window GUI-wide context-sensitive help system. The user may then activate context-sensitive help in figure A and select the requested context object in figure B.

cshelp would normally be coupled with Matlab’s help system for non-trivial GUI implementations. The undocumented and hidden properties HelpTopicKey (of all handles) and HelpTopicMap (of figures), enable easy tie-in to the CSHelp system. A simplified sample is presented below:

Hfcn=['helpview(get(gco,''HelpTopicKey''),''CSHelpWindow'');'...
      'set(gcbf,''CSHelpMode'',''off'');' ];
set(gcf,'HelpFcn',Hfcn);
th = 0:0.314:2*pi;
hLine = plot(th,sin(th),'r-','linewidth',4);
set(hLine,'HelpTopicKey','MyCSHelpFile.html#Line');
set(gca,  'HelpTopicKey','MyCSHelpFile.html#Axes');

cshelp is by no way limited to presenting Matlab documentation: Refer to helpview’s help section for an in-depth description of help maps and help topics. In a nutshell, helpview accepts any HTML webpage filepath (or webpage internal (#) reference), followed by optional parameter ‘CSHelpWindow’ (that indicates that the specified help page should be displayed in a stand-alone popup window rather than in the desktop’s standard Help tab), and optional extra parameters specifying the popup window’s figure handle and position. The webpage filepath parameter may be replaced by two string parameters, HelpTopicMap filepath and HelpTopicKey. Note that helpview itself is another semi-documented function.

Related posts:

  1. Adding a context-menu to a uitree uitree is an undocumented Matlab function, which does not easily enable setting a context-menu. Here's how to do it....
  2. Figure toolbar components Matlab's toolbars can be customized using a combination of undocumented Matlab and Java hacks. This article describes how to access existing toolbar icons and how to add non-button toolbar components....
  3. Customizing print setup Matlab figures print-setup can be customized to automatically prepare the figure for printing in a specific configuration...
  4. uiundo – Matlab’s undocumented undo/redo manager The built-in uiundo function provides easy yet undocumented access to Matlab's powerful undo/redo functionality. This article explains its usage....
  5. Tab panels – uitab and relatives This article describes several undocumented Matlab functions that support tab-panels...
  6. Inactive Control Tooltips & Event Chaining Inactive Matlab uicontrols cannot normally display their tooltips. This article shows how to do this with a combination of undocumented Matlab and Java hacks....

Tags: , , , , , ,

Categories: Figure window, GUI, Hidden property, Listeners, Medium risk of breaking in future versions, Semi-documented function, Stock Matlab function

This entry was posted on Wednesday, August 5th, 2009 at 11:20 am PST
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

PoorSo-soHelpfulVery helpfulExcellent! (No Ratings Yet)
Loading ... Loading ...
Bookmark and Share Print Print

10 Responses to “Context-Sensitive Help”

  1. Ashish Sadanadnan Ashish Sadanadnan says:

    Hi Yair,
    This is completely off topic but you mentioned schema.prop and so I was hoping you’d be able to help with two posts I recently made on CSSM. No one has replied to either yet.

    http://tinyurl.com/mt2ncl
    http://tinyurl.com/nls6r4

    The classes mentioned in the first post are using the schema.m mechanism.

    Thanks for your help,
    Ashish.

  2. Jason McMains Jason McMains says:

    Yair,
    Thanks again, I’ve been looking for an ability like this for a while. The only thing I will point out is that this seems to have an adverse effect with the tabbed panels. When I turn on CSHelp and try to switch tabs I get the following error:

    ??? No appropriate method or public field updateVisibility for class hg.hgjavacomponent.

    Error in ==> uitools.uitabgroup.schema>onSelChanged at 211
    children(i).updateVisibility();

    Any Ideas?
    Thanks
    Jason

  3. Andy Andy says:

    Wow, this is great. I’m not at MATLAB right now, so I can’t try this out, but it’s good to hear that helpview accepts any HTML file path, since I’ve spent about a week typing up full ‘Help’ documentation in HTML to be called via the web function. But using the web function to open my HTML pages doesn’t seem to give me the ability to easily control the help documentation (e.g. close the help window from within the GUI, open the help page to a specific section controlled by the user, etc.). It sounds like I’ll be able to do these things with cshelp and helpview.

    Thanks for the detailed response!

  4. Yair Altman Yair Altman says:

    @Jason – the updateVisibility function is an m-file (%matlabroot%\toolbox\matlab\uitools\@uitools\@uitab\updateVisibility.m) that is responsible for hiding the previous tab’s components and unhiding the new tab’s components, whenever the active tab is changed (selected). Each tab is considered a “child” of the tabgroup and automatically has the updateVisibility() function defined as a private function. It appears that CSHelp adds extra children that do not have this updateVisibility() function defined.

    I think the simplest workaround is simply to add a try-catch block around the offending line (%matlabroot%\toolbox\matlab\uitools\@uitools\@uitabgroup\schema.m line #211 [for Matlab R2008a]):

        try
            children(i).updateVisibility();
        catch
            % never mind...
        end
  5. Jason McMains Jason McMains says:

    @Yair,
    Is there a way to reroute where that callback goes to something in the current directory? I’m deploying this on a network, so if others use it, they would have to update that location as well. (plus my company blocks us from modifying the matlab root directory :( )

    Thanks Again
    Jason

  6. Yair Altman Yair Altman says:

    Jason – you can replicate the entire uitab/uitabgroup code base (m-files and their associated private folders) to a network-accessible central location, which you would then be able to modify.

    You’ll need to ensure that your Matlab path uses the new location rather than the default one – perhaps the best way to ensure this is to simply rename the files (and associate private folders) to uitab_new/uitabgroup_new, or something similar.

  7. Jason McMains Jason McMains says:

    works great, I had to do alot of modifying of the schema and other mfiles throughout to change uitab to uitab_new, but it was well worth it.

  8. Dani Dani says:

    Another help viewer is the one that pops up when I click F1 on a marked Matlab keyword – I like the design of that one the most. Is it possible to (ab)use it and have it pop up with information of my choice? I cannot find out how it is called up.

  9. Yair Altman Yair Altman says:

    Dani – yes: you can popup this HelpPopup window using the following:

    jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
    jTextArea = jDesktop.getMainFrame.getFocusOwner;
    jClassName = 'com.mathworks.mlwidgets.help.HelpPopup';
    jPosition = java.awt.Rectangle(0,0,400,300);
    helpTopic = 'surf';
    javaMethodEDT('showHelp',jClassName,jTextArea,[],jPosition,helpTopic);

    where:
    1) jPosition sets popup’s pixel size and position (X,Y,Width,Height). Remember that Java counts from the top down (opposite to Matlab) and is 0-based. Therefore, Rectangle(0,0,400,300) is a 400×300 window at the screen’s top-left corner.

    2) helpTopic is the help topic of your choice (the output of the doc function). To display arbitrary text, create an HTML doc page. A much easier alternative is to create a simple .m file that only has a main help comment with your arbitrary text, which will be presented in the popup.
    Note: on pre-R2008a releases you need to use the equivalent but more cumbersome awtinvoke function instead of javaMethodEDT.

  10. Yair Altman Yair Altman says:

    I have expanded my answer to Dani’s question into a full article ( http://undocumentedmatlab.com/blog/customizing-help-popup-contents) and companion utility (popupPanelhttp://www.mathworks.com/matlabcentral/fileexchange/25975).

    Enjoy :-)

Leave a Reply


Wrap code fragments inside <pre lang="matlab"> tags, like this:

   <pre lang="matlab">
   a = magic(3);
   sum(a)
   </pre>