KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > diff > builtin > visualizer > DiffPanel


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.diff.builtin.visualizer;
21
22 import java.awt.event.ActionEvent JavaDoc;
23 import java.awt.event.FocusEvent JavaDoc;
24 import java.awt.event.FocusListener JavaDoc;
25 import java.awt.*;
26 //import java.awt.Rectangle;
27
import java.beans.PropertyChangeEvent JavaDoc;
28 import java.beans.PropertyChangeListener JavaDoc;
29 import java.util.*;
30 import java.io.*;
31 import javax.swing.*;
32 import javax.swing.text.*;
33 import org.netbeans.api.editor.fold.FoldHierarchy;
34 import org.netbeans.api.editor.fold.FoldUtilities;
35 import org.netbeans.editor.EditorUI;
36 import org.netbeans.editor.ext.ExtCaret;
37 import org.netbeans.modules.diff.builtin.DiffPresenter;
38
39 import org.openide.actions.CopyAction;
40 import org.openide.util.actions.ActionPerformer;
41 import org.openide.util.actions.CallbackSystemAction;
42 import org.openide.util.actions.SystemAction;
43 import org.openide.ErrorManager;
44 import org.openide.text.CloneableEditorSupport;
45 //import org.openide.windows.Workspace;
46
//import org.openide.windows.Mode;
47

48 /**
49  * This class displays two editor panes with two files and marks the differences
50  * by a different color.
51  * @author Martin Entlicher
52  */

53 public class DiffPanel extends javax.swing.JPanel JavaDoc implements javax.swing.event.CaretListener JavaDoc {
54
55 // private AbstractDiff diff = null;
56
private int totalHeight = 0;
57     private int totalLines = 0;
58
59     //private java.awt.Color numBackgroundColor = new java.awt.Color(224, 224, 224);
60
//private java.awt.Color numForegroundColor = new java.awt.Color(128, 64, 64);
61

62     private int horizontalScroll1ChangedValue = -1;
63     private int horizontalScroll2ChangedValue = -1;
64     
65     private LinesComponent linesComp1;
66     private LinesComponent linesComp2;
67
68     static final long serialVersionUID =3683458237532937983L;
69     private static final String JavaDoc PLAIN_TEXT_MIME = "text/plain";
70
71     /** Creates new DiffComponent from AbstractDiff object*/
72     public DiffPanel() {
73 // this.diff = diff;
74
initComponents ();
75
76         // my init components that radically modifies initComponents()
77
// so all (including this toolbar) is clickable in form editor
78
commandPanel.remove(prevButton);
79         commandPanel.remove(nextButton);
80         JPanel toolbar = new JPanel(new FlowLayout(FlowLayout.TRAILING, 5, 0));
81         toolbar.setBorder(BorderFactory.createEmptyBorder());
82         toolbar.add(prevButton);
83         toolbar.add(nextButton);
84         remove(commandPanel);
85         putClientProperty(DiffPresenter.PROP_TOOLBAR, toolbar);
86         
87         //setTitle(org.openide.util.NbBundle.getBundle(DiffComponent.class).getString("DiffComponent.title"));
88
setName(org.openide.util.NbBundle.getMessage(DiffPanel.class, "DiffComponent.title"));
89         //HelpCtx.setHelpIDString (getRootPane (), DiffComponent.class.getName ());
90
initActions();
91         jSplitPane1.setResizeWeight(0.5);
92         putClientProperty("PersistenceType", "Never");
93         getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(DiffPanel.class, "ACS_DiffPanelA11yName")); // NOI18N
94
getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(DiffPanel.class, "ACS_DiffPanelA11yDesc")); // NOI18N
95
jEditorPane1.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(DiffPanel.class, "ACS_EditorPane1A11yName")); // NOI18N
96
jEditorPane1.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(DiffPanel.class, "ACS_EditorPane1A11yDescr")); // NOI18N
97
jEditorPane2.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(DiffPanel.class, "ACS_EditorPane2A11yName")); // NOI18N
98
jEditorPane2.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(DiffPanel.class, "ACS_EditorPane2A11yDescr")); // NOI18N
99
}
100
101     public void addNotify() {
102         super.addNotify();
103
104         jEditorPane1.putClientProperty("HighlightsLayerExcludes", "^org\\.netbeans\\.modules\\.editor\\.lib2\\.highlighting\\.CaretRowHighlighting$"); //NOI18N
105
jEditorPane2.putClientProperty("HighlightsLayerExcludes", "^org\\.netbeans\\.modules\\.editor\\.lib2\\.highlighting\\.CaretRowHighlighting$"); //NOI18N
106

107         JComponent parent = (JComponent) getParent();
108         
109         Action nextAction = new ButtonAction(nextButton);
110         Action prevAction = new ButtonAction(prevButton);
111         parent.getActionMap().put("jumpNext", nextAction); // NOI18N
112
parent.getActionMap().put("jumpPrev", prevAction); // NOI18N
113
}
114
115     /** Reverse mapping button => action */
116     private static class ButtonAction extends AbstractAction {
117
118         final JButton button;
119
120         public ButtonAction(JButton button) {
121             this.button = button;
122         }
123
124         public void actionPerformed(ActionEvent JavaDoc e) {
125             button.doClick();
126         }
127     }
128
129     /** This method is called from within the constructor to
130      * initialize the form.
131      * WARNING: Do NOT modify this code. The content of this method is
132      * always regenerated by the FormEditor.
133      */

