/**
  * Creates a new instance of this class. Automatically starts listening to corresponding key and
  * modify events coming from the given <var>editor</var>.
  *
  * @param editor the text field to which the Undo-Redo functionality should be added
  */
 public UndoRedoStyledText(StyledText editor) {
   editor.addExtendedModifyListener(this);
   editor.addKeyListener(this);
   onMac = System.getProperty("os.name").startsWith("Mac OS X");
   this.editor = editor;
   stack = new UndoRedoStack<ExtendedModifyEvent>();
 }
Пример #2
0
 private void addListeners(bento.language.bentocomp.resource.bento.ui.BentoEditor editor) {
   UpdateHighlightingListener hl = new UpdateHighlightingListener();
   textWidget.addKeyListener(hl);
   textWidget.addVerifyListener(hl);
   textWidget.addMouseListener(hl);
   editor.addBackgroundParsingListener(hl);
 }
Пример #3
0
  /**
   * Installs this highlighter into the specified StyledText object. Client can manually call
   * detach() method, then wants to destroy this object.
   */
  public void attach(StyledText parent) {
    detach();

    text = parent;
    text.addDisposeListener(ml);
    text.addLineStyleListener(ml);
    text.addLineBackgroundListener(ml);
    text.addPaintListener(ml);
    text.addVerifyListener(ml);
    text.addExtendedModifyListener(ml);
    text.addControlListener(ml);
    text.addKeyListener(ml);
    text.addTraverseListener(ml);
    text.addMouseListener(ml);
    text.addSelectionListener(ml);
    text.getContent().addTextChangeListener(ml);
    ScrollBar sb = text.getVerticalBar();
    if (sb != null) sb.addSelectionListener(ml);
    updateViewport();

    new Thread() {
      public void run() {
        // setPriority(Thread.NORM_PRIORITY-1);
        while (true) {
          try {
            sleep(300);
          } catch (InterruptedException e) {
          }
          if (baseEditor == null || text == null) break;
          if (backParserDelay) {
            backParserDelay = false;
            try {
              sleep(1500);
            } catch (InterruptedException e) {
            }
            continue;
          }
          ;
          Display.getDefault()
              .syncExec(
                  new Runnable() {
                    public void run() {
                      if (baseEditor == null || text == null) return;
                      if (text.isDisposed()) return;
                      // System.out.println(System.currentTimeMillis());
                      baseEditor.idleJob(80);
                      // redrawFrom(text.getLineAtOffset(text.getCaretOffset()));
                    }
                  });
        }
        ;
      };
    }.start();
  }
