directory-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From fel...@apache.org
Subject svn commit: r592089 [2/5] - in /directory/sandbox/felixk/studio-ldifeditor: ./ META-INF/ src/ src/main/ src/main/java/ src/main/java/org/ src/main/java/org/apache/ src/main/java/org/apache/directory/ src/main/java/org/apache/directory/studio/ src/main/...
Date Mon, 05 Nov 2007 17:04:59 GMT
Added: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/dialogs/preferences/LdifEditorSyntaxColoringPreferencePage.java
URL: http://svn.apache.org/viewvc/directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/dialogs/preferences/LdifEditorSyntaxColoringPreferencePage.java?rev=592089&view=auto
==============================================================================
--- directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/dialogs/preferences/LdifEditorSyntaxColoringPreferencePage.java (added)
+++ directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/dialogs/preferences/LdifEditorSyntaxColoringPreferencePage.java Mon Nov  5 09:04:52 2007
@@ -0,0 +1,472 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *  
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *  
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License. 
+ *  
+ */
+
+package org.apache.directory.studio.ldifeditor.dialogs.preferences;
+
+
+import org.apache.directory.studio.ldapbrowser.common.widgets.BaseWidgetUtils;
+import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants;
+import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
+import org.apache.directory.studio.ldapbrowser.core.model.ldif.LdifFile;
+import org.apache.directory.studio.ldifeditor.LdifEditorActivator;
+import org.apache.directory.studio.ldifeditor.LdifEditorConstants;
+import org.apache.directory.studio.ldifeditor.editor.ILdifEditor;
+import org.apache.directory.studio.ldifeditor.widgets.LdifEditorWidget;
+import org.eclipse.jface.preference.ColorSelector;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.PreferenceConverter;
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.jface.text.TextAttribute;
+import org.eclipse.jface.util.IPropertyChangeListener;
+import org.eclipse.jface.util.PropertyChangeEvent;
+import org.eclipse.jface.viewers.ArrayContentProvider;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.RGB;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+
+public class LdifEditorSyntaxColoringPreferencePage extends PreferencePage implements IWorkbenchPreferencePage,
+    ILdifEditor
+{
+
+    private static final String LDIF_INITIAL = "" + "# Content record" + BrowserCoreConstants.LINE_SEPARATOR
+        + "dn: cn=content record" + BrowserCoreConstants.LINE_SEPARATOR + "objectClass: person"
+        + BrowserCoreConstants.LINE_SEPARATOR + "cn: content record" + BrowserCoreConstants.LINE_SEPARATOR
+        + "cn;lang-ja:: 5Za25qWt6YOo" + BrowserCoreConstants.LINE_SEPARATOR + "" + BrowserCoreConstants.LINE_SEPARATOR
+
+        + "# Add record with control" + BrowserCoreConstants.LINE_SEPARATOR + "dn: cn=add record"
+        + BrowserCoreConstants.LINE_SEPARATOR + "control: 1.2.3.4 true: controlValue"
+        + BrowserCoreConstants.LINE_SEPARATOR + "changetype: add" + BrowserCoreConstants.LINE_SEPARATOR
+        + "objectClass: person" + BrowserCoreConstants.LINE_SEPARATOR + "cn: add record"
+        + BrowserCoreConstants.LINE_SEPARATOR + "" + BrowserCoreConstants.LINE_SEPARATOR
+
+        + "# Modify record" + BrowserCoreConstants.LINE_SEPARATOR + "dn: cn=modify record"
+        + BrowserCoreConstants.LINE_SEPARATOR + "changetype: modify" + BrowserCoreConstants.LINE_SEPARATOR + "add: cn"
+        + BrowserCoreConstants.LINE_SEPARATOR + "cn: modify record" + BrowserCoreConstants.LINE_SEPARATOR + "-"
+        + BrowserCoreConstants.LINE_SEPARATOR + "delete: cn" + BrowserCoreConstants.LINE_SEPARATOR + "-"
+        + BrowserCoreConstants.LINE_SEPARATOR + "replace: cn" + BrowserCoreConstants.LINE_SEPARATOR
+        + "cn: modify record" + BrowserCoreConstants.LINE_SEPARATOR + "-" + BrowserCoreConstants.LINE_SEPARATOR + ""
+        + BrowserCoreConstants.LINE_SEPARATOR
+
+        + "# Delete record" + BrowserCoreConstants.LINE_SEPARATOR + "dn: cn=delete record"
+        + BrowserCoreConstants.LINE_SEPARATOR + "changetype: delete" + BrowserCoreConstants.LINE_SEPARATOR + ""
+        + BrowserCoreConstants.LINE_SEPARATOR
+
+        + "# Modify DN record" + BrowserCoreConstants.LINE_SEPARATOR + "dn: cn=moddn record"
+        + BrowserCoreConstants.LINE_SEPARATOR + "changetype: moddn" + BrowserCoreConstants.LINE_SEPARATOR
+        + "newrdn: cn=new rdn" + BrowserCoreConstants.LINE_SEPARATOR + "deleteoldrdn: 1"
+        + BrowserCoreConstants.LINE_SEPARATOR + "newsuperior: cn=new superior" + BrowserCoreConstants.LINE_SEPARATOR
+        + "" + BrowserCoreConstants.LINE_SEPARATOR;
+
+    private LdifEditorWidget ldifEditorWidget;
+
+    private SyntaxItem[] syntaxItems;
+
+    private ColorSelector colorSelector;
+
+    private Button boldCheckBox;
+
+    private Button italicCheckBox;
+
+    private Button underlineCheckBox;
+
+    private Button strikethroughCheckBox;
+
+    private TableViewer syntaxItemViewer;
+
+    private class SyntaxItem
+    {
+        String displayName;
+
+        String key;
+
+        RGB rgb;
+
+        boolean bold;
+
+        boolean italic;
+
+        boolean strikethrough;
+
+        boolean underline;
+
+
+        SyntaxItem( String displayName, String key )
+        {
+            this.displayName = displayName;
+            this.key = key;
+            loadPreferences();
+        }
+
+
+        int getStyle()
+        {
+            int style = SWT.NORMAL;
+            if ( bold )
+                style |= SWT.BOLD;
+            if ( italic )
+                style |= SWT.ITALIC;
+            if ( strikethrough )
+                style |= TextAttribute.STRIKETHROUGH;
+            if ( underline )
+                style |= TextAttribute.UNDERLINE;
+            return style;
+        }
+
+
+        void setStyle( int style )
+        {
+            this.bold = ( style & SWT.BOLD ) != SWT.NORMAL;
+            this.italic = ( style & SWT.ITALIC ) != SWT.NORMAL;
+            this.strikethrough = ( style & TextAttribute.STRIKETHROUGH ) != SWT.NORMAL;
+            this.underline = ( style & TextAttribute.UNDERLINE ) != SWT.NORMAL;
+        }
+
+
+        void loadPreferences()
+        {
+            IPreferenceStore store = LdifEditorActivator.getDefault().getPreferenceStore();
+            this.rgb = PreferenceConverter.getColor( store, key
+                + LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX );
+            int style = store.getInt( key + LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX );
+            setStyle( style );
+        }
+
+
+        void savePreferences()
+        {
+            IPreferenceStore store = LdifEditorActivator.getDefault().getPreferenceStore();
+            PreferenceConverter.setValue( store, key + LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX, rgb );
+            store.setValue( key + LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX, getStyle() );
+        }
+
+
+        void loadDefaultPreferences()
+        {
+            IPreferenceStore store = LdifEditorActivator.getDefault().getPreferenceStore();
+            this.rgb = PreferenceConverter.getDefaultColor( store, key
+                + LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_RGB_SUFFIX );
+            int style = store.getDefaultInt( key + LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_STYLE_SUFFIX );
+            setStyle( style );
+        }
+
+
+        public String toString()
+        {
+            return displayName;
+        }
+    }
+
+
+    public LdifEditorSyntaxColoringPreferencePage()
+    {
+        super( "Syntax Coloring" );
+        super.setPreferenceStore( LdifEditorActivator.getDefault().getPreferenceStore() );
+        // super.setDescription("");
+    }
+
+
+    public void init( IWorkbench workbench )
+    {
+    }
+
+
+    public void dispose()
+    {
+        ldifEditorWidget.dispose();
+        super.dispose();
+    }
+
+
+    protected Control createContents( Composite parent )
+    {
+
+        Composite composite = new Composite( parent, SWT.NONE );
+        GridLayout layout = new GridLayout( 1, false );
+        layout.marginWidth = 0;
+        layout.marginHeight = 0;
+        layout.marginLeft = 0;
+        layout.marginRight = 0;
+        layout.marginTop = 0;
+        layout.marginBottom = 0;
+        composite.setLayout( layout );
+        GridData gd = new GridData( GridData.FILL_HORIZONTAL );
+        composite.setLayoutData( gd );
+
+        BaseWidgetUtils.createSpacer( composite, 1 );
+        BaseWidgetUtils.createSpacer( composite, 1 );
+
+        createSyntaxPage( composite );
+        createPreviewer( composite );
+
+        syntaxItems = new SyntaxItem[10];
+        syntaxItems[0] = new SyntaxItem( "Comments", LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_COMMENT );
+        syntaxItems[1] = new SyntaxItem( "DN", LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_DN );
+        syntaxItems[2] = new SyntaxItem( "Attribute Descriptions",
+            LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_ATTRIBUTE );
+        syntaxItems[3] = new SyntaxItem( "Value Types", LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_VALUETYPE );
+        syntaxItems[4] = new SyntaxItem( "Values", LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_VALUE );
+        syntaxItems[5] = new SyntaxItem( "Keywords (w/o changetypes)",
+            LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_KEYWORD );
+        syntaxItems[6] = new SyntaxItem( "Changetype 'add'",
+            LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEADD );
+        syntaxItems[7] = new SyntaxItem( "Changetype 'modify'",
+            LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEMODIFY );
+        syntaxItems[8] = new SyntaxItem( "Changetype 'delete'",
+            LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEDELETE );
+        syntaxItems[9] = new SyntaxItem( "Changetype 'moddn'",
+            LdifEditorConstants.PREFERENCE_LDIFEDITOR_SYNTAX_CHANGETYPEMODDN );
+        syntaxItemViewer.setInput( syntaxItems );
+        syntaxItemViewer.setSelection( new StructuredSelection( syntaxItems[0] ) );
+
+        return composite;
+    }
+
+
+    private void createSyntaxPage( Composite parent )
+    {
+
+        BaseWidgetUtils.createLabel( parent, "Element:", 1 );
+
+        Composite editorComposite = BaseWidgetUtils.createColumnContainer( parent, 2, 1 );
+
+        syntaxItemViewer = new TableViewer( editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER
+            | SWT.FULL_SELECTION );
+        syntaxItemViewer.setLabelProvider( new LabelProvider() );
+        syntaxItemViewer.setContentProvider( new ArrayContentProvider() );
+        // colorListViewer.setSorter(new WorkbenchViewerSorter());
+        GridData gd = new GridData( GridData.FILL_BOTH );
+        gd.heightHint = convertHeightInCharsToPixels( 5 );
+        syntaxItemViewer.getControl().setLayoutData( gd );
+
+        Composite stylesComposite = BaseWidgetUtils.createColumnContainer( editorComposite, 1, 1 );
+        stylesComposite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
+        Composite colorComposite = BaseWidgetUtils.createColumnContainer( stylesComposite, 2, 1 );
+        BaseWidgetUtils.createLabel( colorComposite, "Color:", 1 );
+        colorSelector = new ColorSelector( colorComposite );
+        boldCheckBox = BaseWidgetUtils.createCheckbox( stylesComposite, "Bold", 1 );
+        italicCheckBox = BaseWidgetUtils.createCheckbox( stylesComposite, "Italic", 1 );
+        strikethroughCheckBox = BaseWidgetUtils.createCheckbox( stylesComposite, "Strikethrough", 1 );
+        underlineCheckBox = BaseWidgetUtils.createCheckbox( stylesComposite, "Underline", 1 );
+
+        syntaxItemViewer.addSelectionChangedListener( new ISelectionChangedListener()
+        {
+            public void selectionChanged( SelectionChangedEvent event )
+            {
+                handleSyntaxItemViewerSelectionEvent();
+            }
+        } );
+        colorSelector.addListener( new IPropertyChangeListener()
+        {
+            public void propertyChange( PropertyChangeEvent event )
+            {
+                handleColorSelectorEvent();
+            }
+        } );
+        boldCheckBox.addSelectionListener( new SelectionAdapter()
+        {
+            public void widgetSelected( SelectionEvent e )
+            {
+                handleBoldSelectionEvent();
+            }
+        } );
+        italicCheckBox.addSelectionListener( new SelectionAdapter()
+        {
+            public void widgetSelected( SelectionEvent e )
+            {
+                handleItalicSelectionEvent();
+            }
+        } );
+        strikethroughCheckBox.addSelectionListener( new SelectionAdapter()
+        {
+            public void widgetSelected( SelectionEvent e )
+            {
+                handleStrikethroughSelectionEvent();
+            }
+        } );
+        underlineCheckBox.addSelectionListener( new SelectionAdapter()
+        {
+            public void widgetSelected( SelectionEvent e )
+            {
+                handleUnderlineSelectionEvent();
+            }
+        } );
+
+    }
+
+
+    private void handleUnderlineSelectionEvent()
+    {
+        SyntaxItem item = getSyntaxItem();
+        if ( item != null )
+        {
+            item.underline = underlineCheckBox.getSelection();
+            setTextAttribute( item );
+        }
+    }
+
+
+    private void handleStrikethroughSelectionEvent()
+    {
+        SyntaxItem item = getSyntaxItem();
+        if ( item != null )
+        {
+            item.strikethrough = strikethroughCheckBox.getSelection();
+            setTextAttribute( item );
+        }
+    }
+
+
+    private void handleItalicSelectionEvent()
+    {
+        SyntaxItem item = getSyntaxItem();
+        if ( item != null )
+        {
+            item.italic = italicCheckBox.getSelection();
+            setTextAttribute( item );
+        }
+    }
+
+
+    private void handleBoldSelectionEvent()
+    {
+        SyntaxItem item = getSyntaxItem();
+        if ( item != null )
+        {
+            item.bold = boldCheckBox.getSelection();
+            setTextAttribute( item );
+        }
+    }
+
+
+    private void handleColorSelectorEvent()
+    {
+        SyntaxItem item = getSyntaxItem();
+        if ( item != null )
+        {
+            item.rgb = colorSelector.getColorValue();
+            setTextAttribute( item );
+        }
+    }
+
+
+    private void handleSyntaxItemViewerSelectionEvent()
+    {
+        SyntaxItem item = getSyntaxItem();
+        if ( item != null )
+        {
+            colorSelector.setColorValue( item.rgb );
+            boldCheckBox.setSelection( item.bold );
+            italicCheckBox.setSelection( item.italic );
+            strikethroughCheckBox.setSelection( item.strikethrough );
+            underlineCheckBox.setSelection( item.underline );
+        }
+    }
+
+
+    private SyntaxItem getSyntaxItem()
+    {
+        SyntaxItem item = ( SyntaxItem ) ( ( IStructuredSelection ) syntaxItemViewer.getSelection() ).getFirstElement();
+        return item;
+    }
+
+
+    private void setTextAttribute( SyntaxItem item )
+    {
+        ldifEditorWidget.getSourceViewerConfiguration().setTextAttribute( item.key, item.rgb, item.getStyle() );
+
+        int topIndex = ldifEditorWidget.getSourceViewer().getTopIndex();
+        // ldifEditorWidget.getSourceViewer().getDocument().set("");
+        ldifEditorWidget.getSourceViewer().getDocument().set( LDIF_INITIAL );
+        ldifEditorWidget.getSourceViewer().setTopIndex( topIndex );
+    }
+
+
+    private void createPreviewer( Composite parent )
+    {
+
+        BaseWidgetUtils.createLabel( parent, "Preview:", 1 );
+
+        ldifEditorWidget = new LdifEditorWidget( null, LDIF_INITIAL, false );
+        ldifEditorWidget.createWidget( parent );
+        ldifEditorWidget.getSourceViewer().setEditable( false );
+
+        GridData gd = new GridData( GridData.FILL_BOTH );
+        gd.widthHint = convertWidthInCharsToPixels( 20 );
+        gd.heightHint = convertHeightInCharsToPixels( 5 );
+        ldifEditorWidget.getSourceViewer().getControl().setLayoutData( gd );
+
+    }
+
+
+    public IBrowserConnection getConnection()
+    {
+        return ldifEditorWidget.getConnection();
+    }
+
+
+    public LdifFile getLdifModel()
+    {
+        return ldifEditorWidget.getLdifModel();
+    }
+
+
+    public boolean performOk()
+    {
+        for ( int i = 0; i < syntaxItems.length; i++ )
+        {
+            syntaxItems[i].savePreferences();
+        }
+        return true;
+    }
+
+
+    protected void performDefaults()
+    {
+        for ( int i = 0; i < syntaxItems.length; i++ )
+        {
+            syntaxItems[i].loadDefaultPreferences();
+            setTextAttribute( syntaxItems[i] );
+        }
+        handleSyntaxItemViewerSelectionEvent();
+        super.performDefaults();
+    }
+
+
+    public Object getAdapter( Class adapter )
+    {
+        return null;
+    }
+
+}