134     // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
135
private void initComponents() {
136         java.awt.GridBagConstraints JavaDoc gridBagConstraints;
137
138         setLayout(new java.awt.GridBagLayout JavaDoc());
139
140         commandPanel.setLayout(new java.awt.GridBagLayout JavaDoc());
141
142         prevButton.setIcon(new ImageIcon(org.openide.util.Utilities.loadImage("org/netbeans/modules/diff/builtin/visualizer/prev.gif", true)));
143         prevButton.setToolTipText(org.openide.util.NbBundle.getBundle(DiffPanel.class).getString("DiffComponent.prevButton.toolTipText"));
144         prevButton.setMargin(new java.awt.Insets JavaDoc(0, 0, 0, 0));
145         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
146         gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE;
147         gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
148         commandPanel.add(prevButton, gridBagConstraints);
149
150         nextButton.setIcon(new ImageIcon(org.openide.util.Utilities.loadImage("org/netbeans/modules/diff/builtin/visualizer/next.gif", true)));
151         nextButton.setToolTipText(org.openide.util.NbBundle.getBundle(DiffPanel.class).getString("DiffComponent.nextButton.toolTipText"));
152         nextButton.setMargin(new java.awt.Insets JavaDoc(0, 0, 0, 0));
153         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
154         gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE;
155         gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
156         gridBagConstraints.insets = new java.awt.Insets JavaDoc(0, 2, 0, 0);
157         commandPanel.add(nextButton, gridBagConstraints);
158
159         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
160         gridBagConstraints.gridy = 0;
161         gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
162         gridBagConstraints.weightx = 1.0;
163         gridBagConstraints.insets = new java.awt.Insets JavaDoc(5, 5, 5, 5);
164         add(commandPanel, gridBagConstraints);
165
166         editorPanel.setLayout(new java.awt.GridBagLayout JavaDoc());
167
168         editorPanel.setPreferredSize(new java.awt.Dimension JavaDoc(700, 600));
169         jSplitPane1.setDividerSize(4);
170         filePanel1.setLayout(new java.awt.GridBagLayout JavaDoc());
171
172         jEditorPane1.addCaretListener(this);
173
174         jScrollPane1.setViewportView(jEditorPane1);
175
176         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
177         gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
178         gridBagConstraints.weightx = 1.0;
179         gridBagConstraints.weighty = 1.0;
180         filePanel1.add(jScrollPane1, gridBagConstraints);
181
182         fileLabel1.setText("jLabel1");
183         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
184         gridBagConstraints.gridy = 1;
185         gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
186         gridBagConstraints.weightx = 1.0;
187         gridBagConstraints.insets = new java.awt.Insets JavaDoc(4, 4, 4, 4);
188         filePanel1.add(fileLabel1, gridBagConstraints);
189
190         jSplitPane1.setLeftComponent(filePanel1);
191
192         filePanel2.setLayout(new java.awt.GridBagLayout JavaDoc());
193
194         jEditorPane2.addCaretListener(this);
195
196         jScrollPane2.setViewportView(jEditorPane2);
197
198         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
199         gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
200         gridBagConstraints.weightx = 1.0;
201         gridBagConstraints.weighty = 1.0;
202         filePanel2.add(jScrollPane2, gridBagConstraints);
203
204         fileLabel2.setText("jLabel2");
205         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
206         gridBagConstraints.gridy = 1;
207         gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
208         gridBagConstraints.weightx = 1.0;
209         gridBagConstraints.insets = new java.awt.Insets JavaDoc(4, 4, 4, 4);
210         filePanel2.add(fileLabel2, gridBagConstraints);
211
212         jSplitPane1.setRightComponent(filePanel2);
213
214         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
215         gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
216         gridBagConstraints.weightx = 1.0;
217         gridBagConstraints.weighty = 1.0;
218         editorPanel.add(jSplitPane1, gridBagConstraints);
219
220         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
221         gridBagConstraints.gridy = 1;
222         gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
223         gridBagConstraints.weightx = 1.0;
224         gridBagConstraints.weighty = 1.0;
225         add(editorPanel, gridBagConstraints);
226
227     }
228
229     // Code for dispatching events from components to event handlers.
230

231     public void caretUpdate(javax.swing.event.CaretEvent JavaDoc evt) {
232         if (evt.getSource() == jEditorPane1) {
233             DiffPanel.this.jEditorPane1CaretUpdate(evt);
234         }
235         else if (evt.getSource() == jEditorPane2) {
236             DiffPanel.this.jEditorPane2CaretUpdate(evt);
237         }
238     }// </editor-fold>//GEN-END:initComponents
239

240   private void jEditorPane1CaretUpdate(javax.swing.event.CaretEvent JavaDoc evt) {//GEN-FIRST:event_jEditorPane1CaretUpdate
241
// Add your handling code here:
242
/* int pos = evt.getDot();
243       int line = org.openide.text.NbDocument.findLineNumber((StyledDocument) jEditorPane1.getDocument(), pos);
244       StyledDocument linesDoc = (StyledDocument)jEditorPane1.getDocument();
245       int numLines = org.openide.text.NbDocument.findLineNumber(linesDoc, linesDoc.getEndPosition().getOffset());
246       if (line <= numLines) {
247           jEditorPane1.setCaretPosition(org.openide.text.NbDocument.findLineOffset(linesDoc, line));
248       }
249  */

250   }//GEN-LAST:event_jEditorPane1CaretUpdate
251

252   private void jEditorPane2CaretUpdate(javax.swing.event.CaretEvent JavaDoc evt) {//GEN-FIRST:event_jEditorPane2CaretUpdate
253
// Add your handling code here:
254
/* int pos = evt.getDot();
255       int line = org.openide.text.NbDocument.findLineNumber((StyledDocument) jEditorPane2.getDocument(), pos);
256       StyledDocument linesDoc = (StyledDocument)jEditorPane2.getDocument();
257       int numLines = org.openide.text.NbDocument.findLineNumber(linesDoc, linesDoc.getEndPosition().getOffset());
258       if (line <= numLines) {
259           jEditorPane2.setCaretPosition(org.openide.text.NbDocument.findLineOffset(linesDoc, line));
260       }
261  */

262   }//GEN-LAST:event_jEditorPane2CaretUpdate
263