Пример #4
0
 public void show(String title, final String message, List<StyleRange> srList) {
   final Shell dialog = new Shell(Display.getDefault(), SWT.DIALOG_TRIM | SWT.RESIZE);
   UIUtil.setDialogDefaultFunctions(dialog);
   dialog.setText(title);
   dialog.setLayout(new GridLayout(1, true));
   final StyledText text =
       new StyledText(dialog, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL);
   GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
   gd.widthHint = 400;
   gd.heightHint = 300;
   text.setLayoutData(gd);
   text.setText(message);
   text.addKeyListener(
       new KeyAdapter() {
         public void keyPressed(KeyEvent e) {
           if (e.stateMask == SWT.CTRL) {
             if (e.keyCode == 'a' || e.keyCode == 'A') {
               text.selectAll();
             }
           }
         }
       });
   if (srList != null && srList.size() > 0) {
     text.setStyleRanges(srList.toArray(new StyleRange[srList.size()]));
   }
   Button btn = new Button(dialog, SWT.PUSH);
   gd = new GridData(SWT.RIGHT, SWT.FILL, false, false);
   gd.widthHint = 100;
   btn.setLayoutData(gd);
   btn.setText("&Close");
   btn.addSelectionListener(
       new SelectionAdapter() {
         public void widgetSelected(SelectionEvent e) {
           dialog.close();
         }
       });
   dialog.pack();
   dialog.open();
 }
  /** DOC amaumont Comment method "addListeners". */
  private void addListeners() {
    styledText.addFocusListener(
        new FocusListener() {

          public void focusGained(FocusEvent e) {
            refreshProposalSize();
          }

          public void focusLost(FocusEvent e) {}
        });

    styledText.addControlListener(
        new ControlListener() {

          public void controlMoved(ControlEvent e) {}

          public void controlResized(ControlEvent e) {
            refreshProposalSize();
          }
        });

    styledText.addExtendedModifyListener(
        new ExtendedModifyListener() {

          public void modifyText(ExtendedModifyEvent event) {
            updateCellExpression();
            // System.out.println("ExtendedModifyListener modify text");

          }
        });
    styledText
        .getContent()
        .addTextChangeListener(
            new TextChangeListener() {

              public void textChanged(TextChangedEvent event) {
                highlightLineOfCursorPosition(styledText.getSelection());
              }

              public void textChanging(TextChangingEvent event) {
                // System.out.println("textChanging");
              }

              public void textSet(TextChangedEvent event) {
                // System.out.println("textSet");
              }
            });
    styledText.addModifyListener(
        new ModifyListener() {

          public void modifyText(ModifyEvent e) {
            highlightLineOfCursorPosition(styledText.getSelection());
          }
        });

    styledText.addKeyListener(
        new KeyListener() {

          public void keyPressed(KeyEvent e) {
            highlightLineOfCursorPosition(styledText.getSelection());
          }

          public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub

          }
        });

    styledText.addVerifyKeyListener(
        new VerifyKeyListener() {

          public void verifyKey(VerifyEvent verifyEvent) {
            if (verifyEvent.character == '\r'
                && contentProposalAdapter != null
                && contentProposalAdapter.isProposalOpened()) {
              verifyEvent.doit = false;
            } else {
              verifyEvent.doit = true;
            }
          }
        });

    styledText.addMouseListener(
        new MouseListener() {

          public void mouseDoubleClick(MouseEvent e) {
            highlightLineOfCursorPosition(styledText.getSelection());
          }

          public void mouseDown(MouseEvent e) {
            highlightLineOfCursorPosition(styledText.getSelection());
          }

          public void mouseUp(MouseEvent e) {}
        });
  }
  /**
   * Creates a source viewer information control with the given shell as parent. The given shell
   * styles are applied to the created shell. The given styles are applied to the created styled
   * text widget. The text widget will be initialized with the given font. The status field will
   * contain the given text or be hidden.
   *
   * @param parent the parent shell
   * @param isResizable <code>true</code> if resizable
   * @param symbolicFontName the symbolic font name
   * @param statusFieldText the text to be used in the optional status field or <code>null</code> if
   *     the status field should be hidden
   */
  public SourceViewerInformationControl(
      Shell parent, boolean isResizable, String symbolicFontName, String statusFieldText) {
    GridLayout layout;
    GridData gd;

    int shellStyle = SWT.TOOL | SWT.ON_TOP | (isResizable ? SWT.RESIZE : 0);
    int textStyle = isResizable ? SWT.V_SCROLL | SWT.H_SCROLL : SWT.NONE;

    fShell = new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle);
    Display display = fShell.getDisplay();

    Composite composite = fShell;
    layout = new GridLayout(1, false);
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    composite.setLayout(layout);
    gd = new GridData(GridData.FILL_HORIZONTAL);
    composite.setLayoutData(gd);

    if (statusFieldText != null) {
      composite = new Composite(composite, SWT.NONE);
      layout = new GridLayout(1, false);
      layout.marginHeight = 0;
      layout.marginWidth = 0;
      composite.setLayout(layout);
      gd = new GridData(GridData.FILL_BOTH);
      composite.setLayoutData(gd);
      composite.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
      composite.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
    }

    // Source viewer
    fViewer = new SourceViewer(composite, null, textStyle);
    fViewer.configure(new SourceViewerConfiguration());
    fViewer.setEditable(false);

    fText = fViewer.getTextWidget();
    gd = new GridData(GridData.BEGINNING | GridData.FILL_BOTH);
    fText.setLayoutData(gd);
    fText.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND));
    fText.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND));
    fSymbolicFontName = symbolicFontName;
    fTextFont = JFaceResources.getFont(symbolicFontName);
    fText.setFont(fTextFont);

    fText.addKeyListener(
        new KeyListener() {

          public void keyPressed(KeyEvent e) {
            if (e.character == 0x1B) // ESC
            fShell.dispose();
          }

          public void keyReleased(KeyEvent e) {}
        });

    // Status field
    if (statusFieldText != null) {

      // Horizontal separator line
      fSeparator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT);
      fSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

      // Status field label
      fStatusField = new Label(composite, SWT.RIGHT);
      fStatusField.setText(statusFieldText);
      Font font = fStatusField.getFont();
      FontData[] fontDatas = font.getFontData();
      for (int i = 0; i < fontDatas.length; i++)
        fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10);
      fStatusTextFont = new Font(fStatusField.getDisplay(), fontDatas);
      fStatusField.setFont(fStatusTextFont);
      GridData gd2 =
          new GridData(
              GridData.FILL_VERTICAL
                  | GridData.FILL_HORIZONTAL
                  | GridData.HORIZONTAL_ALIGN_BEGINNING
                  | GridData.VERTICAL_ALIGN_BEGINNING);
      fStatusField.setLayoutData(gd2);

      fStatusTextForegroundColor =
          new Color(
              fStatusField.getDisplay(),
              blend(
                  display.getSystemColor(SWT.COLOR_INFO_BACKGROUND).getRGB(),
                  display.getSystemColor(SWT.COLOR_INFO_FOREGROUND).getRGB(),
                  0.56f));
      fStatusField.setForeground(fStatusTextForegroundColor);

      fStatusField.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
    }

    addDisposeListener(this);
  }