Propchange: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/dialogs/preferences/LdifEditorSyntaxColoringPreferencePage.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/dialogs/preferences/LdifEditorTemplatesPreferencePage.java
URL: http://svn.apache.org/viewvc/directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/dialogs/preferences/LdifEditorTemplatesPreferencePage.java?rev=592089&view=auto
==============================================================================
--- directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/dialogs/preferences/LdifEditorTemplatesPreferencePage.java (added)
+++ directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/dialogs/preferences/LdifEditorTemplatesPreferencePage.java Mon Nov  5 09:04:52 2007
@@ -0,0 +1,39 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *  
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *  
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License. 
+ *  
+ */
+
+package org.apache.directory.studio.ldifeditor.dialogs.preferences;
+
+
+import org.apache.directory.studio.ldifeditor.LdifEditorActivator;
+import org.eclipse.ui.texteditor.templates.TemplatePreferencePage;
+
+
+public class LdifEditorTemplatesPreferencePage extends TemplatePreferencePage
+{
+
+    public LdifEditorTemplatesPreferencePage()
+    {
+        super();
+        super.setPreferenceStore( LdifEditorActivator.getDefault().getPreferenceStore() );
+        super.setTemplateStore( LdifEditorActivator.getDefault().getLdifTemplateStore() );
+        super.setContextTypeRegistry( LdifEditorActivator.getDefault().getLdifTemplateContextTypeRegistry() );
+    }
+
+}