264   public void setCurrentLine(int line, int diffLength) {
265       if (line > 0) showLine(line, diffLength);
266   }
267
268   public void addPrevLineButtonListener(java.awt.event.ActionListener JavaDoc listener) {
269       prevButton.addActionListener(listener);
270   }
271   public void addNextLineButtonListener(java.awt.event.ActionListener JavaDoc listener) {
272       nextButton.addActionListener(listener);
273   }
274   
275   /*
276   public void goToNextLine(int line, int diffLength) {
277       if (line > 0) showLine(line, diffLength);
278   }
279    */

280   
281     private void jScrollBar1AdjustmentValueChanged (java.awt.event.AdjustmentEvent JavaDoc evt) {//GEN-FIRST:event_jScrollBar1AdjustmentValueChanged
282
// Add your handling code here:
283
}//GEN-LAST:event_jScrollBar1AdjustmentValueChanged
284

285     private void closeButtonActionPerformed (java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_closeButtonActionPerformed
286
// Add your handling code here:
287
exitForm(null);
288     }//GEN-LAST:event_closeButtonActionPerformed
289

290     /** Exit the Application */
291     private void exitForm(java.awt.event.WindowEvent JavaDoc evt) {//GEN-FIRST:event_exitForm
292
/* try {
293             org.netbeans.editor.Settings.setValue(null, org.netbeans.editor.SettingsNames.LINE_NUMBER_VISIBLE, lineNumbersVisible);
294         } catch (Throwable exc) {
295             // editor module not found
296         }
297         //System.out.println("exitForm() called.");
298         //diff.closing();
299         //close();
300         //dispose ();
301         for(Iterator it = closeListeners.iterator(); it.hasNext(); ) {
302             ((TopComponentCloseListener) it.next()).closing();
303         }
304  */

305     }//GEN-LAST:event_exitForm
306

307     private void initActions() {
308         jEditorPane1.addFocusListener(new FocusListener JavaDoc() {
309             public void focusGained(FocusEvent JavaDoc e) {
310                 editorActivated(jEditorPane1);
311             }
312             public void focusLost(FocusEvent JavaDoc e) {
313                 editorDeactivated(jEditorPane1);
314             }
315         });
316         jEditorPane2.addFocusListener(new FocusListener JavaDoc() {
317             public void focusGained(FocusEvent JavaDoc e) {
318                 editorActivated(jEditorPane2);
319             }
320             public void focusLost(FocusEvent JavaDoc e) {
321                 editorDeactivated(jEditorPane2);
322             }
323         });
324     }
325     
326     private Hashtable<JEditorPane, Hashtable<Object JavaDoc, Action>> kitActions;
327             /** Listener for copy action enabling */
328     private PropertyChangeListener JavaDoc copyL;
329     private PropertyChangeListener JavaDoc copyP;
330     
331     private Action getAction (String JavaDoc s, JEditorPane editor) {
332         if (kitActions == null) {
333             kitActions = new Hashtable<JEditorPane, Hashtable<Object JavaDoc, Action>>();
334         }
335         Hashtable<Object JavaDoc, Action> actions = kitActions.get(editor);
336         if (actions == null) {
337             EditorKit kit = editor.getEditorKit();
338             if (kit == null) {
339                 return null;
340             }
341             
342             Action[] a = kit.getActions ();
343             actions = new Hashtable<Object JavaDoc, Action> (a.length);
344             int k = a.length;
345             for (int i = 0; i < k; i++)
346                 actions.put (a[i].getValue (Action.NAME), a[i]);
347             kitActions.put(editor, actions);
348         }
349         return actions.get (s);
350     }
351     
352     private void editorActivated(final JEditorPane editor) {
353         //System.out.println("editor("+editor+") activated.");
354
final Action copy = getAction (DefaultEditorKit.copyAction, editor);
355         if (copy != null) {
356             final CallbackSystemAction sysCopy
357             = ((CallbackSystemAction) SystemAction.get (CopyAction.class));
358             final ActionPerformer perf = new ActionPerformer () {
359                 public void performAction (SystemAction action) {
360                     copy.actionPerformed (new ActionEvent JavaDoc (editor, 0, "")); // NOI18N
361
}
362             };
363             sysCopy.setActionPerformer(copy.isEnabled() ? perf : null);
364             PropertyChangeListener JavaDoc copyListener;
365             copy.addPropertyChangeListener(copyListener = new PropertyChangeListener JavaDoc() {
366                 public void propertyChange(PropertyChangeEvent JavaDoc evt) {
367                     if ("enabled".equals(evt.getPropertyName())) { // NOI18N
368
if (((Boolean JavaDoc)evt.getNewValue()).booleanValue()) {
369                             sysCopy.setActionPerformer(perf);
370                         } else if (sysCopy.getActionPerformer() == perf) {
371                             sysCopy.setActionPerformer(null);
372                         }
373                     }
374                 }
375             });
376             if (editor.equals(jEditorPane1)) copyL = copyListener;
377             else copyP = copyListener;
378         }
379     }
380     
381     private void editorDeactivated(JEditorPane editor) {
382         //System.out.println("editorDeactivated ("+editor+")");
383
Action copy = getAction (DefaultEditorKit.copyAction, editor);
384         PropertyChangeListener JavaDoc copyListener;
385         if (editor.equals(jEditorPane1)) copyListener = copyL;
386         else copyListener = copyP;
387         if (copy != null) {
388             copy.removePropertyChangeListener(copyListener);
389         }
390     }
391     
392
393     public void open() {
394         javax.swing.SwingUtilities.invokeLater(new Runnable JavaDoc() {
395             public void run() {
396                 jSplitPane1.setDividerLocation(0.5);
397                 openPostProcess();
398             }
399         });
400     }
401
402     protected void openPostProcess() {
403         javax.swing.SwingUtilities.invokeLater(new Runnable JavaDoc() {
404             public void run() {
405                 expandFolds();
406                 initGlobalSizes();
407                 //showLine(1, 0);
408
addChangeListeners();
409 /* javax.swing.SwingUtilities.invokeLater(new Runnable() {
410                     public void run() {
411                         initGlobalSizes(); // do that again to be sure that components are initialized.
412                         javax.swing.SwingUtilities.invokeLater(new Runnable() {
413                             public void run() {
414                                 syncFont(); // Components have to be fully initialized before font syncing
415                                 addChangeListeners();
416                             }
417                         });
418                     }
419                 });
420  */

421             }
422         });
423     }
424     
425     private void expandFolds() {
426         FoldHierarchy fh = FoldHierarchy.get(jEditorPane1);
427         FoldUtilities.expandAll(fh);
428         fh = FoldHierarchy.get(jEditorPane2);
429         FoldUtilities.expandAll(fh);
430     }
431
432     /*
433     public void removeNotify() {
434         System.out.println("removeNotify() called");
435         exitForm(null);
436         super.removeNotify();
437     }
438      */