Пример #7
0
  private void initialize(final Composite inContainer) {
    textWidget =
        new StyledText(
            inContainer,
            SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL);

    content = new TextContent();
    textWidget.setContent(content);
    textWidget.setLayout(new GridLayout(1, true));
    textWidget.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    textWidget.addExtendedModifyListener(
        new ExtendedModifyListener() {
          @Override
          public void modifyText(final ExtendedModifyEvent inEvent) {
            if (textWidget.getCharCount() == 0) return;
            final StyleRange lRange =
                textWidget.getStyleRangeAtOffset(Math.max(inEvent.start - 1, 0));
            if (lRange != null) {
              final StyleRange lNew =
                  new StyleRange(
                      lRange.start,
                      lRange.length + inEvent.length,
                      lRange.foreground,
                      lRange.background,
                      lRange.fontStyle);
              textWidget.replaceStyleRanges(lNew.start, lNew.length, new StyleRange[] {lNew});
            }
            final int lEndPos = inEvent.start + inEvent.length;
            if (lEndPos - textWidget.getOffsetAtLine(textWidget.getLineAtOffset(lEndPos)) == 0) {
              final int lLineIndex = textWidget.getLineAtOffset(inEvent.start);
              if (lLineIndex + 2 > textWidget.getLineCount()) return;
              // a new line has been entered, therefore, check whether we
              // have to continue a list
              final Bullet lBullet = textWidget.getLineBullet(lLineIndex);
              textWidget.setLineBullet(lLineIndex + 1, 1, lBullet);
            }
          }
        });
    textWidget.addPaintObjectListener(Styles.getPaintObjectListener(textWidget));
    textWidget.addVerifyKeyListener(
        new VerifyKeyListener() {
          @Override
          public void verifyKey(final VerifyEvent inEvent) {
            if (inEvent.keyCode == 9) { // TAB keyCode
              final StyledText lWidget = (StyledText) inEvent.getSource();
              if (consumeTabKey(lWidget)) {
                inEvent.doit = false;
                final TextStyler lStyler = new TextStyler(lWidget);
                if ((inEvent.stateMask & SWT.SHIFT) != 0) {
                  lStyler.dedentLines();
                  provider.notifyPositionChange(lWidget.getCaretOffset());
                } else {
                  lStyler.indentLines();
                }
              }
            }
          }
        });
    textWidget.addTraverseListener(
        new TraverseListener() {
          @Override
          public void keyTraversed(final TraverseEvent inEvent) {
            if (inEvent.detail == SWT.TRAVERSE_TAB_PREVIOUS
                && consumeTabKey((StyledText) inEvent.getSource())) {
              inEvent.doit = false;
            }
          }
        });
    textWidget.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseDown(final MouseEvent inEvent) {
            provider.notifyPositionChange(textWidget.getCaretOffset());
          }
        });
    textWidget.addKeyListener(
        new KeyAdapter() {
          @Override
          public void keyReleased(final KeyEvent inEvent) {
            provider.notifyPositionChange(textWidget.getCaretOffset());
          }
        });
    provider = ContextInjectionFactory.make(TextStyleProvider.class, context);
    provider.setWidget(textWidget);

    // font handling
    if (fontSizeToUse != 0) {
      trackFontSize(fontSizeToUse);
    }

    disposed = false;
  }