Propchange: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/dialogs/preferences/LdifEditorTemplatesPreferencePage.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/ExecuteLdifAction.java
URL: http://svn.apache.org/viewvc/directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/ExecuteLdifAction.java?rev=592089&view=auto
==============================================================================
--- directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/ExecuteLdifAction.java (added)
+++ directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/ExecuteLdifAction.java Mon Nov  5 09:04:52 2007
@@ -0,0 +1,75 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *  
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *  
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License. 
+ *  
+ */
+
+package org.apache.directory.studio.ldifeditor.editor;
+
+
+import org.apache.directory.studio.ldapbrowser.core.jobs.ExecuteLdifJob;
+import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
+import org.apache.directory.studio.ldifeditor.LdifEditorActivator;
+import org.apache.directory.studio.ldifeditor.LdifEditorConstants;
+import org.eclipse.jface.action.Action;
+
+
+/**
+ * This Action executes LDIF code.
+ *
+ * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
+ * @version $Rev$, $Date$
+ */
+public class ExecuteLdifAction extends Action
+{
+    private LdifEditor editor;
+
+
+    /**
+     * Creates a new instance of ExecuteLdifAction.
+     *
+     * @param editor
+     *      the attached editor
+     */
+    public ExecuteLdifAction( LdifEditor editor )
+    {
+        super( "Execute LDIF", LdifEditorActivator.getDefault().getImageDescriptor( LdifEditorConstants.IMG_EXECUTE ) );
+        super.setToolTipText( "Execute LDIF" );
+        this.editor = editor;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void run()
+    {
+
+        IBrowserConnection connection = editor.getConnection();
+        String ldif = editor.getLdifModel().toRawString();
+
+        new ExecuteLdifJob( connection, ldif, true ).execute();
+
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public boolean isEnabled()
+    {
+        return editor != null && editor.getConnection() != null;
+    }
+}

Propchange: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/ExecuteLdifAction.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/ILdifEditor.java
URL: http://svn.apache.org/viewvc/directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/ILdifEditor.java?rev=592089&view=auto
==============================================================================
--- directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/ILdifEditor.java (added)
+++ directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/ILdifEditor.java Mon Nov  5 09:04:52 2007
@@ -0,0 +1,54 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *  
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *  
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License. 
+ *  
+ */
+
+package org.apache.directory.studio.ldifeditor.editor;
+
+
+import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
+import org.apache.directory.studio.ldapbrowser.core.model.ldif.LdifFile;
+
+import org.eclipse.core.runtime.IAdaptable;
+
+
+/**
+ * This interface represents the LDIF Editor.
+ * 
+ * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
+ * @version $Rev$, $Date$
+ */
+public interface ILdifEditor extends IAdaptable
+{
+    /**
+     * Gets the LDIF Model
+     *
+     * @return
+     *      the LDIF Model
+     */
+    public LdifFile getLdifModel();
+
+
+    /**
+     * Gets the Connection
+     * 
+     * @return
+     *      the Connection
+     */
+    public IBrowserConnection getConnection();
+}

Propchange: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/ILdifEditor.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifDocumentProvider.java
URL: http://svn.apache.org/viewvc/directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifDocumentProvider.java?rev=592089&view=auto
==============================================================================
--- directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifDocumentProvider.java (added)
+++ directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifDocumentProvider.java Mon Nov  5 09:04:52 2007
@@ -0,0 +1,469 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *  
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *  
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License. 
+ *  
+ */
+
+package org.apache.directory.studio.ldifeditor.editor;
+
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants;
+import org.apache.directory.studio.ldapbrowser.core.model.ldif.LdifFile;
+import org.apache.directory.studio.ldapbrowser.core.model.ldif.container.LdifContainer;
+import org.apache.directory.studio.ldapbrowser.core.model.ldif.container.LdifRecord;
+import org.apache.directory.studio.ldapbrowser.core.model.ldif.parser.LdifParser;
+import org.apache.directory.studio.ldifeditor.LdifEditorActivator;
+import org.apache.directory.studio.ldifeditor.editor.text.LdifExternalAnnotationModel;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.operation.IRunnableContext;
+import org.eclipse.jface.text.Document;
+import org.eclipse.jface.text.DocumentEvent;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IDocumentListener;
+import org.eclipse.jface.text.Region;
+import org.eclipse.jface.text.TextUtilities;
+import org.eclipse.jface.text.source.IAnnotationModel;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IPathEditorInput;
+import org.eclipse.ui.texteditor.AbstractDocumentProvider;
+
+
+/**
+ * This class implements the LDIF Document Provider.
+ * This class is used to share a LDIF Document and listen on document modifications.
+ *
+ * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
+ * @version $Rev$, $Date$
+ */
+public class LdifDocumentProvider extends AbstractDocumentProvider implements IDocumentListener
+{
+
+    private final LdifParser ldifParser;
+
+    private final LdifDocumentSetupParticipant ldifDocumentSetupParticipant;
+
+    private LdifFile ldifModel;
+
+
+    /**
+     * Creates a new instance of LdifDocumentProvider.
+     */
+    public LdifDocumentProvider()
+    {
+        super();
+        this.ldifParser = new LdifParser();
+        this.ldifDocumentSetupParticipant = new LdifDocumentSetupParticipant();
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public IDocument getDocument( Object element )
+    {
+        IDocument document = super.getDocument( element );
+        return document;
+    }
+
+
+    /**
+     * Gets the LDIF Model
+     *
+     * @return
+     *      the LDIF Model
+     */
+    public LdifFile getLdifModel()
+    {
+        return ldifModel;
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public void documentAboutToBeChanged( DocumentEvent event )
+    {
+    }
+
+
+    /**
+     * Update the LDIF Model.
+     */
+    public void documentChanged( DocumentEvent event )
+    {
+        try
+        {
+            int changeOffset = event.getOffset();
+            int replacedTextLength = event.getLength();
+            int insertedTextLength = event.getText() != null ? event.getText().length() : 0;
+            IDocument document = event.getDocument();
+            // Region changeRegion = new Region(changeOffset,
+            // replacedTextLength);
+            Region changeRegion = new Region( changeOffset - BrowserCoreConstants.LINE_SEPARATOR.length(),
+                replacedTextLength + ( 2 * BrowserCoreConstants.LINE_SEPARATOR.length() ) );
+
+            // get containers to replace (from changeOffset till
+            // changeOffset+replacedTextLength, check end of record)
+            List<LdifContainer> oldContainerList = new ArrayList<LdifContainer>();
+            LdifContainer[] containers = this.ldifModel.getContainers();
+            for ( int i = 0; i < containers.length; i++ )
+            {
+
+                Region containerRegion = new Region( containers[i].getOffset(), containers[i].getLength() );
+
+                boolean changeOffsetAtEOF = i == containers.length - 1
+                    && changeOffset >= containerRegion.getOffset() + containerRegion.getLength();
+
+                if ( TextUtilities.overlaps( containerRegion, changeRegion ) || changeOffsetAtEOF )
+                {
+
+                    // remember index
+                    int index = i;
+
+                    // add invalid containers and non-records before overlap
+                    i--;
+                    for ( ; i >= 0; i-- )
+                    {
+                        if ( !containers[i].isValid() || !( containers[i] instanceof LdifRecord ) )
+                        {
+                            oldContainerList.add( 0, containers[i] );
+                        }
+                        else
+                        {
+                            break;
+                        }
+                    }
+
+                    // add all overlapping containers
+                    i = index;
+                    for ( ; i < containers.length; i++ )
+                    {
+                        containerRegion = new Region( containers[i].getOffset(), containers[i].getLength() );
+                        if ( TextUtilities.overlaps( containerRegion, changeRegion ) || changeOffsetAtEOF )
+                        {
+                            oldContainerList.add( containers[i] );
+                        }
+                        else
+                        {
+                            break;
+                        }
+                    }
+
+                    // add invalid containers and non-records after overlap
+                    for ( ; i < containers.length; i++ )
+                    {
+                        if ( !containers[i].isValid() || !( containers[i] instanceof LdifRecord )
+                            || !( oldContainerList.get( oldContainerList.size() - 1 ) instanceof LdifRecord ) )
+                        {
+                            oldContainerList.add( containers[i] );
+                        }
+                        else
+                        {
+                            break;
+                        }
+                    }
+                }
+            }
+            LdifContainer[] oldContainers = ( LdifContainer[] ) oldContainerList
+                .toArray( new LdifContainer[oldContainerList.size()] );
+            int oldCount = oldContainers.length;
+            int oldOffset = oldCount > 0 ? oldContainers[0].getOffset() : 0;
+            int oldLength = oldCount > 0 ? ( oldContainers[oldContainers.length - 1].getOffset()
+                + oldContainers[oldContainers.length - 1].getLength() - oldContainers[0].getOffset() ) : 0;
+
+            // get new content
+            int newOffset = oldOffset;
+            int newLength = oldLength - replacedTextLength + insertedTextLength;
+            String textToParse = document.get( newOffset, newLength );
+
+            // parse partion content to containers (offset=0)
+            LdifFile newModel = this.ldifParser.parse( textToParse );
+            LdifContainer[] newContainers = newModel.getContainers();
+
+            // replace old containers with new containers
+            // must adjust offsets of all following containers in model
+            this.ldifModel.replace( oldContainers, newContainers );
+
+        }
+        catch ( Exception e )
+        {
+            e.printStackTrace();
+        }
+
+    }
+
+
+    /**
+     * Creates an LDIF annotation model.
+     */
+    protected IAnnotationModel createAnnotationModel( Object element ) throws CoreException
+    {
+        return new LdifExternalAnnotationModel();
+    }
+
+
+    /**
+     * Tries to read the file pointed at by <code>input</code> if it is an
+     * <code>IPathEditorInput</code>. If the file does not exist, <code>true</code>
+     * is returned.
+     *  
+     * @param document the document to fill with the contents of <code>input</code>
+     * @param input the editor input
+     * @return <code>true</code> if setting the content was successful or no file exists, <code>false</code> otherwise
+     * @throws CoreException if reading the file fails
+     */
+    private boolean setDocumentContent( IDocument document, IEditorInput input ) throws CoreException
+    {
+        // TODO: handle encoding
+        Reader reader;
+        try
+        {
+            if ( input instanceof IPathEditorInput )
+            {
+                reader = new FileReader( ( ( IPathEditorInput ) input ).getPath().toFile() );
+            }
+            else
+            {
+                return false;
+            }
+        }
+        catch ( FileNotFoundException e )
+        {
+            // return empty document and save later
+            return true;
+        }
+
+        try
+        {
+            setDocumentContent( document, reader );
+            return true;
+        }
+        catch ( IOException e )
+        {
+            throw new CoreException( new Status( IStatus.ERROR, LdifEditorActivator.PLUGIN_ID, IStatus.OK,
+                "error reading file", e ) ); //$NON-NLS-1$
+        }
+    }
+
+
+    /**
+     * Reads in document content from a reader and fills <code>document</code>
+     * 
+     * @param document the document to fill
+     * @param reader the source
+     * @throws IOException if reading fails
+     */
+    private void setDocumentContent( IDocument document, Reader reader ) throws IOException
+    {
+        Reader in = new BufferedReader( reader );
+        try
+        {
+            StringBuffer buffer = new StringBuffer( 512 );
+            char[] readBuffer = new char[512];
+            int n = in.read( readBuffer );
+            while ( n > 0 )
+            {
+                buffer.append( readBuffer, 0, n );
+                n = in.read( readBuffer );
+            }
+
+            document.set( buffer.toString() );
+
+        }
+        finally
+        {
+            in.close();
+        }
+    }
+
+
+    /**
+     * Set up the document: partitioning and incremental parser
+     * 
+     * @param document the new document
+     */
+    private void setupDocument( IDocument document )
+    {
+
+        // setup document partitioning
+        ldifDocumentSetupParticipant.setup( document );
+
+        // initial parsing of whole document
+        this.ldifModel = this.ldifParser.parse( document.get() );
+
+        // add listener for incremental parsing
+        document.addDocumentListener( this );
+
+    }
+
+
+    /**
+     * Remove document listener.
+     */
+    protected void disposeElementInfo( Object element, ElementInfo info )
+    {
+        IDocument document = info.fDocument;
+        document.removeDocumentListener( this );
+
+        super.disposeElementInfo( element, info );
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    protected IDocument createDocument( Object element ) throws CoreException
+    {
+        if ( element instanceof IEditorInput )
+        {
+            IDocument document = new Document();
+            if ( setDocumentContent( document, ( IEditorInput ) element ) )
+            {
+                setupDocument( document );
+            }
+            return document;
+        }
+
+        return null;
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    protected void doSaveDocument( IProgressMonitor monitor, Object element, IDocument document, boolean overwrite )
+        throws CoreException
+    {
+
+        if ( element instanceof IPathEditorInput )
+        {
+            IPathEditorInput pei = ( IPathEditorInput ) element;
+            IPath path = pei.getPath();
+            File file = path.toFile();
+
+            try
+            {
+                file.createNewFile();
+
+                if ( file.exists() )
+                {
+                    if ( file.canWrite() )
+                    {
+                        Writer writer = new FileWriter( file );
+                        writeDocumentContent( document, writer, monitor );
+                    }
+                    else
+                    {
+                        throw new CoreException( new Status( IStatus.ERROR,
+                            "org.eclipse.ui.examples.rcp.texteditor", IStatus.OK, "file is read-only", null ) ); //$NON-NLS-1$ //$NON-NLS-2$
+                    }
+                }
+                else
+                {
+                    throw new CoreException( new Status( IStatus.ERROR,
+                        "org.eclipse.ui.examples.rcp.texteditor", IStatus.OK, "error creating file", null ) ); //$NON-NLS-1$ //$NON-NLS-2$
+                }
+            }
+            catch ( IOException e )
+            {
+                throw new CoreException( new Status( IStatus.ERROR,
+                    "org.eclipse.ui.examples.rcp.texteditor", IStatus.OK, "error when saving file", e ) ); //$NON-NLS-1$ //$NON-NLS-2$
+            }
+
+        }
+    }
+
+
+    /**
+     * Saves the document contents to a stream.
+     * 
+     * @param document the document to save
+     * @param writer the stream to save it to
+     * @param monitor a progress monitor to report progress
+     * @throws IOException if writing fails
+     */
+    private void writeDocumentContent( IDocument document, Writer writer, IProgressMonitor monitor ) throws IOException
+    {
+        Writer out = new BufferedWriter( writer );
+        try
+        {
+            out.write( document.get() );
+        }
+        finally
+        {
+            out.close();
+        }
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    protected IRunnableContext getOperationRunner( IProgressMonitor monitor )
+    {
+        return null;
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public boolean isModifiable( Object element )
+    {
+        if ( element instanceof IPathEditorInput )
+        {
+            IPathEditorInput pei = ( IPathEditorInput ) element;
+            File file = pei.getPath().toFile();
+            return file.canWrite() || !file.exists(); // Allow to edit new files
+        }
+        return false;
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public boolean isReadOnly( Object element )
+    {
+        return !isModifiable( element );
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public boolean isStateValidated( Object element )
+    {
+        return true;
+    }
+}
\ No newline at end of file

Propchange: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifDocumentProvider.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifDocumentSetupParticipant.java
URL: http://svn.apache.org/viewvc/directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifDocumentSetupParticipant.java?rev=592089&view=auto
==============================================================================
--- directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifDocumentSetupParticipant.java (added)
+++ directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifDocumentSetupParticipant.java Mon Nov  5 09:04:52 2007
@@ -0,0 +1,83 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *  
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *  
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License. 
+ *  
+ */
+
+package org.apache.directory.studio.ldifeditor.editor;
+
+
+import org.apache.directory.studio.ldifeditor.editor.text.LdifPartitionScanner;
+import org.eclipse.core.filebuffers.IDocumentSetupParticipant;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IDocumentExtension3;
+import org.eclipse.jface.text.IDocumentPartitioner;
+import org.eclipse.jface.text.rules.FastPartitioner;
+
+
+/**
+ * This class implements the IDocumentSetupParticipant interface for LDIF document
+ *
+ * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
+ * @version $Rev$, $Date$
+ */
+public class LdifDocumentSetupParticipant implements IDocumentSetupParticipant
+{
+    /** The LDIF Partitioning ID */
+    public final static String LDIF_PARTITIONING = "org.apache.directory.studio.ldifeditor.LdifPartitioning"; //$NON-NLS-1$
+
+
+    /**
+     * Creates a new instance of LdifDocumentSetupParticipant.
+     */
+    public LdifDocumentSetupParticipant()
+    {
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public void setup( IDocument document )
+    {
+
+        if ( document instanceof IDocumentExtension3 )
+        {
+            IDocumentExtension3 extension3 = ( IDocumentExtension3 ) document;
+            if ( extension3.getDocumentPartitioner( LdifDocumentSetupParticipant.LDIF_PARTITIONING ) == null )
+            {
+                IDocumentPartitioner partitioner = createDocumentPartitioner();
+                extension3.setDocumentPartitioner( LDIF_PARTITIONING, partitioner );
+                partitioner.connect( document );
+            }
+        }
+    }
+
+
+    /**
+     * Creates the Document Partitioner
+     *
+     * @return
+     *      the Document Partitioner
+     */
+    private IDocumentPartitioner createDocumentPartitioner()
+    {
+        IDocumentPartitioner partitioner = new FastPartitioner( new LdifPartitionScanner(), new String[]
+            { LdifPartitionScanner.LDIF_RECORD } );
+        return partitioner;
+    }
+}

Propchange: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifDocumentSetupParticipant.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifEditor.java
URL: http://svn.apache.org/viewvc/directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifEditor.java?rev=592089&view=auto
==============================================================================
--- directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifEditor.java (added)
+++ directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifEditor.java Mon Nov  5 09:04:52 2007
@@ -0,0 +1,901 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+
+package org.apache.directory.studio.ldifeditor.editor;
+
+
+import java.io.File;
+import java.util.ResourceBundle;
+
+import org.apache.directory.studio.connection.core.Connection;
+import org.apache.directory.studio.connection.core.ConnectionFolder;
+import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry;
+import org.apache.directory.studio.connection.core.event.ConnectionUpdateListener;
+import org.apache.directory.studio.connection.ui.ConnectionUIPlugin;
+import org.apache.directory.studio.ldapbrowser.common.BrowserCommonActivator;
+import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
+import org.apache.directory.studio.ldapbrowser.common.actions.ValueEditorPreferencesAction;
+import org.apache.directory.studio.ldapbrowser.common.widgets.BaseWidgetUtils;
+import org.apache.directory.studio.ldapbrowser.common.widgets.WidgetModifyEvent;
+import org.apache.directory.studio.ldapbrowser.common.widgets.WidgetModifyListener;
+import org.apache.directory.studio.ldapbrowser.common.widgets.search.BrowserConnectionWidget;
+import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
+import org.apache.directory.studio.ldapbrowser.core.model.ldif.LdifFile;
+import org.apache.directory.studio.ldifeditor.LdifEditorActivator;
+import org.apache.directory.studio.ldifeditor.LdifEditorConstants;
+import org.apache.directory.studio.ldifeditor.editor.actions.EditLdifAttributeAction;
+import org.apache.directory.studio.ldifeditor.editor.actions.EditLdifRecordAction;
+import org.apache.directory.studio.ldifeditor.editor.actions.FormatLdifDocumentAction;
+import org.apache.directory.studio.ldifeditor.editor.actions.FormatLdifRecordAction;
+import org.apache.directory.studio.ldifeditor.editor.actions.OpenBestValueEditorAction;
+import org.apache.directory.studio.ldifeditor.editor.actions.OpenDefaultValueEditorAction;
+import org.apache.directory.studio.ldifeditor.editor.actions.OpenValueEditorAction;
+import org.apache.directory.studio.ldifeditor.editor.text.LdifPartitionScanner;
+import org.apache.directory.studio.valueeditors.AbstractDialogValueEditor;
+import org.apache.directory.studio.valueeditors.IValueEditor;
+import org.apache.directory.studio.valueeditors.ValueEditorManager;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.action.ActionContributionItem;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.IContributionItem;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.IToolBarManager;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.action.Separator;
+import org.eclipse.jface.action.ToolBarManager;
+import org.eclipse.jface.commands.ActionHandler;
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.text.ITextHover;
+import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
+import org.eclipse.jface.text.source.IAnnotationHover;
+import org.eclipse.jface.text.source.ISourceViewer;
+import org.eclipse.jface.text.source.IVerticalRuler;
+import org.eclipse.jface.text.source.projection.ProjectionSupport;
+import org.eclipse.jface.text.source.projection.ProjectionViewer;
+import org.eclipse.jface.util.PropertyChangeEvent;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.ViewForm;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.ToolBar;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorSite;
+import org.eclipse.ui.IPageLayout;
+import org.eclipse.ui.IPartListener2;
+import org.eclipse.ui.IPathEditorInput;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.IWorkbenchPartReference;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.commands.ICommandService;
+import org.eclipse.ui.contexts.IContextActivation;
+import org.eclipse.ui.contexts.IContextService;
+import org.eclipse.ui.editors.text.EditorsUI;
+import org.eclipse.ui.editors.text.TextEditor;
+import org.eclipse.ui.part.IShowInTargetList;
+import org.eclipse.ui.texteditor.ChainedPreferenceStore;
+import org.eclipse.ui.texteditor.ContentAssistAction;
+import org.eclipse.ui.texteditor.IDocumentProvider;
+import org.eclipse.ui.texteditor.ITextEditorActionConstants;
+import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
+import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
+import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
+
+
+/**
+ * This class implements the LDIF editor
+ *
+ * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
+ * @version $Rev$, $Date$
+ */
+public class LdifEditor extends TextEditor implements ILdifEditor, ConnectionUpdateListener, IPartListener2
+{
+    private ViewForm control;
+
+    private BrowserConnectionWidget browserConnectionWidget;
+
+    private ToolBar actionToolBar;
+
+    private IToolBarManager actionToolBarManager;
+
+    private IBrowserConnection browserConnection;
+
+    private ProjectionSupport projectionSupport;
+
+    private LdifOutlinePage outlinePage;
+
+    private ValueEditorManager valueEditorManager;
+
+    private OpenBestValueEditorAction openBestValueEditorAction;
+
+    private OpenValueEditorAction[] openValueEditorActions;
+
+    private ValueEditorPreferencesAction valueEditorPreferencesAction;
+
+
+    /**
+     * Creates a new instance of LdifEditor.
+     */
+    public LdifEditor()
+    {
+        super();
+
+        setSourceViewerConfiguration( new LdifSourceViewerConfiguration( this, true ) );
+        setDocumentProvider( new LdifDocumentProvider() );
+
+        IPreferenceStore editorStore = EditorsUI.getPreferenceStore();
+        IPreferenceStore browserStore = LdifEditorActivator.getDefault().getPreferenceStore();
+        IPreferenceStore combinedStore = new ChainedPreferenceStore( new IPreferenceStore[]
+            { browserStore, editorStore } );
+        setPreferenceStore( combinedStore );
+
+        setHelpContextId( LdifEditorActivator.PLUGIN_ID + "." + "tools_ldif_editor" );
+    }
+
+
+    /**
+     * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#handlePreferenceStoreChanged(org.eclipse.jface.util.PropertyChangeEvent)
+     */
+    protected void handlePreferenceStoreChanged( PropertyChangeEvent event )
+    {
+        try
+        {
+
+            ISourceViewer sourceViewer = getSourceViewer();
+            if ( sourceViewer == null )
+            {
+                return;
+            }
+
+            int topIndex = getSourceViewer().getTopIndex();
+            getSourceViewer().getDocument().set( getSourceViewer().getDocument().get() );
+            getSourceViewer().setTopIndex( topIndex );
+
+        }
+        finally
+        {
+            super.handlePreferenceStoreChanged( event );
+        }
+    }
+
+
+    /**
+     * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#collectContextMenuPreferencePages()
+     */
+    protected String[] collectContextMenuPreferencePages()
+    {
+        String[] ids = super.collectContextMenuPreferencePages();
+        String[] more = new String[ids.length + 4];
+        more[0] = LdifEditorConstants.PREFERENCEPAGEID_LDIFEDITOR;
+        more[1] = LdifEditorConstants.PREFERENCEPAGEID_LDIFEDITOR_CONTENTASSIST;
+        more[2] = LdifEditorConstants.PREFERENCEPAGEID_LDIFEDITOR_SYNTAXCOLORING;
+        more[3] = LdifEditorConstants.PREFERENCEPAGEID_LDIFEDITOR_TEMPLATES;
+        System.arraycopy( ids, 0, more, 4, ids.length );
+        return more;
+    }
+
+
+    /**
+     * Gets the ID of the LDIF Editor
+     *
+     * @return
+     *      the ID of the LDIF Editor
+     */
+    public static String getId()
+    {
+        return LdifEditor.class.getName();
+    }
+
+
+    /**
+     * @see org.eclipse.ui.texteditor.AbstractTextEditor#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput)
+     */
+    public void init( IEditorSite site, IEditorInput input ) throws PartInitException
+    {
+        if ( input instanceof IPathEditorInput )
+        {
+            IPathEditorInput pei = ( IPathEditorInput ) input;
+            IPath path = pei.getPath();
+            File javaIoFile = path.toFile();
+            long fileLength = javaIoFile.length();
+            if ( fileLength > ( 1 * 1024 * 1024 ) )
+            {
+                MessageDialog.openError( site.getShell(), "LDIF file is too big",
+                    "The selected LDIF file is too big. Perhaps it is possilbe to open it in a further version..." );
+                super.init( site, new NonExistingLdifEditorInput() );
+                return;
+            }
+        }
+
+        super.init( site, input );
+
+        ConnectionEventRegistry.addConnectionUpdateListener( this, ConnectionUIPlugin.getDefault().getEventRunner() );
+        getSite().getPage().addPartListener( this );
+
+        this.valueEditorManager = new ValueEditorManager( getSite().getShell() );
+    }
+
+
+    /**
+     * @see org.eclipse.ui.editors.text.TextEditor#dispose()
+     */
+    public void dispose()
+    {
+        valueEditorManager.dispose();
+
+        deactivateGlobalActionHandlers();
+
+        ConnectionEventRegistry.removeConnectionUpdateListener( this );
+        getSite().getPage().removePartListener( this );
+
+        super.dispose();
+    }
+
+
+    /**
+     * @see org.eclipse.ui.editors.text.TextEditor#getAdapter(java.lang.Class)
+     */
+    public Object getAdapter( Class required )
+    {
+        if ( IShowInTargetList.class.equals( required ) )
+        {
+            return new IShowInTargetList()
+            {
+                public String[] getShowInTargetIds()
+                {
+                    return new String[]
+                        { IPageLayout.ID_RES_NAV };
+                }
+            };
+        }
+        if ( IContentOutlinePage.class.equals( required ) )
+        {
+            if ( outlinePage == null || outlinePage.getControl() == null || outlinePage.getControl().isDisposed() )
+            {
+                outlinePage = new LdifOutlinePage( this );
+            }
+            return outlinePage;
+        }
+        if ( ISourceViewer.class.equals( required ) )
+        {
+            return getSourceViewer();
+        }
+        if ( IAnnotationHover.class.equals( required ) )
+        {
+            if ( getSourceViewerConfiguration() != null && getSourceViewer() != null )
+                return getSourceViewerConfiguration().getAnnotationHover( getSourceViewer() );
+        }
+        if ( ITextHover.class.equals( required ) )
+        {
+            if ( getSourceViewerConfiguration() != null && getSourceViewer() != null )
+                return getSourceViewerConfiguration().getTextHover( getSourceViewer(), null );
+        }
+        if ( IContentAssistProcessor.class.equals( required ) )
+        {
+            if ( getSourceViewerConfiguration() != null && getSourceViewer() != null )
+                return getSourceViewerConfiguration().getContentAssistant( getSourceViewer() )
+                    .getContentAssistProcessor( LdifPartitionScanner.LDIF_RECORD );
+        }
+        if ( projectionSupport != null )
+        {
+            Object adapter = projectionSupport.getAdapter( getSourceViewer(), required );
+            if ( adapter != null )
+                return adapter;
+        }
+        return super.getAdapter( required );
+    }
+
+
+    /**
+     * @see org.eclipse.ui.editors.text.TextEditor#editorContextMenuAboutToShow(org.eclipse.jface.action.IMenuManager)
+     */
+    protected void editorContextMenuAboutToShow( IMenuManager menu )
+    {
+        super.editorContextMenuAboutToShow( menu );
+
+        IContributionItem[] items = menu.getItems();
+        for ( int i = 0; i < items.length; i++ )
+        {
+            if ( items[i] instanceof ActionContributionItem )
+            {
+                ActionContributionItem aci = ( ActionContributionItem ) items[i];
+                if ( aci.getAction() == getAction( ITextEditorActionConstants.SHIFT_LEFT ) )
+                {
+                    menu.remove( items[i] );
+                }
+                if ( aci.getAction() == getAction( ITextEditorActionConstants.SHIFT_RIGHT ) )
+                {
+                    menu.remove( items[i] );
+                }
+            }
+        }
+
+        // add Edit actions
+        addAction( menu, ITextEditorActionConstants.GROUP_EDIT, EditLdifAttributeAction.class.getName() );
+        addAction( menu, ITextEditorActionConstants.GROUP_EDIT, OpenDefaultValueEditorAction.class.getName() );
+
+        MenuManager valueEditorMenuManager = new MenuManager( "Edit Value With" );
+        if ( this.openBestValueEditorAction.isEnabled() )
+        {
+            valueEditorMenuManager.add( this.openBestValueEditorAction );
+            valueEditorMenuManager.add( new Separator() );
+        }
+        for ( int i = 0; i < this.openValueEditorActions.length; i++ )
+        {
+            this.openValueEditorActions[i].update();
+            if ( this.openValueEditorActions[i].isEnabled()
+                && this.openValueEditorActions[i].getValueEditor().getClass() != this.openBestValueEditorAction
+                    .getValueEditor().getClass()
+                && this.openValueEditorActions[i].getValueEditor() instanceof AbstractDialogValueEditor )
+            {
+                valueEditorMenuManager.add( this.openValueEditorActions[i] );
+            }
+        }
+        valueEditorMenuManager.add( new Separator() );
+        valueEditorMenuManager.add( this.valueEditorPreferencesAction );
+        menu.appendToGroup( ITextEditorActionConstants.GROUP_EDIT, valueEditorMenuManager );
+
+        addAction( menu, ITextEditorActionConstants.GROUP_EDIT, EditLdifRecordAction.class.getName() );
+
+        // add Format actions
+        MenuManager formatMenuManager = new MenuManager( "Format" );
+        addAction( formatMenuManager, FormatLdifDocumentAction.class.getName() );
+        addAction( formatMenuManager, FormatLdifRecordAction.class.getName() );
+        menu.appendToGroup( ITextEditorActionConstants.GROUP_EDIT, formatMenuManager );
+    }
+
+
+    /**
+     * @see org.eclipse.ui.editors.text.TextEditor#createActions()
+     */
+    protected void createActions()
+    {
+        super.createActions();
+
+        // add content assistant
+        ResourceBundle bundle = LdifEditorActivator.getDefault().getResourceBundle();
+        IAction action = new ContentAssistAction( bundle, "ldifeditor__contentassistproposal_", this ); //$NON-NLS-1$
+        action.setActionDefinitionId( ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS );
+        setAction( "ContentAssistProposal", action ); //$NON-NLS-1$
+
+        // add execute action (for tool bar)
+        ExecuteLdifAction executeLdifAction = new ExecuteLdifAction( this );
+        actionToolBarManager.add( executeLdifAction );
+        setAction( ExecuteLdifAction.class.getName(), executeLdifAction );
+        actionToolBarManager.update( true );
+
+        // add context menu edit actions
+        EditLdifAttributeAction editLdifAttributeAction = new EditLdifAttributeAction( this );
+        setAction( EditLdifAttributeAction.class.getName(), editLdifAttributeAction );
+
+        openBestValueEditorAction = new OpenBestValueEditorAction( this );
+        IValueEditor[] valueEditors = valueEditorManager.getAllValueEditors();
+        openValueEditorActions = new OpenValueEditorAction[valueEditors.length];
+        for ( int i = 0; i < this.openValueEditorActions.length; i++ )
+        {
+            openValueEditorActions[i] = new OpenValueEditorAction( this, valueEditors[i] );
+        }
+        valueEditorPreferencesAction = new ValueEditorPreferencesAction();
+
+        OpenDefaultValueEditorAction openDefaultValueEditorAction = new OpenDefaultValueEditorAction( this,
+            openBestValueEditorAction );
+        setAction( OpenDefaultValueEditorAction.class.getName(), openDefaultValueEditorAction );
+
+        EditLdifRecordAction editRecordAction = new EditLdifRecordAction( this );
+        setAction( EditLdifRecordAction.class.getName(), editRecordAction );
+
+        // add context menu format actions
+        FormatLdifDocumentAction formatDocumentAction = new FormatLdifDocumentAction( this );
+        setAction( FormatLdifDocumentAction.class.getName(), formatDocumentAction );
+        FormatLdifRecordAction formatRecordAction = new FormatLdifRecordAction( this );
+        setAction( FormatLdifRecordAction.class.getName(), formatRecordAction );
+
+        // update cut, copy, paste
+        IAction cutAction = getAction( ITextEditorActionConstants.CUT );
+        if ( cutAction != null )
+        {
+            cutAction.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
+                ISharedImages.IMG_TOOL_CUT ) );
+        }
+        IAction copyAction = getAction( ITextEditorActionConstants.COPY );
+        if ( copyAction != null )
+        {
+            copyAction.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
+                ISharedImages.IMG_TOOL_COPY ) );
+        }
+        IAction pasteAction = getAction( ITextEditorActionConstants.PASTE );
+        if ( pasteAction != null )
+        {
+            pasteAction.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
+                ISharedImages.IMG_TOOL_PASTE ) );
+        }
+
+        activateGlobalActionHandlers();
+    }
+
+
+    /**
+     * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createPartControl(org.eclipse.swt.widgets.Composite)
+     */
+    public void createPartControl( Composite parent )
+    {
+        setHelpContextId( LdifEditorActivator.PLUGIN_ID + "." + "tools_ldif_editor" );
+
+        Composite composite = new Composite( parent, SWT.NONE );
+        composite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
+        GridLayout layout = new GridLayout();
+        layout.marginWidth = 0;
+        layout.marginHeight = 0;
+        // layout.horizontalSpacing = 0;
+        layout.verticalSpacing = 0;
+        composite.setLayout( layout );
+
+        control = new ViewForm( composite, SWT.NONE );
+        control.setLayoutData( new GridData( GridData.FILL_BOTH ) );
+
+        Composite browserConnectionWidgetControl = BaseWidgetUtils.createColumnContainer( control, 2, 1 );
+        browserConnectionWidget = new BrowserConnectionWidget();
+        browserConnectionWidget.createWidget( browserConnectionWidgetControl );
+        connectionUpdated( null );
+        browserConnectionWidget.addWidgetModifyListener( new WidgetModifyListener()
+        {
+            public void widgetModified( WidgetModifyEvent event )
+            {
+                IBrowserConnection browserConnection = browserConnectionWidget.getBrowserConnection();
+                setConnection( browserConnection );
+            }
+        } );
+        control.setTopLeft( browserConnectionWidgetControl );
+
+        // tool bar
+        actionToolBar = new ToolBar( control, SWT.FLAT | SWT.RIGHT );
+        actionToolBar.setLayoutData( new GridData( SWT.END, SWT.NONE, true, false ) );
+        actionToolBarManager = new ToolBarManager( actionToolBar );
+        control.setTopCenter( actionToolBar );
+
+        // local menu
+        control.setTopRight( null );
+
+        // content
+        Composite editorComposite = new Composite( control, SWT.NONE );
+        editorComposite.setLayout( new FillLayout() );
+        GridData data = new GridData( GridData.FILL_BOTH );
+        data.widthHint = 450;
+        data.heightHint = 250;
+        editorComposite.setLayoutData( data );
+        super.createPartControl( editorComposite );
+        control.setContent( editorComposite );
+
+        ProjectionViewer projectionViewer = ( ProjectionViewer ) getSourceViewer();
+        projectionSupport = new ProjectionSupport( projectionViewer, getAnnotationAccess(), getSharedColors() );
+        projectionSupport.install();
+        projectionViewer.doOperation( ProjectionViewer.TOGGLE );
+    }
+
+
+    /**
+     * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createSourceViewer(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.source.IVerticalRuler, int)
+     */
+    protected ISourceViewer createSourceViewer( Composite parent, IVerticalRuler ruler, int styles )
+    {
+        getAnnotationAccess();
+        getOverviewRuler();
+        ISourceViewer viewer = new ProjectionViewer( parent, ruler, getOverviewRuler(), true, styles );
+        getSourceViewerDecorationSupport( viewer );
+
+        return viewer;
+    }
+
+
+    /**
+     * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#configureSourceViewerDecorationSupport(org.eclipse.ui.texteditor.SourceViewerDecorationSupport)
+     */
+    protected void configureSourceViewerDecorationSupport( SourceViewerDecorationSupport support )
+    {
+        super.configureSourceViewerDecorationSupport( support );
+    }
+
+
+    /**
+     * @see org.apache.directory.studio.ldifeditor.editor.ILdifEditor#getLdifModel()
+     */
+    public LdifFile getLdifModel()
+    {
+        IDocumentProvider provider = getDocumentProvider();
+        if ( provider instanceof LdifDocumentProvider )
+        {
+            return ( ( LdifDocumentProvider ) provider ).getLdifModel();
+        }
+        else
+        {
+            return null;
+        }
+    }
+
+
+    /**
+     * This method is used to notify the LDIF Editor that the Outline Page has been closed.
+     */
+    public void outlinePageClosed()
+    {
+        projectionSupport.dispose();
+        outlinePage = null;
+    }
+
+
+    /**
+     * @see org.apache.directory.studio.ldifeditor.editor.ILdifEditor#getConnection()
+     */
+    public IBrowserConnection getConnection()
+    {
+        return browserConnection;
+    }
+
+
+    /**
+     * Sets the Connection
+     *
+     * @param browserConnection
+     *      the browser connection to set
+     */
+    private void setConnection( IBrowserConnection browserConnection )
+    {
+        this.browserConnection = browserConnection;
+        getEditorSite().getActionBars().getStatusLineManager().setMessage(
+            "Used Connection: " + ( this.browserConnection == null ? "-" : this.browserConnection.getConnection().getName() ) );
+        // getStatusField("ldapconnection").setText();
+        
+        IAction action = getAction( ExecuteLdifAction.class.getName() );
+        if ( action != null )
+        {
+            action.setEnabled( browserConnection == null );
+            action.setEnabled( browserConnection != null );
+        }
+    }
+
+
+    /**
+     * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionUpdated(org.apache.directory.studio.connection.core.Connection)
+     */
+    public final void connectionUpdated( Connection connection )
+    {
+        IBrowserConnection browserConnection = browserConnectionWidget.getBrowserConnection();
+        setConnection( browserConnection );
+        browserConnectionWidget.setBrowserConnection( browserConnection );
+    }
+
+
+    /**
+     * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionAdded(org.apache.directory.studio.connection.core.Connection)
+     */
+    public void connectionAdded( Connection connection )
+    {
+        connectionUpdated( connection );
+    }
+
+
+    /**
+     * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionRemoved(org.apache.directory.studio.connection.core.Connection)
+     */
+    public void connectionRemoved( Connection connection )
+    {
+        connectionUpdated( connection );
+    }
+
+
+    /**
+     * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionOpened(org.apache.directory.studio.connection.core.Connection)
+     */
+    public void connectionOpened( Connection connection )
+    {
+        connectionUpdated( connection );
+    }
+
+
+    /**
+     * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionClosed(org.apache.directory.studio.connection.core.Connection)
+     */
+    public void connectionClosed( Connection connection )
+    {
+        connectionUpdated( connection );
+    }
+
+
+    /**
+     * @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionFolderModified(org.apache.directory.studio.connection.core.ConnectionFolder)
+     */
+    public void connectionFolderModified( ConnectionFolder connectionFolder )
+    {
+    }
+
+
+    
+    
+    
+    
+    /**
+     * This implementation checks if the input is of type
+     * NonExistingLdifEditorInput. In that case doSaveAs() is
+     * called to prompt for a new file name and location.
+     * 
+     * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSave(org.eclipse.core.runtime.IProgressMonitor)
+     */
+    public void doSave( IProgressMonitor progressMonitor )
+    {
+        final IEditorInput input = getEditorInput();
+        if ( input instanceof NonExistingLdifEditorInput )
+        {
+            super.doSaveAs();
+            return;
+        }
+
+        super.doSave( progressMonitor );
+    }
+
+
+    
+    /**
+     * The input could be one of the following types:
+     * - NonExistingLdifEditorInput: New file, not yet saved
+     * - PathEditorInput: file opened with our internal "Open File.." action
+     * - FileEditorInput: file is within workspace
+     * - JavaFileEditorInput: file opend with "Open File..." action from org.eclipse.ui.editor
+     *
+     * In RCP the FileDialog appears.
+     * In IDE the super implementation is called.
+     * To detect if this plugin runs in IDE the org.eclipse.ui.ide extension point is checked.
+     *
+     * @see org.eclipse.ui.editors.text.TextEditor#performSaveAs(org.eclipse.core.runtime.IProgressMonitor)
+     */
+    protected void performSaveAs( IProgressMonitor progressMonitor )
+    {
+        // detect IDE or RCP:
+        // check if perspective org.eclipse.ui.resourcePerspective is available
+        boolean isIDE = BrowserCommonActivator.isIDEEnvironment();
+
+        if ( isIDE )
+        {
+            // Just call super implementation for now
+            IPreferenceStore store = EditorsUI.getPreferenceStore();
+            String key = getEditorSite().getId() + ".internal.delegateSaveAs"; // $NON-NLS-1$
+            store.setValue( key, true );
+            super.performSaveAs( progressMonitor );
+        }
+        else
+        {
+            // Open FileDialog
+            Shell shell = getSite().getShell();
+            final IEditorInput input = getEditorInput();
+
+            IDocumentProvider provider = getDocumentProvider();
+            final IEditorInput newInput;
+
+            FileDialog dialog = new FileDialog( shell, SWT.SAVE );
+
+            String path = dialog.open();
+            if ( path == null )
+            {
+                if ( progressMonitor != null )
+                {
+                    progressMonitor.setCanceled( true );
+                }
+                return;
+            }
+
+            // Check whether file exists and if so, confirm overwrite
+            final File externalFile = new File( path );
+            if ( externalFile.exists() )
+            {
+                MessageDialog overwriteDialog = new MessageDialog( shell, "Overwrite", null, "Overwrite?",
+                    MessageDialog.WARNING, new String[]
+                        { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 1 ); // 'No' is the default
+                if ( overwriteDialog.open() != Window.OK )
+                {
+                    if ( progressMonitor != null )
+                    {
+                        progressMonitor.setCanceled( true );
+                        return;
+                    }
+                }
+            }
+
+            IPath iPath = new Path( path );
+            newInput = new PathEditorInput( iPath );
+
+            boolean success = false;
+            try
+            {
+                provider.aboutToChange( newInput );
+                provider.saveDocument( progressMonitor, newInput, provider.getDocument( input ), true );
+                success = true;
+            }
+            catch ( CoreException x )
+            {
+                final IStatus status = x.getStatus();
+                if ( status == null || status.getSeverity() != IStatus.CANCEL )
+                {
+                    String title = "Error in Save As...";
+                    String msg = "Error in Save As... " + x.getMessage();
+                    MessageDialog.openError( shell, title, msg );
+                }
+            }
+            finally
+            {
+                provider.changed( newInput );
+                if ( success )
+                {
+                    setInput( newInput );
+                }
+            }
+
+            if ( progressMonitor != null )
+            {
+                progressMonitor.setCanceled( !success );
+            }
+        }
+
+    }
+
+    private IContextActivation contextActivation;
+
+
+    /**
+     * @see org.eclipse.ui.IPartListener2#partDeactivated(org.eclipse.ui.IWorkbenchPartReference)
+     */
+    public void partDeactivated( IWorkbenchPartReference partRef )
+    {
+        if ( partRef.getPart( false ) == this && contextActivation != null )
+        {
+            deactivateGlobalActionHandlers();
+
+            IContextService contextService = ( IContextService ) PlatformUI.getWorkbench().getAdapter(
+                IContextService.class );
+            contextService.deactivateContext( contextActivation );
+            contextActivation = null;
+        }
+    }
+
+
+    /**
+     * @see org.eclipse.ui.IPartListener2#partActivated(org.eclipse.ui.IWorkbenchPartReference)
+     */
+    public void partActivated( IWorkbenchPartReference partRef )
+    {
+        if ( partRef.getPart( false ) == this )
+        {
+            IContextService contextService = ( IContextService ) PlatformUI.getWorkbench().getAdapter(
+                IContextService.class );
+            contextActivation = contextService
+                .activateContext( BrowserCommonConstants.CONTEXT_WINDOWS );
+
+            activateGlobalActionHandlers();
+        }
+    }
+
+
+    /**
+     * @see org.eclipse.ui.IPartListener2#partBroughtToTop(org.eclipse.ui.IWorkbenchPartReference)
+     */
+    public void partBroughtToTop( IWorkbenchPartReference partRef )
+    {
+    }
+
+
+    /**
+     * @see org.eclipse.ui.IPartListener2#partClosed(org.eclipse.ui.IWorkbenchPartReference)
+     */
+    public void partClosed( IWorkbenchPartReference partRef )
+    {
+    }
+
+
+    /**
+     * @see org.eclipse.ui.IPartListener2#partHidden(org.eclipse.ui.IWorkbenchPartReference)
+     */
+    public void partHidden( IWorkbenchPartReference partRef )
+    {
+    }
+
+
+    /**
+     * @see org.eclipse.ui.IPartListener2#partInputChanged(org.eclipse.ui.IWorkbenchPartReference)
+     */
+    public void partInputChanged( IWorkbenchPartReference partRef )
+    {
+    }
+
+
+    /**
+     * @see org.eclipse.ui.IPartListener2#partOpened(org.eclipse.ui.IWorkbenchPartReference)
+     */
+    public void partOpened( IWorkbenchPartReference partRef )
+    {
+    }
+
+
+    /**
+     * @see org.eclipse.ui.IPartListener2#partVisible(org.eclipse.ui.IWorkbenchPartReference)
+     */
+    public void partVisible( IWorkbenchPartReference partRef )
+    {
+    }
+
+
+    /**
+     * Activates global action handlers
+     */
+    public void activateGlobalActionHandlers()
+    {
+        ICommandService commandService = ( ICommandService ) PlatformUI.getWorkbench().getAdapter(
+            ICommandService.class );
+        if ( commandService != null )
+        {
+            IAction elaa = getAction( EditLdifAttributeAction.class.getName() );
+            commandService.getCommand( elaa.getActionDefinitionId() ).setHandler( new ActionHandler( elaa ) );
+            IAction elva = getAction( OpenDefaultValueEditorAction.class.getName() );
+            commandService.getCommand( elva.getActionDefinitionId() ).setHandler( new ActionHandler( elva ) );
+            IAction elra = getAction( EditLdifRecordAction.class.getName() );
+            commandService.getCommand( elra.getActionDefinitionId() ).setHandler( new ActionHandler( elra ) );
+        }
+    }
+
+
+    /**
+     * Deactivates global action handlers
+     */
+    public void deactivateGlobalActionHandlers()
+    {
+        ICommandService commandService = ( ICommandService ) PlatformUI.getWorkbench().getAdapter(
+            ICommandService.class );
+        if ( commandService != null )
+        {
+            IAction elaa = getAction( EditLdifAttributeAction.class.getName() );
+            commandService.getCommand( elaa.getActionDefinitionId() ).setHandler( null );
+            IAction elva = getAction( OpenDefaultValueEditorAction.class.getName() );
+            commandService.getCommand( elva.getActionDefinitionId() ).setHandler( null );
+            IAction elra = getAction( EditLdifRecordAction.class.getName() );
+            commandService.getCommand( elra.getActionDefinitionId() ).setHandler( null );
+        }
+    }
+
+
+    /**
+     * Gets the Value Editor Manager
+     *
+     * @return
+     *      the Value Editor Manager
+     */
+    public ValueEditorManager getValueEditorManager()
+    {
+        return valueEditorManager;
+    }
+
+}

Propchange: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifEditor.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifEditorContributor.java
URL: http://svn.apache.org/viewvc/directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifEditorContributor.java?rev=592089&view=auto
==============================================================================
--- directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifEditorContributor.java (added)
+++ directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifEditorContributor.java Mon Nov  5 09:04:52 2007
@@ -0,0 +1,90 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *  
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *  
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License. 
+ *  
+ */
+
+package org.apache.directory.studio.ldifeditor.editor;
+
+
+import org.apache.directory.studio.ldifeditor.LdifEditorActivator;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.texteditor.BasicTextEditorActionContributor;
+import org.eclipse.ui.texteditor.ITextEditor;
+import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
+import org.eclipse.ui.texteditor.RetargetTextEditorAction;
+
+
+/**
+ * This class manages the installation and removal of global actions for the LDIF Editor.
+ *
+ * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
+ * @version $Rev$, $Date$
+ */
+public class LdifEditorContributor extends BasicTextEditorActionContributor
+{
+
+    private static final String CONTENTASSIST_ACTION = "org.apache.directory.studio.ldapbrowser.ContentAssist";
+
+    private RetargetTextEditorAction contentAssist;
+
+
+    /**
+     * Creates a new instance of LdifEditorContributor.
+     */
+    public LdifEditorContributor()
+    {
+        super();
+
+        contentAssist = new RetargetTextEditorAction( LdifEditorActivator.getDefault().getResourceBundle(),
+            "ContentAssistProposal." );
+        contentAssist.setActionDefinitionId( ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS );
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public void setActiveEditor( IEditorPart part )
+    {
+        super.setActiveEditor( part );
+        ITextEditor editor = ( part instanceof ITextEditor ) ? ( ITextEditor ) part : null;
+        contentAssist.setAction( getAction( editor, CONTENTASSIST_ACTION ) );
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public void init( IActionBars bars, IWorkbenchPage page )
+    {
+        super.init( bars, page );
+        bars.setGlobalActionHandler( CONTENTASSIST_ACTION, contentAssist );
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public void dispose()
+    {
+        setActiveEditor( null );
+        super.dispose();
+    }
+}

Propchange: directory/sandbox/felixk/studio-ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifEditorContributor.java
------------------------------------------------------------------------------
    svn:eol-style = native



Mime
View raw message