439     private void initGlobalSizes() {
440         StyledDocument doc1 = (StyledDocument) jEditorPane1.getDocument();
441         StyledDocument doc2 = (StyledDocument) jEditorPane2.getDocument();
442         int numLines1 = org.openide.text.NbDocument.findLineNumber(doc1, doc1.getEndPosition().getOffset());
443         int numLines2 = org.openide.text.NbDocument.findLineNumber(doc2, doc2.getEndPosition().getOffset());
444         int numLines = Math.max(numLines1, numLines2);
445         if (numLines < 1) numLines = 1;
446         this.totalLines = numLines;
447         // int totHeight = editorPanel1.getSize().height;
448
int totHeight = jEditorPane1.getSize().height;
449         // int value = editorPanel2.getSize().height;
450
int value = jEditorPane2.getSize().height;
451         if (value > totHeight) totHeight = value;
452         this.totalHeight = totHeight;
453     }
454
455     private void showLine(int line, int diffLength) {
456         //System.out.println("showLine("+line+", "+diffLength+")");
457
this.linesComp1.setActiveLine(line);
458         this.linesComp2.setActiveLine(line);
459         linesComp2.repaint();
460         linesComp1.repaint();
461         int padding = 5;
462         if (line <= 5) padding = line/2;
463         int off1, off2;
464         int ypos;
465         int viewHeight = jViewport1.getExtentSize().height;
466         java.awt.Point JavaDoc p1, p2;
467         initGlobalSizes(); // The window might be resized in the mean time.
468
p1 = jViewport1.getViewPosition();
469         p2 = jViewport2.getViewPosition();
470         ypos = (totalHeight*(line - padding - 1))/(totalLines + 1);
471
472         try {
473             off1 = org.openide.text.NbDocument.findLineOffset((StyledDocument) jEditorPane1.getDocument(), line - 1);
474             off2 = org.openide.text.NbDocument.findLineOffset((StyledDocument) jEditorPane2.getDocument(), line - 1);
475
476             jEditorPane1.setCaretPosition(off1);
477             jEditorPane2.setCaretPosition(off2);
478         } catch (IndexOutOfBoundsException JavaDoc ex) {
479             ErrorManager.getDefault().notify(ex);
480         }
481
482         if (ypos < p1.y || ypos + ((diffLength + padding)*totalHeight)/totalLines > p1.y + viewHeight) {
483             p1.y = ypos;
484             jViewport1.setViewPosition(p1); // joinScrollBar will move paired view
485
}
486     }
487     
488     private void joinScrollBars() {
489         final JScrollBar scrollBarH1 = jScrollPane1.getHorizontalScrollBar();
490         final JScrollBar scrollBarV1 = jScrollPane1.getVerticalScrollBar();
491         final JScrollBar scrollBarH2 = jScrollPane2.getHorizontalScrollBar();
492         final JScrollBar scrollBarV2 = jScrollPane2.getVerticalScrollBar();
493         scrollBarV1.getModel().addChangeListener(new javax.swing.event.ChangeListener JavaDoc() {
494             public void stateChanged(javax.swing.event.ChangeEvent JavaDoc e) {
495                 int value = scrollBarV1.getValue();
496                 int oldValue = scrollBarV2.getValue();
497                 if (oldValue != value) {
498                     scrollBarV2.setValue(value);
499 // System.out.println("setting v2=" + value);
500
// Thread.dumpStack();
501
}
502             }
503         });
504         //jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
505
// The vertical scroll bar must be there for mouse wheel to work correctly.
506
// However it's not necessary to be seen (but must be visible so that the wheel will work).
507
jScrollPane1.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0));
508         scrollBarV2.getModel().addChangeListener(new javax.swing.event.ChangeListener JavaDoc() {
509             public void stateChanged(javax.swing.event.ChangeEvent JavaDoc e) {
510                 int value = scrollBarV2.getValue();
511                 int oldValue = scrollBarV1.getValue();
512                 if (oldValue != value) {
513                     scrollBarV1.setValue(value);
514 // System.out.println("setting v1 to=" + value);
515
}
516             }
517         });
518         scrollBarH1.getModel().addChangeListener(new javax.swing.event.ChangeListener JavaDoc() {
519             public void stateChanged(javax.swing.event.ChangeEvent JavaDoc e) {
520                 int value = scrollBarH1.getValue();
521                 // System.out.println("stateChangedH1:value = "+value+", horizontalScroll1ChangedValue = "+horizontalScroll1ChangedValue);
522
if (value == horizontalScroll1ChangedValue) return;
523                 int max1 = scrollBarH1.getMaximum();
524                 int max2 = scrollBarH2.getMaximum();
525                 int ext1 = scrollBarH1.getModel().getExtent();
526                 int ext2 = scrollBarH2.getModel().getExtent();
527                 if (max1 == ext1) horizontalScroll2ChangedValue = 0;
528                 else horizontalScroll2ChangedValue = (value*(max2 - ext2))/(max1 - ext1);
529                 horizontalScroll1ChangedValue = -1;
530                 // System.out.println("H1 value = "+value+" => H2 value = "+horizontalScroll2ChangedValue+"\t\tmax1 = "+max1+", max2 = "+max2);
531
scrollBarH2.setValue(horizontalScroll2ChangedValue);
532             }
533         });
534         scrollBarH2.getModel().addChangeListener(new javax.swing.event.ChangeListener JavaDoc() {
535             public void stateChanged(javax.swing.event.ChangeEvent JavaDoc e) {
536                 int value = scrollBarH2.getValue();
537                 // System.out.println("stateChangedH2:value = "+value+", horizontalScroll2ChangedValue = "+horizontalScroll2ChangedValue);
538
if (value == horizontalScroll2ChangedValue) return;
539                 int max1 = scrollBarH1.getMaximum();
540                 int max2 = scrollBarH2.getMaximum();
541                 int ext1 = scrollBarH1.getModel().getExtent();
542                 int ext2 = scrollBarH2.getModel().getExtent();
543                 if (max2 == ext2) horizontalScroll1ChangedValue = 0;
544                 else horizontalScroll1ChangedValue = (value*(max1 - ext1))/(max2 - ext2);
545                 horizontalScroll2ChangedValue = -1;
546                 // System.out.println("H2 value = "+value+" => H1 value = "+horizontalScroll1ChangedValue+"\t\tmax1 = "+max1+", max2 = "+max2);
547
scrollBarH1.setValue(horizontalScroll1ChangedValue);
548             }
549         });
550         jSplitPane1.setDividerLocation(0.5);
551     }
552     
553     private String JavaDoc strCharacters(char c, int num) {
554         StringBuffer JavaDoc s = new StringBuffer JavaDoc();
555         while(num-- > 0) {
556             s.append(c);
557         }
558         return s.toString();
559     }
560     
561     private void customizeEditor(JEditorPane editor) {
562         EditorKit kit = editor.getEditorKit();
563         /*
564         try {
565             org.netbeans.editor.Settings.setValue(null, org.netbeans.editor.SettingsNames.LINE_NUMBER_VISIBLE, Boolean.FALSE);
566         } catch (Throwable exc) {
567             // editor module not found
568         }
569          */

570         StyledDocument doc;
571         Document document = editor.getDocument();
572 /* StyledDocument docLines = new DefaultStyledDocument();
573         textLines.setStyledDocument(docLines);
574  */

575         try {
576             doc = (StyledDocument) editor.getDocument();
577         } catch(ClassCastException JavaDoc e) {
578             doc = new DefaultStyledDocument();
579             try {
580                 doc.insertString(0, document.getText(0, document.getLength()), null);
581             } catch (BadLocationException ble) {
582                 // leaving the document empty
583
}
584             editor.setDocument(doc);
585         }
586         int lastOffset = doc.getEndPosition().getOffset();
587         int numLines = org.openide.text.NbDocument.findLineNumber(doc, lastOffset);
588         int numLength = Integer.toString(numLines).length();
589         // textLines.setForeground(numForegroundColor);
590
// textLines.setBackground(numBackgroundColor);
591
for (int line = 0; line <= numLines; line++) {
592             int offset = org.openide.text.NbDocument.findLineOffset(doc, line);
593             String JavaDoc lineStr = Integer.toString(line+1);
594             if (lineStr.length() < numLength) lineStr = strCharacters(' ', numLength - lineStr.length()) + lineStr;
595             //lineStr = " "+lineStr+" "; // NOI18N
596
/* try {
597                 if (line < numLines) lineStr += "\n"; // NOI18N
598                 docLines.insertString(docLines.getLength(), lineStr, null);
599             } catch (BadLocationException e) {
600                 E.deb("Internal ERROR: "+e.getMessage()); // NOI18N
601             }
602  */

603         }
604         // joinScrollBars();
605
}
606     
607 /* private void syncFont(JEditorPane editorPane, JTextPane numLineText) {
608         //editorPane.getToolkit().sync();
609         /*
610         try {
611             //System.out.println("editor size = "+editorPane.getSize()+", last pos = "+editorPane.modelToView(editorPane.getDocument().getEndPosition().getOffset()));
612             java.awt.Rectangle viewRect = editorPane.modelToView(editorPane.getDocument().getEndPosition().getOffset());
613             if (viewRect.y <= totalLines && viewRect.height == 1) return; // probably not complete or empty document
614             editorPane.setSize(editorPane.getSize().width, viewRect.y + viewRect.height);
615             totalHeight = viewRect.y + viewRect.height;
616             //System.out.println(" => new editor size = "+editorPane.getSize());
617         } catch (javax.swing.text.BadLocationException exc) {
618             // ignored
619         }
620  */