Пример #8
0
  /**
   * Creates a new <code>BZStyledText</code> for parentShell <code>parentShell</code>.
   *
   * @param parentShell parentShell of the new instance (cannot be null)
   */
  public BZStyledText(Shell parentShell) {
    this.parentShell = parentShell;

    //   version from jar manifest
    String version = getClass().getPackage().getImplementationVersion();

    //   version from build file
    if (version == null) version = System.getProperty("braillezephyr.version");

    //   no version
    if (version == null) {
      logWriter.println("WARNING:  unable to determine version, using 0.0");
      version = "0.0";
    }

    versionString = version;
    String[] versionStrings = versionString.split("\\.");
    versionMajor = Integer.parseInt(versionStrings[0]);
    if (versionStrings.length > 1) versionMinor = Integer.parseInt(versionStrings[1]);
    else versionMinor = 0;
    if (versionStrings.length > 2) versionPatch = Integer.parseInt(versionStrings[2]);
    else versionPatch = 0;

    color = parentShell.getDisplay().getSystemColor(SWT.COLOR_BLACK);

    composite = new Composite(parentShell, 0);
    composite.setLayout(new GridLayout(2, true));

    //   load fonts
    loadFont("BrailleZephyr_6.otf");
    loadFont("BrailleZephyr_6b.otf");
    loadFont("BrailleZephyr_6s.otf");
    loadFont("BrailleZephyr_6sb.otf");
    loadFont("BrailleZephyr_8.otf");
    loadFont("BrailleZephyr_8b.otf");
    loadFont("BrailleZephyr_8s.otf");
    loadFont("BrailleZephyr_8sb.otf");
    loadFont("BrailleZephyr_8w.otf");
    loadFont("BrailleZephyr_8wb.otf");
    loadFont("BrailleZephyr_8ws.otf");
    loadFont("BrailleZephyr_8wsb.otf");

    //   load line margin bell
    try {
      InputStream inputStreamBellMargin =
          new BufferedInputStream(getClass().getResourceAsStream("/sounds/line_margin_bell.wav"));
      AudioInputStream audioInputStreamMargin =
          AudioSystem.getAudioInputStream(inputStreamBellMargin);
      DataLine.Info dataLineInfoMargin =
          new DataLine.Info(Clip.class, audioInputStreamMargin.getFormat());
      lineMarginClip = (Clip) AudioSystem.getLine(dataLineInfoMargin);
      lineMarginClip.open(audioInputStreamMargin);
    } catch (IOException exception) {
      logWriter.println(
          "ERROR:  Unable to read default line margin bell file:  " + exception.getMessage());
      lineMarginClip = null;
    } catch (UnsupportedAudioFileException exception) {
      logWriter.println(
          "ERROR:  Sound file unsupported for default line margin bell:  "
              + exception.getMessage());
      lineMarginClip = null;
    } catch (LineUnavailableException exception) {
      logWriter.println(
          "ERROR:  Line unavailable for default line margin bell:  " + exception.getMessage());
      lineMarginClip = null;
    }

    //   load page margin bell
    try {
      InputStream inputStreamBellPage =
          new BufferedInputStream(getClass().getResourceAsStream("/sounds/page_margin_bell.wav"));
      AudioInputStream audioInputStreamPage = AudioSystem.getAudioInputStream(inputStreamBellPage);
      DataLine.Info dataLineInfoPage =
          new DataLine.Info(Clip.class, audioInputStreamPage.getFormat());
      pageMarginClip = (Clip) AudioSystem.getLine(dataLineInfoPage);
      pageMarginClip.open(audioInputStreamPage);
    } catch (IOException exception) {
      logWriter.println(
          "ERROR:  Unable to read default page margin bell file:  " + exception.getMessage());
      pageMarginClip = null;
    } catch (UnsupportedAudioFileException exception) {
      logWriter.println(
          "ERROR:  Sound file unsupported for default page margin bell:  "
              + exception.getMessage());
      pageMarginClip = null;
    } catch (LineUnavailableException exception) {
      logWriter.println(
          "ERROR:  Line unavailable for default page margin bell:  " + exception.getMessage());
      pageMarginClip = null;
    }

    //   load line end bell
    try {
      InputStream inputStreamBellPage =
          new BufferedInputStream(getClass().getResourceAsStream("/sounds/line_end_bell.wav"));
      AudioInputStream audioInputStreamPage = AudioSystem.getAudioInputStream(inputStreamBellPage);
      DataLine.Info dataLineInfoPage =
          new DataLine.Info(Clip.class, audioInputStreamPage.getFormat());
      lineEndClip = (Clip) AudioSystem.getLine(dataLineInfoPage);
      lineEndClip.open(audioInputStreamPage);
    } catch (IOException exception) {
      logWriter.println(
          "ERROR:  Unable to read default line end bell file:  " + exception.getMessage());
      lineEndClip = null;
    } catch (UnsupportedAudioFileException exception) {
      logWriter.println(
          "ERROR:  Sound file unsupported for default line end bell:  " + exception.getMessage());
      lineEndClip = null;
    } catch (LineUnavailableException exception) {
      logWriter.println(
          "ERROR:  Line unavailable for default line end bell:  " + exception.getMessage());
      lineEndClip = null;
    }

    brailleText = new StyledText(composite, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
    brailleText.setLayoutData(new GridData(GridData.FILL_BOTH));
    brailleText.setFont(new Font(parentShell.getDisplay(), "BrailleZephyr_6s", 18, SWT.NORMAL));
    brailleText.addFocusListener(new FocusHandler(brailleText));
    brailleText.addPaintListener(new PaintHandler(brailleText));
    BrailleKeyHandler brailleKeyHandler = new BrailleKeyHandler(true);
    brailleText.addKeyListener(brailleKeyHandler);
    brailleText.addVerifyKeyListener(brailleKeyHandler);
    brailleText.addExtendedModifyListener(new ExtendedModifyHandler(brailleText));

    content = brailleText.getContent();

    asciiText = new StyledText(composite, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
    asciiText.setContent(content);
    asciiText.setLayoutData(new GridData(GridData.FILL_BOTH));
    asciiText.setFont(new Font(parentShell.getDisplay(), "Monospace", 18, SWT.NORMAL));
    asciiText.addFocusListener(new FocusHandler(asciiText));
    asciiText.addPaintListener(new PaintHandler(asciiText));
    asciiText.addVerifyKeyListener(new BrailleKeyHandler(false));
    asciiText.addExtendedModifyListener(new ExtendedModifyHandler(asciiText));

    brailleText.addCaretListener(new CaretHandler(brailleText, asciiText));
    asciiText.addCaretListener(new CaretHandler(asciiText, brailleText));

    currentText = brailleText;
  }
Пример #9
0
  /**
   * view command
   *
   * @param shell shell
   * @param repositoryTab repository tab
   * @param fileData file to view
   * @param revision revision to view
   */
  CommandView(
      final Shell shell,
      final RepositoryTab repositoryTab,
      final FileData fileData,
      final String revision) {
    Composite composite, subComposite;
    Label label;
    Button button;
    Listener listener;

    // initialize variables
    this.repositoryTab = repositoryTab;
    this.fileData = fileData;

    // get display
    display = shell.getDisplay();
    clipboard = new Clipboard(display);

    // add files dialog
    dialog = Dialogs.open(shell, "View: " + fileData.getFileName(), new double[] {1.0, 0.0}, 1.0);

    composite = Widgets.newComposite(dialog);
    composite.setLayout(new TableLayout(new double[] {0.0, 1.0, 0.0}, 1.0, 4));
    Widgets.layout(composite, 0, 0, TableLayoutData.NSWE, 0, 0, 4);
    {
      subComposite = Widgets.newComposite(composite);
      subComposite.setLayout(new TableLayout(1.0, new double[] {0.0, 1.0}));
      Widgets.layout(subComposite, 0, 0, TableLayoutData.WE);
      {
        label = Widgets.newLabel(subComposite, "Revision:");
        Widgets.layout(label, 0, 0, TableLayoutData.W);

        widgetRevision = Widgets.newSelect(subComposite);
        widgetRevision.setEnabled(false);
        Widgets.layout(widgetRevision, 0, 1, TableLayoutData.WE);
        Widgets.addModifyListener(
            new WidgetListener(widgetRevision, data) {
              public void modified(Control control) {
                Widgets.setEnabled(control, (data.revisionNames != null));
              }
            });
        widgetRevision.setToolTipText("Revision to view.");

        widgetRevisionPrev = Widgets.newButton(subComposite, Onzen.IMAGE_ARROW_LEFT);
        widgetRevisionPrev.setEnabled(false);
        Widgets.layout(widgetRevisionPrev, 0, 2, TableLayoutData.NSW);
        Widgets.addModifyListener(
            new WidgetListener(widgetRevisionPrev, data) {
              public void modified(Control control) {
                Widgets.setEnabled(
                    control,
                    (data.revisionNames != null) && (widgetRevision.getSelectionIndex() > 0));
              }
            });
        widgetRevisionPrev.setToolTipText("Show previous revision.");

        widgetRevisionNext = Widgets.newButton(subComposite, Onzen.IMAGE_ARROW_RIGHT);
        widgetRevisionNext.setEnabled(false);
        Widgets.layout(widgetRevisionNext, 0, 3, TableLayoutData.NSW);
        Widgets.addModifyListener(
            new WidgetListener(widgetRevisionNext, data) {
              public void modified(Control control) {

                Widgets.setEnabled(
                    control,
                    (data.revisionNames != null)
                        && (widgetRevision.getSelectionIndex() < data.revisionNames.length - 1));
              }
            });
        widgetRevisionNext.setToolTipText("Show next revision.");
      }

      subComposite = Widgets.newComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);
      subComposite.setLayout(new TableLayout(1.0, new double[] {0.0, 1.0}));
      Widgets.layout(subComposite, 1, 0, TableLayoutData.NSWE);
      {
        widgetLineNumbers = Widgets.newTextView(subComposite, SWT.RIGHT | SWT.BORDER | SWT.MULTI);
        widgetLineNumbers.setForeground(Onzen.COLOR_GRAY);
        Widgets.layout(widgetLineNumbers, 0, 0, TableLayoutData.NS, 0, 0, 0, 0, 60, SWT.DEFAULT);
        Widgets.addModifyListener(
            new WidgetListener(widgetLineNumbers, data) {
              public void modified(Control control) {
                control.setForeground((data.lines != null) ? null : Onzen.COLOR_GRAY);
              }
            });

        widgetText = Widgets.newTextView(subComposite, SWT.LEFT | SWT.BORDER | SWT.MULTI);
        widgetText.setForeground(Onzen.COLOR_GRAY);
        Widgets.layout(widgetText, 0, 1, TableLayoutData.NSWE);
        Widgets.addModifyListener(
            new WidgetListener(widgetText, data) {
              public void modified(Control control) {
                control.setForeground((data.lines != null) ? null : Onzen.COLOR_GRAY);
              }
            });
      }
      widgetHorizontalScrollBar = subComposite.getHorizontalBar();
      widgetVerticalScrollBar = subComposite.getVerticalBar();

      subComposite = Widgets.newComposite(composite);
      subComposite.setLayout(new TableLayout(1.0, new double[] {0.0, 1.0}));
      Widgets.layout(subComposite, 2, 0, TableLayoutData.NSWE);
      {
        label = Widgets.newLabel(subComposite, "Find:", SWT.NONE, Settings.keyFind);
        Widgets.layout(label, 0, 0, TableLayoutData.W);

        widgetFind = Widgets.newText(subComposite, SWT.SEARCH | SWT.ICON_CANCEL);
        widgetFind.setMessage("Enter text to find");
        Widgets.layout(widgetFind, 0, 1, TableLayoutData.WE);

        widgetFindPrev = Widgets.newButton(subComposite, Onzen.IMAGE_ARROW_UP);
        widgetFindPrev.setEnabled(false);
        Widgets.layout(widgetFindPrev, 0, 2, TableLayoutData.NSW);
        Widgets.addModifyListener(
            new WidgetListener(widgetFindPrev, data) {
              public void modified(Control control) {
                Widgets.setEnabled(control, (data.lines != null));
              }
            });
        widgetFindPrev.setToolTipText(
            "Find previous occurrence of text ["
                + Widgets.acceleratorToText(Settings.keyFindPrev)
                + "].");

        widgetFindNext = Widgets.newButton(subComposite, Onzen.IMAGE_ARROW_DOWN);
        widgetFindNext.setEnabled(false);
        Widgets.layout(widgetFindNext, 0, 3, TableLayoutData.NSW);
        Widgets.addModifyListener(
            new WidgetListener(widgetFindNext, data) {
              public void modified(Control control) {
                Widgets.setEnabled(control, (data.lines != null));
              }
            });
        widgetFindNext.setToolTipText(
            "Find next occurrence of text  ["
                + Widgets.acceleratorToText(Settings.keyFindNext)
                + "].");
      }
    }

    // buttons
    composite = Widgets.newComposite(dialog);
    composite.setLayout(new TableLayout(0.0, 1.0));
    Widgets.layout(composite, 1, 0, TableLayoutData.WE, 0, 0, 4);
    {
      button = Widgets.newButton(composite, "Save as...");
      Widgets.layout(
          button, 0, 0, TableLayoutData.W, 0, 0, 0, 0, SWT.DEFAULT, SWT.DEFAULT, 70, SWT.DEFAULT);
      button.addSelectionListener(
          new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent selectionEvent) {}

            public void widgetSelected(SelectionEvent selectionEvent) {
              // get file name
              String fileName = Dialogs.fileSave(dialog, "Save file", "", new String[] {"*"});
              if (fileName == null) {
                return;
              }

              // check if file exists: overwrite or append
              File file = new File(fileName);
              if (file.exists()) {
                switch (Dialogs.select(
                    dialog,
                    "Confirmation",
                    String.format("File '%s' already exists.", fileName),
                    new String[] {"Overwrite", "Append", "Cancel"},
                    2)) {
                  case 0:
                    if (!file.delete()) {
                      Dialogs.error(dialog, "Cannot delete file!");
                      return;
                    }
                  case 1:
                    break;
                  case 2:
                    return;
                }
              }

              PrintWriter output = null;
              try {
                // open file
                output = new PrintWriter(new FileWriter(file, true));

                // write/append file
                for (String line : data.lines) {
                  output.println(line);
                }

                // close file
                output.close();
              } catch (IOException exception) {
                Dialogs.error(
                    dialog,
                    "Cannot write file '" + file.getName() + "' (error: " + exception.getMessage());
                return;
              } finally {
                if (output != null) output.close();
              }
            }
          });

      widgetClose = Widgets.newButton(composite, "Close");
      Widgets.layout(
          widgetClose,
          0,
          1,
          TableLayoutData.E,
          0,
          0,
          0,
          0,
          SWT.DEFAULT,
          SWT.DEFAULT,
          70,
          SWT.DEFAULT);
      widgetClose.addSelectionListener(
          new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent selectionEvent) {}

            public void widgetSelected(SelectionEvent selectionEvent) {
              Settings.geometryView = dialog.getSize();

              Dialogs.close(dialog, false);
            }
          });
    }

    // listeners
    widgetRevision.addSelectionListener(
        new SelectionListener() {
          public void widgetDefaultSelected(SelectionEvent selectionEvent) {}

          public void widgetSelected(SelectionEvent selectionEvent) {
            Combo widget = (Combo) selectionEvent.widget;

            int index = widget.getSelectionIndex();
            if ((data.revisionNames != null)
                && (index >= 0)
                && (index < data.revisionNames.length)) {
              show(data.revisionNames[index]);
            }
          }
        });
    widgetRevisionPrev.addSelectionListener(
        new SelectionListener() {
          public void widgetDefaultSelected(SelectionEvent selectionEvent) {}

          public void widgetSelected(SelectionEvent selectionEvent) {
            int index = widgetRevision.getSelectionIndex();
            if (index > 0) {
              show(data.revisionNames[index - 1]);
            }
          }
        });
    widgetRevisionNext.addSelectionListener(
        new SelectionListener() {
          public void widgetDefaultSelected(SelectionEvent selectionEvent) {}

          public void widgetSelected(SelectionEvent selectionEvent) {
            int index = widgetRevision.getSelectionIndex();
            if ((data.revisionNames != null) && (index < data.revisionNames.length - 1)) {
              show(data.revisionNames[index + 1]);
            }
          }
        });

    listener =
        new Listener() {
          public void handleEvent(Event event) {
            StyledText widget = (StyledText) event.widget;
            int topIndex = widget.getTopIndex();
            // Dprintf.dprintf("%d %d",widget.getTopPixel(),widgetText.getTopPixel());

            widgetText.setTopIndex(topIndex);
            widgetText.setCaretOffset(widgetText.getOffsetAtLine(topIndex));
          }
        };
    widgetLineNumbers.addListener(SWT.KeyDown, listener);
    widgetLineNumbers.addListener(SWT.KeyUp, listener);
    widgetLineNumbers.addListener(SWT.MouseDown, listener);
    widgetLineNumbers.addListener(SWT.MouseUp, listener);
    widgetLineNumbers.addListener(SWT.MouseMove, listener);
    widgetLineNumbers.addListener(SWT.Resize, listener);

    listener =
        new Listener() {
          public void handleEvent(Event event) {
            StyledText widget = (StyledText) event.widget;
            int topIndex = widget.getTopIndex();
            // Dprintf.dprintf("widget=%s: %d",widget,widget.getTopIndex());

            widgetLineNumbers.setTopIndex(topIndex);
            widgetVerticalScrollBar.setSelection(topIndex);
          }
        };
    widgetText.addListener(SWT.KeyDown, listener);
    widgetText.addListener(SWT.KeyUp, listener);
    widgetText.addListener(SWT.MouseDown, listener);
    widgetText.addListener(SWT.MouseUp, listener);
    widgetText.addListener(SWT.MouseMove, listener);
    widgetText.addListener(SWT.Resize, listener);
    widgetText.addLineStyleListener(
        new LineStyleListener() {
          public void lineGetStyle(LineStyleEvent lineStyleEvent) {
            // Dprintf.dprintf("x %d %s",lineStyleEvent.lineOffset,lineStyleEvent.lineText);
            String findText = widgetFind.getText().toLowerCase();
            int findTextLength = findText.length();
            if (findTextLength > 0) {
              ArrayList<StyleRange> styleRangeList = new ArrayList<StyleRange>();
              int index = 0;
              while ((index = lineStyleEvent.lineText.toLowerCase().indexOf(findText, index))
                  >= 0) {
                styleRangeList.add(
                    new StyleRange(
                        lineStyleEvent.lineOffset + index,
                        findTextLength,
                        COLOR_VIEW_SEARCH_TEXT,
                        COLOR_VIEW_SEARCH_BACKGROUND));
                index += findTextLength;
              }
              lineStyleEvent.styles = styleRangeList.toArray(new StyleRange[styleRangeList.size()]);
              // Dprintf.dprintf("lineStyleEvent.styles=%d",lineStyleEvent.styles.length);
            } else {
              lineStyleEvent.styles = null;
            }
          }
        });
    widgetText.addKeyListener(
        new KeyListener() {
          public void keyPressed(KeyEvent keyEvent) {
            if (Widgets.isAccelerator(keyEvent, SWT.CTRL + 'c')) {
              Widgets.setClipboard(clipboard, widgetText.getSelectionText());
            }
          }

          public void keyReleased(KeyEvent keyEvent) {}
        });
    widgetHorizontalScrollBar.addSelectionListener(
        new SelectionListener() {
          public void widgetDefaultSelected(SelectionEvent selectionEvent) {}

          public void widgetSelected(SelectionEvent selectionEvent) {
            ScrollBar widget = (ScrollBar) selectionEvent.widget;
            int index = widget.getSelection();

            // sync text widget
            widgetText.setHorizontalIndex(index);
          }
        });
    widgetVerticalScrollBar.addSelectionListener(
        new SelectionListener() {
          public void widgetDefaultSelected(SelectionEvent selectionEvent) {}

          public void widgetSelected(SelectionEvent selectionEvent) {
            ScrollBar widget = (ScrollBar) selectionEvent.widget;
            int index = widget.getSelection();
            // Dprintf.dprintf("widget=%s: %d %d
            // %d",widget,widget.getSelection(),widget.getMinimum(),widget.getMaximum());

            // sync  number text widget, text widget
            widgetLineNumbers.setTopIndex(index);
            widgetText.setTopIndex(index);
          }
        });

    widgetFind.addSelectionListener(
        new SelectionListener() {
          public void widgetDefaultSelected(SelectionEvent selectionEvent) {
            findNext(widgetText, widgetFind);
          }

          public void widgetSelected(SelectionEvent selectionEvent) {}
        });
    widgetFind.addKeyListener(
        new KeyListener() {
          public void keyPressed(KeyEvent keyEvent) {}

          public void keyReleased(KeyEvent keyEvent) {
            updateViewFindText(widgetText, widgetFind);
          }
        });
    widgetFindPrev.addSelectionListener(
        new SelectionListener() {
          public void widgetDefaultSelected(SelectionEvent selectionEvent) {}

          public void widgetSelected(SelectionEvent selectionEvent) {
            findPrev(widgetText, widgetFind);
          }
        });
    widgetFindNext.addSelectionListener(
        new SelectionListener() {
          public void widgetDefaultSelected(SelectionEvent selectionEvent) {}

          public void widgetSelected(SelectionEvent selectionEvent) {
            findNext(widgetText, widgetFind);
          }
        });

    KeyListener keyListener =
        new KeyListener() {
          public void keyPressed(KeyEvent keyEvent) {
            if (Widgets.isAccelerator(keyEvent, Settings.keyFind)) {
              widgetFind.forceFocus();
            } else if (Widgets.isAccelerator(keyEvent, Settings.keyFindPrev)) {
              Widgets.invoke(widgetFindPrev);
            } else if (Widgets.isAccelerator(keyEvent, Settings.keyFindNext)) {
              Widgets.invoke(widgetFindNext);
            }
          }

          public void keyReleased(KeyEvent keyEvent) {}
        };
    widgetText.addKeyListener(keyListener);
    widgetFind.addKeyListener(keyListener);
    widgetFindPrev.addKeyListener(keyListener);
    widgetFindNext.addKeyListener(keyListener);

    dialog.addListener(
        USER_EVENT_NEW_REVISION,
        new Listener() {
          public void handleEvent(Event event) {}
        });

    // show dialog
    Dialogs.show(dialog, Settings.geometryView, Settings.setWindowLocation);

    // start show file
    show(revision);

    // start add revisions (only if single file is seleccted)
    Background.run(
        new BackgroundRunnable(fileData, revision) {
          public void run(FileData fileData, final String revision) {
            // get revisions
            repositoryTab.setStatusText("Get revisions for '%s'...", fileData.getFileName());
            try {
              data.revisionNames = repositoryTab.repository.getRevisionNames(fileData);
            } catch (RepositoryException exception) {
              final String exceptionMessage = exception.getMessage();
              display.syncExec(
                  new Runnable() {
                    public void run() {
                      Dialogs.error(
                          dialog, String.format("Getting revisions fail: %s", exceptionMessage));
                    }
                  });
              return;
            } finally {
              repositoryTab.clearStatusText();
            }

            if (data.revisionNames.length > 0) {
              // add revisions
              if (!dialog.isDisposed()) {
                display.syncExec(
                    new Runnable() {
                      public void run() {
                        if (!widgetRevision.isDisposed()) {
                          int selectIndex = -1;
                          for (int z = 0; z < data.revisionNames.length; z++) {
                            widgetRevision.add(data.revisionNames[z]);
                            if ((revision != null) && revision.equals(data.revisionNames[z])) {
                              selectIndex = z;
                            }
                          }
                          widgetRevision.add(repositoryTab.repository.getLastRevision());
                          if ((revision != null)
                              && revision.equals(repositoryTab.repository.getLastRevision()))
                            selectIndex = data.revisionNames.length;
                          if (selectIndex == -1) selectIndex = data.revisionNames.length;
                          widgetRevision.select(selectIndex);
                        }

                        // notify modification
                        Widgets.modified(data);
                      }
                    });
              }
            }
          }
        });
  }
