Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/WpfTestSvgSample/Backup/SvgPage.xaml.cs @ 12762

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

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

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