621 /* //editorPane.getToolkit().sync();
622         java.awt.Font f = editorPane.getFont();
623         //numLineText.setFont(f);
624         float fontSize = f.getSize();
625         java.awt.Font nlf = numLineText.getFont();
626         StyledDocument doc = (StyledDocument) editorPane.getDocument();
627         Element root = org.openide.text.NbDocument.findLineRootElement(doc);
628         Element element = root.getElement(0);
629         //System.out.println("fontSize = "+fontSize);
630         javax.swing.text.View v = this.jEditorPane2.getUI().getRootView(this.jEditorPane2);
631         if (v.getViewCount() == 1)
632             v = v.getView (0);
633         int rh = (int) v.getPreferredSpan (View.Y_AXIS);
634         int lineHeight = rh/(org.openide.text.NbDocument.findLineNumber(doc, doc.getEndPosition().getOffset())+1);
635         int spacingGap = 0;
636         if (element != null) {
637             javax.swing.text.ViewFactory viewFactory = editorPane.getEditorKit().getViewFactory();
638             if (viewFactory != null) {
639                 javax.swing.text.View view = viewFactory.create(element);
640                 fontSize = view.getMaximumSpan(javax.swing.text.View.Y_AXIS);
641             } else {
642                 //System.out.println("size = "+editorPane.getSize().height+", num lines = "+org.openide.text.NbDocument.findLineNumber(doc, doc.getEndPosition().getOffset()));
643                 //int lineHeight = editorPane.getSize().height/org.openide.text.NbDocument.findLineNumber(doc, doc.getEndPosition().getOffset());
644                 //System.out.println("lineHeight = "+lineHeight);
645                 int fmh;
646                 do {
647                     java.awt.Font nlf1 = nlf.deriveFont(fontSize);
648                     fmh = numLineText.getFontMetrics(nlf1).getHeight();
649                     //System.out.println("fontSize = "+fontSize+" => fmh = "+fmh);
650                     if (fmh < lineHeight) fontSize += 1;
651                 } while (fmh < lineHeight);
652                 int maxfmh = fmh;
653                 do {
654                     java.awt.Font nlf1 = nlf.deriveFont(fontSize);
655                     fmh = numLineText.getFontMetrics(nlf1).getHeight();
656                     //System.out.println("fontSize = "+fontSize+" => fmh = "+fmh);
657                     if (fmh > lineHeight) fontSize -= 1;
658                 } while (fmh > lineHeight && fontSize > 1);
659                 int minfmh = fmh;
660                 spacingGap = maxfmh - minfmh;
661                 // if (minfmh != maxfmh && (lineHeight - minfmh)/(maxfmh - lineHeight) > 1) fontSize += 1;
662             }
663             //System.out.println("recalculated fontSize = "+fontSize);
664         }
665         nlf = nlf.deriveFont(fontSize);
666         int nlfLineHeight = numLineText.getFontMetrics(nlf).getHeight();
667         numLineText.setFont(nlf);
668         int numLines = root.getElementCount();
669         StyledDocument docNl = numLineText.getStyledDocument();
670         Element rootNl = docNl.getDefaultRootElement();
671         if (numLines < rootNl.getElementCount()) numLines = rootNl.getElementCount();
672         //for(int i = 0; i < numLines; i++) {
673         Element elementNl = rootNl;//.getElement(i);
674         AttributeSet attrNl = elementNl.getAttributes();
675         Style s = docNl.getLogicalStyle(elementNl.getStartOffset());
676         //System.out.println("style at "+elementNl.getStartOffset()+": "+s.getAttribute(StyleConstants.FontConstants.FontSize));
677 /* StyleConstants.setLineSpacing(s, ((float) StyleConstants.getLineSpacing(s)lineHeight)/nlfLineHeight);
678 /* StyleConstants.setFontSize(s, nlf.getSize());
679         if (spacingGap > 0) {
680             float currentGap = StyleConstants.getSpaceAbove(s);
681             currentGap = currentGap + spacingGap;
682             StyleConstants.setSpaceAbove(s, currentGap);
683         }
684         //StyleConstants.setSpaceAbove(s, lineHeight - nlf.getSize());
685 /* docNl.setLogicalStyle(elementNl.getStartOffset(), s);
686         //}
687         numLineText.repaint();
688     }
689  */