Пример #10
0
  public void createPartControl(Composite parent) {
    SashForm sash = new SashForm(parent, SWT.VERTICAL | SWT.SMOOTH);

    queryViewer = new SourceViewer(sash, null, SWT.MULTI | SWT.WRAP);
    queryString = queryViewer.getTextWidget();
    queryString.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT));
    Color background = queryString.getBackground();
    IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager();
    ITheme current = themeManager.getCurrentTheme();
    ColorRegistry colorRegistry = current.getColorRegistry();
    commentCol = colorRegistry.get(ColorProvider.COMMENT_COLOR_PREF);
    keywordCol = colorRegistry.get(ColorProvider.KEYWORD_COLOR_PREF);
    IDocument d = createDocument();
    d.set(Messages.OQLPane_F1ForHelp);

    queryViewer.addSelectionChangedListener(
        new ISelectionChangedListener() {
          public void selectionChanged(SelectionChangedEvent event) {
            updateActions();
          }
        });

    queryViewer.setDocument(d);
    queryViewer.configure(new OQLTextViewerConfiguration(getSnapshot(), commentCol, keywordCol));
    // Eclipse 4 seems to need this otherwise in high contrast mode the background is white
    queryString.setBackground(background);
    queryString.selectAll();

    PlatformUI.getWorkbench()
        .getHelpSystem()
        .setHelp(queryString, "org.eclipse.mat.ui.help.oql"); // $NON-NLS-1$
    queryString.addKeyListener(
        new KeyAdapter() {
          public void keyPressed(KeyEvent e) {
            if (e.keyCode == '\r' && (e.stateMask & SWT.MOD1) != 0) {
              executeAction.run();
              e.doit = false;
            } else if (e.keyCode == ' ' && (e.stateMask & SWT.CTRL) != 0) {
              // ctrl space combination for content assist
              contentAssistAction.run();
            } else if (e.keyCode == SWT.F5) {
              executeAction.run();
              e.doit = false;
            }
          }
        });

    queryString.addFocusListener(
        new FocusListener() {

          public void focusGained(FocusEvent e) {
            IActionBars actionBars = getEditor().getEditorSite().getActionBars();
            actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), copyQueryStringAction);
            actionBars.updateActionBars();
          }

          public void focusLost(FocusEvent e) {}
        });
    queryString.setFocus();

    createContainer(sash);

    sash.setWeights(new int[] {1, 4});

    makeActions();
    hookContextMenu();
  }