home *** CD-ROM | disk | FTP | other *** search
/ io Programmo 39 / IOPROG_39.ISO / SOFT / sdkjava40.exe / data1.cab / fg_Samples / Samples / afc11 / JNotepad / src / JNoteUIEdit.java < prev    next >
Encoding:
Java Source  |  2000-05-04  |  15.4 KB  |  501 lines

  1. /*
  2.  * (C) Copyright 1995 - 1999 Microsoft Corporation.  All rights reserved.
  3.  */
  4. import com.ms.ui.*;
  5. import com.ms.ui.event.*;
  6. import com.ms.ui.resource.*;
  7. import java.awt.*;
  8. import java.io.*;
  9. import com.ms.fx.*;
  10. import java.awt.datatransfer.*;
  11. /** 
  12.  *    JNoteUIEdit
  13.  *
  14.  *    JNotepad extension of UIEdit. Supports ITextOperationTargetExt interface,
  15.  *    which allows other classes to control the JNoteUIEdit without knowing
  16.  *    anything about it. Adds a right-click context menu and support for HTML links.
  17.  *
  18.  *    @version    1.0, 7/13/97
  19.  */
  20. public class JNoteUIEdit extends UIEdit implements ITextOperationTargetExt, IConstants, IUIFocusListener{
  21.     protected ICommandFeedback commandFeedback;
  22.     protected IComponentFeature compFeature; 
  23.     protected UIContextMenu popupMenu;
  24.     protected Clipboard clipBoard;
  25.     protected UIFrame parentFrame;
  26.     /**
  27.     * Default constructor. Constructs a JNoteUIEdit.
  28.     */
  29.     public JNoteUIEdit(UIFrame parentframe){
  30.         super();
  31.         this.setAlwaysShowSelection(true);
  32.         init(parentframe);
  33.     }
  34.     /**
  35.     *    Constructs a JNoteUIEdit with the given text.
  36.     *
  37.     *    @param text Text to fill the control with.
  38.     */
  39.     public JNoteUIEdit(UIFrame parentframe, String text){
  40.         super();
  41.         this.setAlwaysShowSelection(true);
  42.         setText(text);
  43.         init(parentframe);
  44.     }
  45.     /**
  46.     *    Constructs a JNoteUIEdit with the given text.
  47.     *
  48.     *    @param text    Text to fill the control with.
  49.     */
  50.     public JNoteUIEdit(UIFrame parentframe, char[] text){
  51.         super();
  52.         this.setAlwaysShowSelection(true);
  53.         setText(new String(text));
  54.         init(parentframe);
  55.     }
  56.     // private init method. Initializes variables and sets colors and styles.
  57.     private void init(UIFrame parentframe){
  58.         parentFrame = parentframe;
  59.         commandFeedback = null;
  60.         setSingleLine(false);
  61.         clipBoard = Toolkit.getDefaultToolkit().getSystemClipboard();
  62.         loadPopupMenu();        
  63.         // set the initial word wrap. We enable/disable the appropriate menu
  64.         // items in the gotFocus() method.
  65.         setWordWrap(wwWrap);
  66.         // add a focus listener, so we can detect when we gain focus. This class
  67.         // implements IUIFocusListener, so we can set a listener on ourselves. We
  68.         // change the word wrap menu radio buttons to reflect the current word
  69.         // wrapping style.
  70.         addFocusListener(this);
  71.     }
  72.     public void setFeedbackObject(ICommandFeedback comfeedback){
  73.         commandFeedback = comfeedback;        
  74.     }
  75.     public void setCommandObject(IComponentFeature compfeature){
  76.         compFeature = compfeature;
  77.         compFeature.addTalker(popupMenu);        
  78.     }
  79.     // private method which loads the right-click popup menu.
  80.     private void loadPopupMenu(){
  81.         UIMenuList ml = new UIMenuList();
  82.         ml.add( JNotePad.loadMenuItem( ResourceIDs.IDS_UNDO, ResourceIDs.ID_EDIT_UNDO ));
  83.         ml.add( JNotePad.loadMenuItem( ResourceIDs.IDS_REDO, ResourceIDs.ID_EDIT_REDO ));
  84.         ml.add(new UILine());                    
  85.         ml.add( JNotePad.loadMenuItem( ResourceIDs.IDS_CUT,  ResourceIDs.ID_EDIT_CUT ));
  86.         ml.add( JNotePad.loadMenuItem( ResourceIDs.IDS_COPY, ResourceIDs.ID_EDIT_COPY ));
  87.         ml.add( JNotePad.loadMenuItem( ResourceIDs.IDS_PASTE, ResourceIDs.ID_EDIT_PASTE ));
  88.         ml.add( JNotePad.loadMenuItem( ResourceIDs.IDS_DELETE, ResourceIDs.ID_EDIT_DELETE ));
  89.         ml.add(new UILine());
  90.         ml.add( JNotePad.loadMenuItem( ResourceIDs.IDS_FONT, ResourceIDs.ID_FONT ));
  91.         ml.add( JNotePad.loadMenuItem( ResourceIDs.IDS_TEXTCOLOR, ResourceIDs.ID_TEXTCOLOR ));
  92.         ml.add( JNotePad.loadMenuItem( ResourceIDs.IDS_BGCOLOR, ResourceIDs.ID_BGCOLOR ));
  93.         ml.add(new UILine());
  94.         ml.add( JNotePad.loadMenuItem( ResourceIDs.IDS_LAUNCHSELLINK, ResourceIDs.ID_LAUNCH ));
  95.         popupMenu = new JNoteContextMenu(this, ml);
  96.     }
  97.     protected void enableCommand(String command, boolean on){
  98.         if (commandFeedback != null)
  99.             commandFeedback.enableCommand(command, on);
  100.     }
  101.     protected void setChecked(String command, boolean on){
  102.         if (commandFeedback != null)
  103.             commandFeedback.setChecked(command, on);
  104.     }
  105.     public boolean handleEvent(Event e){
  106.         // check for right button click
  107.         if ((e.id == Event.MOUSE_UP) && (e.modifiers == Event.META_MASK)){
  108.             //Dimension d = TabFileViewer.getSize();
  109.             Point pt = parentFrame.getLocation();
  110.             Point edit = getLocation(parentFrame);
  111.             popupMenu.launchAt(e.x+pt.x+edit.x, e.y+pt.y+edit.y, parentFrame);                        
  112.             
  113.             return true;
  114.         }
  115.         else if ((e.id == Event.MOUSE_DOWN) && (e.modifiers == Event.META_MASK))
  116.             // do nothing. We swallow this event and don't give it to the superclass
  117.             // to avoid losing focus for the context menu
  118.             return true;
  119.         else
  120.             return super.handleEvent(e);
  121.     }
  122.     /**
  123.     *    Sets the word wrapping for this control. Makes sure that the    
  124.     *    word wrap radio buttons are properly updated.
  125.     *
  126.     *    @param    iStyle    Word wrap style. See the AFC UIEdit class for more information.
  127.     *    @returns    true
  128.     */
  129.     protected boolean setWordWrapStyle(int iStyle){
  130.         boolean b1 = false;
  131.         boolean b2 = false;
  132.         boolean b3 = false;
  133.         // decide which radio buttons should be selected and which not
  134.         if (iStyle == wwNone)
  135.         {
  136.             b2=b3=false;
  137.             b1=true;
  138.         }
  139.         else if (iStyle == wwWrap)
  140.         {
  141.             b1=b3=false;
  142.             b2=true;
  143.         }
  144.         else if (iStyle == wwKeepWordIntact)
  145.         {
  146.             b1=b2=false;
  147.             b3=true;
  148.         }
  149.         // set the word wrap menu radio buttons accordingly
  150.         setChecked(JNotePad.loadString(ResourceIDs.IDS_NOWORDWRAP), b1);
  151.         setChecked(JNotePad.loadString(ResourceIDs.IDS_WORDWRAP), b2);
  152.         setChecked(JNotePad.loadString(ResourceIDs.IDS_WORDWRAP2), b3);
  153.         setWordWrap(iStyle);
  154.         invalidate();
  155.         return true;
  156.     }
  157.     public boolean otherCommand(String command, UIActionEvent evt){
  158.         boolean ret = false;
  159.         
  160.         IUIComponent comp=evt.getActionItem();
  161.         switch( comp.getID() ){
  162.         case ResourceIDs.ID_LAUNCH:
  163.             return launchApp();
  164.         case ResourceIDs.ID_NOWORDWRAP:
  165.             return setWordWrapStyle(wwNone);
  166.         case ResourceIDs.ID_WORDWRAP:
  167.             return setWordWrapStyle(wwWrap);
  168.         case ResourceIDs.ID_WORDWRAP2:
  169.             return setWordWrapStyle(wwKeepWordIntact);
  170.         }
  171.         if (evt.getActionItem() instanceof UIStatic){
  172.             UIStatic s = (UIStatic)evt.getActionItem();                    
  173.             Object bgcolor = s.getBackground();
  174.             Object fgcolor = s.getForeground();
  175.             if (bgcolor instanceof FxColor){
  176.                 if (s.getName().startsWith("Custom"))
  177.                     changeBackColor();
  178.                 else
  179.                     setBackground((FxColor)bgcolor);
  180.                 commandFeedback.notifyColorChange(this, getBackColor(), 
  181.                         commandFeedback.COLORCHANGE_BACKGROUND);
  182.             }
  183.             else if (fgcolor instanceof FxColor){
  184.                 if (s.getName().startsWith("Custom"))
  185.                     changeTextColor();
  186.                 else
  187.                     setForeground((FxColor)fgcolor);
  188.                 commandFeedback.notifyColorChange(this, getTextColor(), 
  189.                         commandFeedback.COLORCHANGE_FOREGROUND);
  190.             }
  191.             ret = true;
  192.         }
  193.         return ret;
  194.     }
  195.     /**
  196.     *    Tries to run the selected text as a file or HTML link.    
  197.     *
  198.     *    @returns    true
  199.     */
  200.     protected boolean launchApp(){
  201.         String linkText = getSelectedText();
  202.         if (linkText.length() == 0){
  203.             int iIndex = getCaretIndex();
  204.             linkText = getWord(iIndex);
  205.             if (linkText == null){
  206.                 // file could not be run
  207.                 UIMessageBox box = new UIMessageBox(new UIFrame(), 
  208.                     JNotePad.loadString(ResourceIDs.IDS_MSGLAUNCHERR),
  209.                     JNotePad.loadString(ResourceIDs.IDS_MSGNOTRUNNABLE),
  210.                     box.STOP, UIButtonBar.OK);
  211.                 box.doModal();
  212.                 return true;
  213.             }
  214.         }
  215.         // load in the text which links the two strings, depending on whether you're
  216.         // launching an HTML link or a file.
  217.         int linkID = (linkText.startsWith("http://") ? ResourceIDs.IDS_MSGLINKTO : ResourceIDs.IDS_MSGLAUNCH);
  218.         String linkOrFileText = JNotePad.loadString(linkID);
  219.         File fileToRun = new File(linkText);
  220.         if (fileToRun.exists() || linkID == ResourceIDs.IDS_MSGLINKTO){
  221.             // confirm that user wants to launch this
  222.             UIMessageBox msgbox = new UIMessageBox(parentFrame, 
  223.                 JNotePad.loadString(ResourceIDs.IDS_MSGLAUNCH),
  224.                 JNotePad.loadString(ResourceIDs.IDS_MSGLAUNCHANNOC)+linkOrFileText+linkText+
  225.                 JNotePad.loadString(ResourceIDs.IDS_MSGOKCANCEL), 
  226.                 UIMessageBox.INFORMATION, UIButtonBar.OKCANCEL);
  227.             UIButton ret = (UIButton)msgbox.doModal();
  228.             if (ret.getID() != UIButtonBar.ID_OK)
  229.                 return true;
  230.             ExeRunnerThread exerunner = new ExeRunnerThread(linkText);
  231.             exerunner.start();
  232.         }else{
  233.             // file could not be run
  234.             UIMessageBox box = new UIMessageBox(new UIFrame(), 
  235.                 JNotePad.loadString(ResourceIDs.IDS_MSGLAUNCHERR),
  236.                 JNotePad.loadString(ResourceIDs.IDS_MSGNOTRUNNABLE),
  237.                 box.STOP, UIButtonBar.OK);
  238.             box.doModal();
  239.         }
  240.         return true;
  241.     }
  242.     // returns the word at the given character index.
  243.     protected String getWord(int iIndex){
  244.         String editText = getText();
  245.         // if we're clicking on valid text
  246.         if ((iIndex >= 0) && (iIndex < editText.length())){
  247.             // try to grab the word. 
  248.             // getWordEdge definition:
  249.             //        getWordEdge(int iPos, boolean pleaseMoveLeft, 
  250.             //                    boolean givePrevious)
  251.             // the ifs test for spaces - if we click right before
  252.             //        or after a space, we have to make sure we
  253.             //        grab the edge of the current word and not the
  254.             //        edge of the next (or prev) word.
  255.             int iWordLeftEdge = 0;
  256.             int iWordRightEdge = 0;
  257.             if ((iIndex > 0) && (editText.charAt(iIndex-1) == ' '))
  258.                 iWordLeftEdge = getWordEdge(iIndex, true, false);
  259.             else
  260.                 iWordLeftEdge = getWordEdge(iIndex, true, true);
  261.             if ((iIndex < editText.length()-1) && (editText.charAt(iIndex) == ' '))
  262.                 iWordRightEdge = getWordEdge(iIndex+1, false, true);
  263.             else
  264.                 iWordRightEdge = getWordEdge(iIndex, false, false);
  265.             return editText.substring(iWordLeftEdge, iWordRightEdge-1);
  266.         }
  267.         return null;
  268.     }
  269.     // protected method. Copies given text to clipboard.
  270.     protected void copyToClipboard(String text){
  271.         StringSelection cbdata = new StringSelection(text);
  272.         clipBoard.setContents(cbdata, cbdata);
  273.     }
  274.     protected String getClipboardContents(){
  275.         Transferable cbdata = clipBoard.getContents(this);
  276.         if (cbdata != null){
  277.             try {
  278.                 return (String)cbdata.getTransferData(DataFlavor.stringFlavor);                            
  279.             }
  280.             catch (Exception e){
  281.                 System.out.println("Data not string flavor");
  282.             }                        
  283.         }
  284.         
  285.         return null;
  286.     }
  287.     //
  288.     // ITextOperation methods
  289.     //
  290.     /**
  291.     *    IFileOperationTarget method. Called when the user wants to perform a cut
  292.     *    operation. Does the usual thing.
  293.     */
  294.     public void cut(){            
  295.         int iSelStart = getSelectionStart();
  296.         int iSelEnd = getSelectionEnd();
  297.         if (iSelStart != iSelEnd){
  298.             String selText = getSelectedText();
  299.             copyToClipboard(selText);
  300.             remove(iSelStart, iSelEnd - iSelStart);
  301.             setSelection(iSelStart, iSelStart);
  302.             moveTheCaret(iSelStart);
  303.             requestFocus();
  304.         }
  305.     }
  306.     /**
  307.     *    IFileOperationTarget method. Called when the user wants to do a copy
  308.     *    operation. Does the usual thing.
  309.     */
  310.     public void copy(){            
  311.         if (getSelectionStart() != getSelectionEnd())
  312.             copyToClipboard(getSelectedText());
  313.     }
  314.     /**
  315.     *    IFileOperationTarget method. Called when the user wants to do a paste
  316.     *    operation. Does the usual thing.
  317.     */
  318.     public void paste(){
  319.         String data = getClipboardContents();
  320.         paste(data);                        
  321.     }
  322.     /**
  323.     *    IFileOperationTarget method. Called when the user wants to change the
  324.     *    font. Pops up a AwtUIFontDialog and does the usual thing.
  325.     */    
  326.     public void changeFont(){
  327.         UIFontDialog dialog = new UIFontDialog(parentFrame);
  328.         dialog.show();
  329.         FxFont font = dialog.getFxFont();
  330.         if (font != null)
  331.             setFont(font);
  332.     }
  333.     /**
  334.     *    IFileOperationTarget method. Called when the user wants to change the
  335.     *    font to a certain font. Does the usual thing.
  336.     *
  337.     *    @param font    Font to change to
  338.     */
  339.     public void changeFont(FxFont font){
  340.         setFont(font);
  341.     }
  342.     /**
  343.     *    IFileOperationTarget method. Called when the user wants to change the
  344.     *    text color. Pops up a AwtUIColorDialog and does the usual thing.
  345.     */    
  346.     public void changeTextColor(){
  347.         UIColorDialog dialog = new UIColorDialog(parentFrame);            
  348.         dialog.show();
  349.         FxColor c = dialog.getFxColor();
  350.         if (c != null){
  351.             setForeground(c);
  352.             repaint();
  353.         }                
  354.     }
  355.     public void changeBackColor(){
  356.         UIColorDialog dialog = new UIColorDialog(parentFrame);
  357.         dialog.show();
  358.         FxColor c = dialog.getFxColor();
  359.         if (c != null){
  360.             setBackground(c);
  361.             repaint();
  362.         }                
  363.     }
  364.     public FxColor getTextColor(){
  365.         Color c=getForeground();
  366.         if(c!=null)
  367.             return FxColor.getExtendedColor(c);
  368.         return null;
  369.     }
  370.     public FxColor getBackColor(){
  371.         Color c=getBackground();
  372.         if(c!=null)
  373.             return FxColor.getExtendedColor(c);
  374.         return null;
  375.     }
  376.     public void setTextColor(FxColor color){
  377.         setForeground((Color)color);            
  378.     }
  379.     public void setBackColor(FxColor color){
  380.         setBackground((Color)color);            
  381.     }
  382.     public void selectAll(){
  383.         setSelection(0, getText().length());
  384.     }
  385.     //
  386.     // ITextOperationTargetExt functions
  387.     //
  388.     public void paste(String text){
  389.         int iSelStart = getSelectionStart();
  390.         int iSelEnd = getSelectionEnd();
  391.         // if no selection, insert at current caret position
  392.         // if selection, paste over hilited text
  393.         if (iSelStart == iSelEnd){
  394.             iSelStart = iSelEnd = getCaretIndex();
  395.         }
  396.         String str = getText();
  397.         str = str.substring(0, iSelStart) + text + str.substring(iSelEnd);
  398.         setText(str);
  399.         moveTheCaret(iSelStart + text.length());
  400.     }
  401.     /**
  402.     *    Inserts text at the given character position in the control.
  403.     *    If iPos < 0, insert at caret position.
  404.     *
  405.     *    @param text String to insert
  406.     *    @parem iPos Position to insert at. If < 0, insert at caret.
  407.     */
  408.     public void insertText(String text, int iPos){
  409.         if (iPos < 0)
  410.             insert(text, getCurrIndex());
  411.         else
  412.             insert(text, iPos);
  413.     }
  414.     public void moveCaret(int idx){
  415.         setCurrIndex(idx);
  416.     }
  417.     public void appendText(String text){
  418.         append(text);
  419.     }
  420.     public void delete(){    
  421.         int iSelStart = getSelectionStart();
  422.         int iSelEnd = getSelectionEnd();
  423.         if (iSelStart != iSelEnd){
  424.             remove(iSelStart, iSelEnd - iSelStart);
  425.             setSelection(iSelStart, iSelStart);
  426.             moveTheCaret(iSelStart);
  427.             requestFocus();
  428.         }
  429.     }
  430.     public int getCaretIndex(){
  431.         return getCurrIndex();
  432.     }
  433.     public void moveTheCaret(int idx){
  434.         setCurrIndex(idx);
  435.     }
  436.     public void setText(String text){
  437.         setValueText(text);
  438.     }
  439.     public String getText(){
  440.         return getValueText();
  441.     }
  442.     // part of IUIFocusListener interface.
  443.     /**
  444.     *    Called when this control gets focus, via the IUIFocusListener interface.    
  445.     *    Sets the current word wrap style.
  446.     *
  447.     *    @param    evt    The UIFocusEvent we are handling
  448.     */
  449.     public void focusGained(UIFocusEvent evt){
  450.         setWordWrapStyle(getWordWrap());
  451.     }
  452.     /**
  453.     *    Called when this control loses focus, via the IUIFocusListener interface.    
  454.     *    Does nothing.
  455.     *
  456.     *    @param    evt    The UIFocusEvent we are handling
  457.     */
  458.     public void focusLost(UIFocusEvent evt){
  459.         // we don't do anything if focus is lost
  460.     }
  461. }
  462. /**
  463. *    Thread to start processes. We run external programs using a thread
  464. *    so we can continue to use the app while the program loads.
  465. *    Used by JNoteUIEdit.
  466. *
  467. *    @version    1.0, 8/2/97
  468. *    @see        JNoteUIEdit
  469. */
  470. class ExeRunnerThread extends Thread{
  471. /**
  472.  *    Name of program to run.
  473.  */
  474.     String exeFile;
  475.     /**
  476.     *    Creates a new ExeRunnerThread.
  477.     *    
  478.     *    @param    exeFile    Name of program to run.
  479.     */
  480.     public ExeRunnerThread(String exefile){
  481.         super();
  482.         exeFile = exefile;
  483.     }
  484.     /**
  485.     *    Called when thread is started. Overrides Thread.start(). Runs
  486.     *    the program using Runtime.exec() and then quits.
  487.     */
  488.     public void start(){                        
  489.         try{
  490.             Runtime.getRuntime().exec(exeFile);
  491.         }
  492.         catch (IOException e1){
  493.             // error trying to run file
  494.             UIMessageBox mb = new UIMessageBox(new UIFrame(), 
  495.                 JNotePad.loadString(ResourceIDs.IDS_MSGFILERUNERR),
  496.                 JNotePad.loadString(ResourceIDs.IDS_MSGRUNERROR)+exeFile,
  497.                 UIMessageBox.INFORMATION, UIButtonBar.OK);
  498.             mb.doModal();
  499.         }
  500.     }
  501. }