Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/WpfTestSvgSample/XamlPage.xaml.cs @ 13857

Last change on this file since 13857 was 12762, checked in by aballeit, 9 years ago

#2283 GUI updates, Tree-chart, MCTS Version 2 (prune leaves)

File size: 15.5 KB
Line 
1using System;
2using System.IO;
3using System.IO.Packaging;
4using System.IO.Compression;
5using System.Collections.Generic;
6
7using System.Printing;
8using System.Windows;
9using System.Windows.Controls;
10using System.Windows.Documents;
11using System.Windows.Input;
12using System.Windows.Media;
13using System.Windows.Xps;
14using System.Windows.Xps.Packaging;
15
16using ICSharpCode.AvalonEdit;
17using ICSharpCode.AvalonEdit.Utils;
18using ICSharpCode.AvalonEdit.Document;
19using ICSharpCode.AvalonEdit.Folding;
20using ICSharpCode.AvalonEdit.Indentation;
21using ICSharpCode.AvalonEdit.Highlighting;
22using ICSharpCode.AvalonEdit.CodeCompletion;
23using ICSharpCode.AvalonEdit.Searching;
24
25using Microsoft.Win32;
26
27namespace WpfTestSvgSample
28{
29    /// <summary>
30    /// Interaction logic for XamlPage.xaml
31    /// </summary>
32    public partial class XamlPage : Page
33    {
34        #region Private Fields
35
36        private string currentFileName;
37
38        private TextEditorSearchTarget _searchText;
39
40        private FoldingManager _foldingManager;
41        private XmlFoldingStrategy _foldingStrategy;
42
43        #endregion
44
45        #region Constructors and Destructor
46
47        public XamlPage()
48        {
49            InitializeComponent();
50
51            textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("XML");
52            TextEditorOptions options = textEditor.Options;
53            if (options != null)
54            {
55                //options.AllowScrollBelowDocument = true;
56                options.EnableHyperlinks = true;
57                options.EnableEmailHyperlinks = true;
58                //options.ShowSpaces = true;
59                //options.ShowTabs = true;
60                //options.ShowEndOfLine = true;             
61            }
62            textEditor.ShowLineNumbers = true;
63
64            _foldingManager  = FoldingManager.Install(textEditor.TextArea);
65            _foldingStrategy = new XmlFoldingStrategy();
66
67            _searchText = new TextEditorSearchTarget(textEditor);
68
69            textEditor.CommandBindings.Add(new CommandBinding(
70                ApplicationCommands.Print, OnPrint, OnCanExecuteTextEditorCommand));
71            textEditor.CommandBindings.Add(new CommandBinding(
72                ApplicationCommands.PrintPreview, OnPrintPreview, OnCanExecuteTextEditorCommand));
73        }
74
75        #endregion
76
77        #region Public Methods
78
79        public void LoadDocument(string documentFileName)
80        {
81            if (textEditor == null || String.IsNullOrEmpty(documentFileName))
82            {
83                return;
84            }
85
86            string fileExt = Path.GetExtension(documentFileName);
87            if (String.Equals(fileExt, ".zaml", StringComparison.OrdinalIgnoreCase))
88            {
89                using (FileStream fileStream = File.OpenRead(documentFileName))
90                {
91                    using (GZipStream zipStream =
92                        new GZipStream(fileStream, CompressionMode.Decompress))
93                    {
94                        // Text Editor does not work with this stream, so we read the data to memory stream...
95                        MemoryStream memoryStream = new MemoryStream();
96                        // Use this method is used to read all bytes from a stream.
97                        int totalCount = 0;
98                        int bufferSize = 512;
99                        byte[] buffer = new byte[bufferSize];
100                        while (true)
101                        {
102                            int bytesRead = zipStream.Read(buffer, 0, bufferSize);
103                            if (bytesRead == 0)
104                            {
105                                break;
106                            }
107                            else
108                            {
109                                memoryStream.Write(buffer, 0, bytesRead);
110                            }
111                            totalCount += bytesRead;
112                        }
113
114                        if (totalCount > 0)
115                        {
116                            memoryStream.Position = 0;
117                        }
118
119                        textEditor.Load(memoryStream);
120
121                        memoryStream.Close();
122                    }
123                }
124            }
125            else
126            {
127                textEditor.Load(documentFileName);
128            }
129
130            if (_foldingManager == null || _foldingStrategy == null)
131            {
132                _foldingManager  = FoldingManager.Install(textEditor.TextArea);
133                _foldingStrategy = new XmlFoldingStrategy();
134            }
135
136            _foldingStrategy.UpdateFoldings(_foldingManager, textEditor.Document);
137        }
138
139        public void UnloadDocument()
140        {
141            if (textEditor != null)
142            {
143                textEditor.Document.Text = String.Empty;
144            }
145        }
146
147        public void PageSelected(bool isSelected)
148        {
149            if (isSelected)
150            {
151                if (!textEditor.TextArea.IsKeyboardFocusWithin)
152                {
153                    Keyboard.Focus(textEditor.TextArea);
154                }
155            }
156        }
157
158        #endregion
159
160        #region Private Methods
161
162        private void OnOpenFileClick(object sender, RoutedEventArgs e)
163        {
164            OpenFileDialog dlg = new OpenFileDialog();
165            dlg.CheckFileExists = true;
166            if (dlg.ShowDialog() ?? false)
167            {
168                currentFileName = dlg.FileName;
169                textEditor.Load(currentFileName);
170                textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinitionByExtension(Path.GetExtension(currentFileName));
171            }
172        }
173
174        private void OnSaveFileClick(object sender, EventArgs e)
175        {
176            if (currentFileName == null)
177            {
178                SaveFileDialog dlg = new SaveFileDialog();
179                dlg.DefaultExt = ".txt";
180                if (dlg.ShowDialog() ?? false)
181                {
182                    currentFileName = dlg.FileName;
183                }
184                else
185                {
186                    return;
187                }
188            }
189            textEditor.Save(currentFileName);
190        }
191
192        private void OnSearchTextClick(object sender, RoutedEventArgs e)
193        {
194            string searchText = searchTextBox.Text;
195
196            if (String.IsNullOrEmpty(searchText))
197            {
198                return;
199            }
200
201            SearchOptions.FindPattern = searchText;
202            SearchManager.Initialize(_searchText);
203
204            SearchManager.FindNext();
205
206            SearchManager.Uninitialize();
207        }
208
209        private void OnSearchTextBoxKeyUp(object sender, KeyEventArgs e)
210        {
211            if (e.Key != Key.Enter)
212                return;
213
214            // your event handler here
215            e.Handled = true;           
216
217            textEditor.Select(textEditor.SelectionStart, 1);
218            searchTextBox.Focus();
219
220            this.OnSearchTextClick(sender, e);
221        }
222
223        private void OnHighlightingSelectionChanged(object sender, SelectionChangedEventArgs e)
224        {
225            //if (textEditor.SyntaxHighlighting == null)
226            //{
227            //    _foldingStrategy = null;
228            //}
229            //else
230            //{
231            //    switch (textEditor.SyntaxHighlighting.Name)
232            //    {
233            //        case "XML":
234            //            _foldingStrategy = new XmlFoldingStrategy();
235            //            textEditor.TextArea.IndentationStrategy = new DefaultIndentationStrategy();
236            //            break;
237            //        case "C#":
238            //        case "C++":
239            //        case "PHP":
240            //        case "Java":
241            //            textEditor.TextArea.IndentationStrategy = new CSharpIndentationStrategy(textEditor.Options);
242            //            _foldingStrategy = new BraceFoldingStrategy();
243            //            break;
244            //        default:
245            //            textEditor.TextArea.IndentationStrategy = new DefaultIndentationStrategy();
246            //            _foldingStrategy = null;
247            //            break;
248            //    }
249            //}
250            //if (_foldingStrategy != null)
251            //{
252            //    if (_foldingManager == null)
253            //        _foldingManager = FoldingManager.Install(textEditor.TextArea);
254            //    _foldingStrategy.UpdateFoldings(_foldingManager, textEditor.Document);
255            //}
256            //else
257            //{
258            //    if (_foldingManager != null)
259            //    {
260            //        FoldingManager.Uninstall(_foldingManager);
261            //        _foldingManager = null;
262            //    }
263            //}
264        }
265
266        #endregion
267
268        #region Printing Methods
269
270        private Block ConvertTextDocumentToBlock()
271        {
272            TextDocument document = textEditor.Document;
273            IHighlighter highlighter =
274                textEditor.TextArea.GetService(typeof(IHighlighter)) as IHighlighter;
275
276            Paragraph p = new Paragraph();
277            foreach (DocumentLine line in document.Lines)
278            {
279                int lineNumber = line.LineNumber;
280                HighlightedInlineBuilder inlineBuilder = new HighlightedInlineBuilder(document.GetText(line));
281                if (highlighter != null)
282                {
283                    HighlightedLine highlightedLine = highlighter.HighlightLine(lineNumber);
284                    int lineStartOffset = line.Offset;
285                    foreach (HighlightedSection section in highlightedLine.Sections)
286                        inlineBuilder.SetHighlighting(section.Offset - lineStartOffset, section.Length, section.Color);
287                }
288                p.Inlines.AddRange(inlineBuilder.CreateRuns());
289                p.Inlines.Add(new LineBreak());
290            }
291
292            return p;
293        }
294
295        private FlowDocument CreateFlowDocumentForEditor()
296        {
297            FlowDocument doc = new FlowDocument(ConvertTextDocumentToBlock());
298            doc.FontFamily = textEditor.FontFamily;
299            doc.FontSize   = textEditor.FontSize;
300            return doc;
301        }
302
303        // CanExecuteRoutedEventHandler that only returns true if
304        // the source is a control.
305        private void OnCanExecuteTextEditorCommand(object sender, CanExecuteRoutedEventArgs e)
306        {
307            TextEditor target = e.Source as TextEditor;
308
309            if (target != null)
310            {
311                e.CanExecute = true;
312            }
313            else
314            {
315                e.CanExecute = false;
316            }
317        }
318
319        private void OnPrint(object sender, ExecutedRoutedEventArgs e)
320        {
321            PrintDialog printDialog = new PrintDialog();
322            printDialog.PageRangeSelection   = PageRangeSelection.AllPages;
323            printDialog.UserPageRangeEnabled = true;
324            bool? dialogResult = printDialog.ShowDialog();
325            if (dialogResult != null && dialogResult.Value == false)
326            {
327                return;
328            }
329
330            FlowDocument printSource = this.CreateFlowDocumentForEditor();
331
332            // Save all the existing settings.                               
333            double pageHeight     = printSource.PageHeight;
334            double pageWidth      = printSource.PageWidth;
335            Thickness pagePadding = printSource.PagePadding;
336            double columnGap      = printSource.ColumnGap;
337            double columnWidth    = printSource.ColumnWidth;
338
339            // Make the FlowDocument page match the printed page.
340            printSource.PageHeight  = printDialog.PrintableAreaHeight;
341            printSource.PageWidth   = printDialog.PrintableAreaWidth;
342            printSource.PagePadding = new Thickness(20);
343            printSource.ColumnGap   = Double.NaN;
344            printSource.ColumnWidth = printDialog.PrintableAreaWidth;
345
346            Size pageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight);
347
348            DocumentPaginator paginator = ((IDocumentPaginatorSource)printSource).DocumentPaginator;
349            paginator.PageSize = pageSize;
350            paginator.ComputePageCount();
351
352            printDialog.PrintDocument(paginator, "Svg Contents");
353
354            // Reapply the old settings.
355            printSource.PageHeight  = pageHeight;
356            printSource.PageWidth   = pageWidth;
357            printSource.PagePadding = pagePadding;
358            printSource.ColumnGap   = columnGap;
359            printSource.ColumnWidth = columnWidth;
360        }
361
362        private void OnPrintPreview(object sender, ExecutedRoutedEventArgs e)
363        {
364            PrintDialog printDialog = new PrintDialog();
365            printDialog.PageRangeSelection   = PageRangeSelection.AllPages;
366            printDialog.UserPageRangeEnabled = true;
367            bool? dialogResult = printDialog.ShowDialog();
368            if (dialogResult != null && dialogResult.Value == false)
369            {
370                return;
371            }
372
373            FlowDocument printSource = this.CreateFlowDocumentForEditor();
374
375            // Save all the existing settings.                               
376            double pageHeight     = printSource.PageHeight;
377            double pageWidth      = printSource.PageWidth;
378            Thickness pagePadding = printSource.PagePadding;
379            double columnGap      = printSource.ColumnGap;
380            double columnWidth    = printSource.ColumnWidth;
381
382            // Make the FlowDocument page match the printed page.
383            printSource.PageHeight  = printDialog.PrintableAreaHeight;
384            printSource.PageWidth   = printDialog.PrintableAreaWidth;
385            printSource.PagePadding = new Thickness(20);
386            printSource.ColumnGap   = Double.NaN;
387            printSource.ColumnWidth = printDialog.PrintableAreaWidth;
388
389            Size pageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight);
390
391            MemoryStream xpsStream  = new MemoryStream();
392            Package package         = Package.Open(xpsStream, FileMode.Create, FileAccess.ReadWrite);
393            string packageUriString = "memorystream://data.xps";
394            PackageStore.AddPackage(new Uri(packageUriString), package);
395
396            XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Normal, packageUriString);
397            XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
398
399            DocumentPaginator paginator = ((IDocumentPaginatorSource)printSource).DocumentPaginator;
400            paginator.PageSize = pageSize;
401            paginator.ComputePageCount();
402
403            writer.Write(paginator);
404
405            // Reapply the old settings.
406            printSource.PageHeight  = pageHeight;
407            printSource.PageWidth   = pageWidth;
408            printSource.PagePadding = pagePadding;
409            printSource.ColumnGap   = columnGap;
410            printSource.ColumnWidth = columnWidth;
411
412            PrintPreviewWindow printPreview = new PrintPreviewWindow();
413            printPreview.Width  = this.ActualWidth;
414            printPreview.Height = this.ActualHeight;
415            printPreview.Owner  = Application.Current.MainWindow;
416
417            printPreview.LoadDocument(xpsDocument, package, packageUriString);
418
419            printPreview.Show();
420        }
421
422        #endregion
423    }
424}
Note: See TracBrowser for help on using the repository browser.