690     
691     /**
692      * Synchronize the font of line numbers with the editor's font.
693      */

694 /* private void syncFont() {
695         initGlobalSizes();
696 // syncFont(jEditorPane1, jTextPane1);
697 // syncFont(jEditorPane2, jTextPane2);
698         setScrollBarsIncrements();
699     }
700  */

701     
702     private void addChangeListeners() {
703         jEditorPane1.addPropertyChangeListener("font", new java.beans.PropertyChangeListener JavaDoc() {
704             public void propertyChange(java.beans.PropertyChangeEvent JavaDoc evt) {
705                 //System.out.println("1:evt = "+evt+", Property NAME = "+evt.getPropertyName());
706
javax.swing.SwingUtilities.invokeLater(new Runnable JavaDoc() {
707                     public void run() {
708                         initGlobalSizes();
709                         linesComp1.repaint();
710                     }
711                 });
712             }
713         });
714         jEditorPane2.addPropertyChangeListener("font", new java.beans.PropertyChangeListener JavaDoc() {
715             public void propertyChange(java.beans.PropertyChangeEvent JavaDoc evt) {
716                 //System.out.println("2:evt = "+evt+", Property NAME = "+evt.getPropertyName());
717
javax.swing.SwingUtilities.invokeLater(new Runnable JavaDoc() {
718                     public void run() {
719                         initGlobalSizes();
720                         linesComp2.repaint();
721                     }
722                 });
723             }
724         });
725     }
726     
727     public void setSource1(Reader r) throws IOException {
728         //D.deb("setFile("+url+")"); // NOI18N
729
//System.out.println("setFile1("+url+")");
730
EditorKit kit = jEditorPane1.getEditorKit();
731         if (kit == null) throw new IOException("Missing Editor Kit"); // NOI18N
732
Document doc = kit.createDefaultDocument();
733         if (!(doc instanceof StyledDocument)) {
734             doc = new DefaultStyledDocument(new StyleContext());
735             kit = new StyledEditorKit();
736             jEditorPane1.setEditorKit(kit);
737         }
738         try {
739             kit.read(r, doc, 0);
740         } catch (javax.swing.text.BadLocationException JavaDoc e) {
741             throw new IOException("Can not locate the beginning of the document."); // NOI18N
742
} finally {
743             r.close();
744         }
745         kit.install(jEditorPane1);
746         jEditorPane1.setDocument(doc);
747         //jEditorPane1.setPage(url);
748
jEditorPane1.setEditable(false);
749         customizeEditor(jEditorPane1);
750         linesComp1 = new LinesComponent(jEditorPane1);
751         jScrollPane1.setRowHeaderView(linesComp1);
752         jViewport1 = jScrollPane1.getViewport();
753     }
754     
755     public void setSource2(Reader r) throws IOException {
756         //D.deb("setFile("+url+")"); // NOI18N
757
EditorKit kit = jEditorPane2.getEditorKit();
758         if (kit == null) throw new IOException("Missing Editor Kit"); // NOI18N
759
Document doc = kit.createDefaultDocument();
760         if (!(doc instanceof StyledDocument)) {
761             doc = new DefaultStyledDocument(new StyleContext());
762             kit = new StyledEditorKit();
763             jEditorPane2.setEditorKit(kit);
764         }
765         try {
766             kit.read(r, doc, 0);
767         } catch (javax.swing.text.BadLocationException JavaDoc e) {
768             throw new IOException("Can not locate the beginning of the document."); // NOI18N
769
} finally {
770             r.close();
771         }
772         kit.install(jEditorPane2);
773         jEditorPane2.setDocument(doc);
774         //jEditorPane2.setPage(url);
775
jEditorPane2.setEditable(false);
776         
777         customizeEditor(jEditorPane2);
778         linesComp2 = new LinesComponent(jEditorPane2);
779         jScrollPane2.setRowHeaderView(linesComp2);
780         jViewport2 = jScrollPane2.getViewport();
781         // add scrollbar listeners..
782
joinScrollBars();
783     }
784     
785     public void setSource1Title(String JavaDoc title) {
786         fileLabel1.setText(title);
787         // Set the minimum size in 'x' direction to a low value, so that the splitter can be moved to corner locations
788
fileLabel1.setMinimumSize(new Dimension(3, fileLabel1.getMinimumSize().height));
789     }
790     
791     public void setSource2Title(String JavaDoc title) {
792         fileLabel2.setText(title);
793         // Set the minimum size in 'x' direction to a low value, so that the splitter can be moved to corner locations
794
fileLabel2.setMinimumSize(new Dimension(3, fileLabel2.getMinimumSize().height));
795     }
796     
797     public void setMimeType1(String JavaDoc mime) {
798         EditorKit kit = CloneableEditorSupport.getEditorKit(mime);
799         jEditorPane1.setEditorKit(kit);
800         //Document doc = jEditorPane1.getDocument();
801
//if (!(doc instanceof StyledDocument)) jEditorPane1.setDocument(new DefaultStyledDocument());
802
}
803     
804     public void setMimeType2(String JavaDoc mime) {
805         EditorKit kit = CloneableEditorSupport.getEditorKit(mime);
806         jEditorPane2.setEditorKit(kit);
807         //Document doc = jEditorPane2.getDocument();
808
//if (!(doc instanceof StyledDocument)) jEditorPane2.setDocument(new DefaultStyledDocument());
809
}
810     
811     public void setDocument1(Document doc) {
812         if (doc != null) {
813             jEditorPane1.setDocument(doc);
814         }
815     }
816     
817     public void setDocument2(Document doc) {
818         if (doc != null) {
819             jEditorPane2.setDocument(doc);
820         }
821     }
822     
823     String JavaDoc getDocumentText1() {
824         return jEditorPane1.getText();
825     }
826     
827     String JavaDoc getDocumentText2() {
828         return jEditorPane2.getText();
829     }
830     
831     private void setHighlight(StyledDocument doc, int line1, int line2, java.awt.Color JavaDoc color) {
832         //System.out.println("setHighlight(): <"+line1+", "+line2+">, color = "+color); // NOI18N
833
//Style s = doc.addStyle("diff-style("+color+"):1500", null); // NOI18N
834
// SimpleAttributeSet attrSet = new SimpleAttributeSet();
835
// attrSet.addAttribute(StyleConstants.ColorConstants.Background, java.awt.Color.green);
836
//s.addAttribute(StyleConstants.ColorConstants.Background, color);
837
for(int line = line1-1; line < line2; line++) {
838             if (line < 0) continue;
839             try {
840                 int offset = org.openide.text.NbDocument.findLineOffset(doc, line);
841                 //System.out.println("setHighlight(): I got offset = "+offset); // NOI18N
842
if (offset >= 0) {
843                     Style s = doc.getLogicalStyle(offset);
844                     if (s == null) {
845                         //System.out.println("setHighlight(): logical style is NULL"); // NOI18N
846
s = doc.addStyle("diff-style("+color+"):1500", null); // NOI18N
847
}
848                     s.addAttribute(StyleConstants.ColorConstants.Background, color);
849                     doc.setLogicalStyle(offset, s);
850                     //doc.setParagraphAttributes(offset, 1, s, false);
851
}
852             } catch (IndexOutOfBoundsException JavaDoc ex) {
853                 // diagnostics
854
ErrorManager.getDefault().annotate(ex, "#67631 reappreared. Please reopen with details."); // NOI18N
855
ErrorManager.getDefault().notify(ex);
856             }
857         }
858         //doc.setParagraphAttributes(offset, 100, s, true);
859
}
860     
861     private void unhighlight(StyledDocument doc) {
862         int endOffset = doc.getEndPosition().getOffset();
863         int endLine = org.openide.text.NbDocument.findLineNumber(doc, endOffset);
864         Style s = doc.addStyle("diff-style(white):1500", null); // NOI18N
865
s.addAttribute(StyleConstants.ColorConstants.Background, java.awt.Color.white);
866         for(int line = 0; line <= endLine; line++) {
867             int offset = org.openide.text.NbDocument.findLineOffset(doc, line);
868             doc.setLogicalStyle(offset, s);
869         }
870     }
871     
872     public void unhighlightAll() {
873         unhighlight((StyledDocument) jEditorPane1.getDocument());
874         unhighlight((StyledDocument) jEditorPane2.getDocument());
875     }
876     
877     public void highlightRegion1(int line1, int line2, java.awt.Color JavaDoc color) {
878         StyledDocument doc = (StyledDocument) jEditorPane1.getDocument();
879         setHighlight(doc, line1, line2, color);
880     }
881     
882     public void highlightRegion2(int line1, int line2, java.awt.Color JavaDoc color) {
883         StyledDocument doc = (StyledDocument) jEditorPane2.getDocument();
884         setHighlight(doc, line1, line2, color);
885     }
886     
887     private void addEmptyLines(StyledDocument doc, int line, int numLines) {
888         int lastOffset = doc.getEndPosition().getOffset();
889         int totLines = org.openide.text.NbDocument.findLineNumber(doc, lastOffset);
890         //int totLines = doc.getDefaultRootElement().getElementIndex(lastOffset);
891
int offset = lastOffset-1;
892         if (line <= totLines) {
893             offset = org.openide.text.NbDocument.findLineOffset(doc, line);
894             //offset = doc.getDefaultRootElement().getElement(line).getStartOffset();
895
}
896         //int endOffset = doc.getEndPosition().getOffset();
897
//if (offset > endOffset) offset = endOffset;
898
String JavaDoc insStr = strCharacters('\n', numLines);
899         try {
900             doc.insertString(offset, insStr, null);
901         } catch (BadLocationException e) {
902             org.openide.ErrorManager.getDefault().notify(e);
903         }
904         //initScrollBars();
905
}
906     
907     public void addEmptyLines1(int line, int numLines) {
908         StyledDocument doc = (StyledDocument) jEditorPane1.getDocument();
909         //System.out.println("addEmptyLines1: line = "+line+", numLines = "+numLines); // NOI18N
910
addEmptyLines(doc, line, numLines);
911         linesComp1.addEmptyLines(line, numLines);
912     }
913     
914     public void addEmptyLines2(int line, int numLines) {
915         StyledDocument doc = (StyledDocument) jEditorPane2.getDocument();
916         //System.out.println("addEmptyLines2: line = "+line+", numLines = "+numLines); // NOI18N
917
addEmptyLines(doc, line, numLines);
918         linesComp2.addEmptyLines(line, numLines);
919     }
920     
921     
922     private javax.swing.JViewport JavaDoc jViewport1;
923     private javax.swing.JViewport JavaDoc jViewport2;
924     //private javax.swing.JScrollBar jScrollBar1 = new javax.swing.JScrollBar();
925
//private javax.swing.JScrollBar jScrollBar2 = new javax.swing.JScrollBar();
926
//private javax.swing.JScrollBar jScrollBar3 = new javax.swing.JScrollBar();
927
//private javax.swing.JEditorPane jEditorPane1 = new JEditorPane();
928
//private javax.swing.JEditorPane jEditorPane2 = new JEditorPane();
929
// private Boolean lineNumbersVisible = Boolean.FALSE;
930

931     // Variables declaration - do not modify//GEN-BEGIN:variables
932
final javax.swing.JPanel JavaDoc commandPanel = new javax.swing.JPanel JavaDoc();
933     final javax.swing.JPanel JavaDoc editorPanel = new javax.swing.JPanel JavaDoc();
934     final javax.swing.JLabel JavaDoc fileLabel1 = new javax.swing.JLabel JavaDoc();
935     final javax.swing.JLabel JavaDoc fileLabel2 = new javax.swing.JLabel JavaDoc();
936     final javax.swing.JPanel JavaDoc filePanel1 = new javax.swing.JPanel JavaDoc();
937     final javax.swing.JPanel JavaDoc filePanel2 = new javax.swing.JPanel JavaDoc();
938     final org.netbeans.modules.diff.builtin.visualizer.DEditorPane jEditorPane1 = new DEditorPane();
939     final org.netbeans.modules.diff.builtin.visualizer.DEditorPane jEditorPane2 = new DEditorPane();
940     final javax.swing.JScrollPane JavaDoc jScrollPane1 = new javax.swing.JScrollPane JavaDoc();
941     final javax.swing.JScrollPane JavaDoc jScrollPane2 = new javax.swing.JScrollPane JavaDoc();
942     final javax.swing.JSplitPane JavaDoc jSplitPane1 = new javax.swing.JSplitPane JavaDoc();
943     final javax.swing.JButton JavaDoc nextButton = new javax.swing.JButton JavaDoc();
944     final javax.swing.JButton JavaDoc prevButton = new javax.swing.JButton JavaDoc();
945     // End of variables declaration//GEN-END:variables
946

947     /* scroll pane with unvisible scroll bar
948      * if necessary can be solved this way, however easier approach was chosen:
949      * jScrollPane1.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0));
950      * If the easier approach stop to work, this class can be used instead.
951     private static final class JScrollPaneWithUnvisibleVerticalScrollBar extends JScrollPane {
952         
953         public JScrollBar createVerticalScrollBar() {
954             return new UnvisibleScrollBar(JScrollBar.VERTICAL);
955         }
956         
957         private final class UnvisibleScrollBar extends JScrollPane.ScrollBar {
958             
959             public UnvisibleScrollBar(int orientation) {
960                 super(orientation);
961             }
962             
963             public boolean contains(int x, int y) {
964                 return false;
965             }
966             
967             public Rectangle getBounds() {
968                 return new Rectangle(0, 0, 0, 0);
969             }
970             
971             public Rectangle getBounds(Rectangle rv) {
972                 if (rv == null) rv = new Rectangle(0, 0, 0, 0);
973                 else rv.setBounds(0, 0, 0, 0);
974                 return rv;
975             }
976             
977             public int getHeight() {
978                 return 0;
979             }
980             
981             public int getWidth() {
982                 return 0;
983             }
984             
985             public Dimension getSize() {
986                 return new Dimension(0, 0);
987             }
988             
989             public Dimension getSize(Dimension rv) {
990                 if (rv == null) rv = new Dimension(0, 0);
991                 else rv.setSize(0, 0);
992                 return rv;
993             }
994             
995             public Dimension getPreferredSize() {
996                 return new Dimension(0, 0);
997             }
998         }
999     }
1000     */

1001    
1002}
1003
Popular Tags