-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMainWindowViewModel.cs
1364 lines (1089 loc) · 42.2 KB
/
MainWindowViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;
using Microsoft.Win32;
using ProverbTeleprompter.Converters;
using ProverbTeleprompter.Helpers;
using ProverbTeleprompter.Properties;
using Tools.API.Messages.lParam;
using Application = System.Windows.Application;
using Brushes = System.Windows.Media.Brushes;
using DataFormats = System.Windows.DataFormats;
using Image = System.Windows.Controls.Image;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MessageBox = System.Windows.MessageBox;
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;
using Point = System.Windows.Point;
using RichTextBox = System.Windows.Controls.RichTextBox;
using SaveFileDialog = Microsoft.Win32.SaveFileDialog;
using Size = System.Windows.Size;
namespace ProverbTeleprompter
{
public partial class MainWindowViewModel : NotifyPropertyChangedBase, IDisposable
{
private static readonly SemaphoreSlim ChangeSemaphore = new SemaphoreSlim(1);
private readonly DispatcherTimer _scrollTimer;
private ObservableCollection<Bookmark> _bookmarks = new ObservableCollection<Bookmark>();
private bool _configInitialized;
private TimeSpan _eta;
private double _pixelsPerSecond;
private double _prevScrollOffset;
private DateTime _prevTime = DateTime.Now;
private double _speedBoostAmount;
private TalentWindow _talentWindow;
private int _ticksElapsed;
private ToolsWindow _toolsWindow;
private Process _wordpadProcess;
public MainWindowViewModel(RichTextBox mainTextBox)
{
_scrollTimer = new DispatcherTimer (DispatcherPriority.Render) {Interval = new TimeSpan(0, 0, 0, 0, 15), IsEnabled = true};
_scrollTimer.Tick += _scrollTimer_Tick;
_scrollTimer.Start();
MainTextBox = mainTextBox;
MultipleMonitorsAvailable = SystemInformation.MonitorCount > 1;
SystemHandler.RemoteButtonPressed += RemoteButtonPressed;
SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged;
SystemEvents.DisplaySettingsChanged += new EventHandler(SystemEvents_DisplaySettingsChanged);
KeyboardHookHelpers.CreateHook();
KeyboardHookHelpers.KeyDown += KeyboardHookHelpers_KeyDown;
KeyboardHookHelpers.KeyPress += KeyboardHookHelpers_KeyPress;
KeyboardHookHelpers.KeyUp += KeyboardHookHelpers_KeyUp;
Displays = new ObservableCollection<string>(Screen.AllScreens.Select(x => x.DeviceName));
MainTextBox.SizeChanged += new SizeChangedEventHandler(MainTextBox_SizeChanged);
MainTextBox.TextChanged += new System.Windows.Controls.TextChangedEventHandler(MainTextBox_TextChanged);
}
void MainTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
StartCalcBookmarks();
}
DispatcherTimer _calcBookmarksTimer = new DispatcherTimer();
void MainTextBox_SizeChanged(object sender, SizeChangedEventArgs e)
{
StartCalcBookmarks(5);
}
private void StartCalcBookmarks(int delay = 1)
{
_calcBookmarksTimer.Stop();
_calcBookmarksTimer.Interval = new TimeSpan(0, 0, 0, delay);
_calcBookmarksTimer.Tick -= calcBookmarksTimer_Tick;
_calcBookmarksTimer.Tick += calcBookmarksTimer_Tick;
_calcBookmarksTimer.Start();
}
void calcBookmarksTimer_Tick(object sender, EventArgs e)
{
_calcBookmarksTimer.Stop();
UpdateBookmarks();
}
private void UpdateBookmarks()
{
LoadBookmarks(MainDocument);
//Bookmarks = new ObservableCollection<Bookmark>(CalculateAllBookMarkInfo());
}
private IEnumerable<Bookmark> CalculateAllBookMarkInfo()
{
Debug.WriteLine("Calc all bookmark info");
return Bookmarks.Select(bookmark => CalculateBookMarkInfo(bookmark)).Where(bm => bm != null);
}
/// <summary>
///
/// </summary>
/// <param name="bm"></param>
/// <param name="bookmarkOffset"></param>
/// <returns>The updated bookmark, null if the hyperlink no longer exists in the document</returns>
private Bookmark CalculateBookMarkInfo(Bookmark bm, double? bookmarkOffset = null)
{
if(!bookmarkOffset.HasValue)
{
var rect = bm.Hyperlink.ContentStart.GetCharacterRect(LogicalDirection.Forward);
if(rect.IsEmpty)
{
return null;
}
bookmarkOffset = rect.Top;
}
TextPointer pos = MainTextBox.GetPositionFromPoint(new Point(0, bookmarkOffset.GetValueOrDefault()), true);
TextPointer endPos = MainTextBox.GetPositionFromPoint(new Point(MainTextBox.ActualWidth, bookmarkOffset.GetValueOrDefault()), true);
if (pos == null)
{
Trace.Fail("Could not get text start position for bookmark");
return null;
}
if (endPos == null)
{
Trace.Fail("Could not get text end position for bookmark");
return null;
}
int num = DocumentHelpers.GetLineNumberFromPosition(_mainTextBox, pos);
if (bm.Hyperlink == null)
{
var hyperlink = new Hyperlink(pos, pos);
bm.Hyperlink = hyperlink;
if (BookmarkImage != null)
{
var img = new Image();
img.Source = BookmarkImage;
img.Visibility = Visibility.Collapsed;
bm.Image = img;
hyperlink.Inlines.Add(" ");
}
}
var textRange = new TextRange(pos, endPos);
string toolTipText = textRange.Text;
bm.Line = num;
bm.TopOffset = bookmarkOffset.GetValueOrDefault();
if (string.IsNullOrWhiteSpace(toolTipText))
{
toolTipText = "<<Blank line>>";
}
bm.TooltipText = string.Format("{0} (Line: {1})", toolTipText, num);
bm.Name = bm.TooltipText;
bm.Hyperlink.NavigateUri = new Uri(String.Format("http://bookmark/{0}", bm.Name));
bm.Position = pos;
return bm;
}
void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
{
Debug.WriteLine(@"
#############################################
SystemEvents_DisplaySettingsChanged
#############################################
");
ShowDisplayDiagnostics();
SetScreenState();
}
private void SetScreenState()
{
Displays = new ObservableCollection<string>(Screen.AllScreens.Select(x => x.DeviceName));
MultipleMonitorsAvailable = Screen.AllScreens.Count() > 1;
if (!MultipleMonitorsAvailable && Displays.Count == 1)
{
SelectedTalentWindowDisplay = Displays[0];
}
if (Displays.Count > 1)
{
SelectedTalentWindowDisplay = Displays[1];
}
MoveTalentWindowToDisplay(SelectedTalentWindowDisplay);
}
private void ShowDisplayDiagnostics()
{
var details = DisplayDetails.GetMonitorDetails();
#region Diagnostics
Debug.WriteLine("****************** GetWorkingArea: {0}", Screen.GetWorkingArea(new System.Drawing.Point(0, 0)));
Debug.WriteLine("****************** GetBounds: {0}", Screen.GetBounds(new System.Drawing.Point(0, 0)));
Debug.WriteLine("****************** Primary Screen: {0}", Screen.PrimaryScreen.DeviceName, 0);
Debug.WriteLine("****************** EntireDesktop Res: {0}", ScreenHelpers.GetEntireDesktopArea(), 0);
foreach (var displayDetails in details)
{
Debug.WriteLine("DETAILS:");
Debug.WriteLine("\t\tAvailability: {0}", displayDetails.Availability);
Debug.WriteLine("\t\tModel: {0}", displayDetails.Model, 0);
Debug.WriteLine("\t\tMonitorID: {0}", displayDetails.MonitorID, 0);
Debug.WriteLine("\t\tPixelHeight: {0}", displayDetails.PixelHeight, 0);
Debug.WriteLine("\t\tPixelWidth: {0}", displayDetails.PixelWidth);
Debug.WriteLine("\t\tPnPID: {0}", displayDetails.PnPID, 0);
Debug.WriteLine("\t\tSerialNumber: {0}", displayDetails.SerialNumber, 0);
}
Debug.WriteLine("********* SCREENS *********");
var screens = Screen.AllScreens;
foreach (var screen in screens)
{
Debug.WriteLine("SCREEN:");
Debug.WriteLine("\t\tBitsPerPixel: {0}", screen.BitsPerPixel, 0);
Debug.WriteLine("\t\tBounds: {0}", screen.Bounds, 0);
Debug.WriteLine("\t\tDeviceName: {0}", screen.DeviceName, 0);
Debug.WriteLine("\t\tPrimary: {0}", screen.Primary, 0);
Debug.WriteLine("\t\tWorkingArea: {0}", screen.WorkingArea, 0);
}
#endregion
}
void KeyboardHookHelpers_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
GlobalKeyUp(sender, e);
}
void KeyboardHookHelpers_KeyPress(object sender, KeyPressEventArgs e)
{
}
void KeyboardHookHelpers_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
GlobalKeyDown(sender, e);
}
public ObservableCollection<Bookmark> Bookmarks
{
get { return _bookmarks; }
set
{
_bookmarks = value;
Changed(() => Bookmarks);
}
}
#region IDisposable Members
public void Dispose()
{
KillWordPadProcess();
SystemEvents.DisplaySettingsChanged -= SystemEvents_DisplaySettingsChanged;
if (_talentWindow != null)
{
_talentWindow.Close();
}
}
#endregion
private void _scrollTimer_Tick(object sender, EventArgs e)
{
_ticksElapsed++;
if (!Paused && Speed.CompareTo(0) != 0)
{
MainScrollerVerticalOffset = MainScrollerVerticalOffset + Speed;
}
else if(TotalBoostAmount.CompareTo(0) != 0)
{
MainScrollerVerticalOffset = MainScrollerVerticalOffset +
TotalBoostAmount;
}
//Only update calculations every 10 timer ticks (100 ms)
if (_ticksElapsed%10 == 0)
{
//Calculate pixels per second (velocity)
if (DateTime.Now - _prevTime > TimeSpan.FromSeconds(1))
{
CalcEta();
}
PercentComplete = ((MainScrollerVerticalOffset + EyelinePosition)/
(MainScrollerExtentHeight + EyelinePosition))*100;
}
}
private void CalcEta()
{
TimeSpan diff = DateTime.Now - _prevTime;
double pixelChange = (MainScrollerVerticalOffset - _prevScrollOffset);
_pixelsPerSecond = pixelChange/diff.TotalSeconds;
double pixelsToGo = MainScrollerExtentHeight - MainScrollerVerticalOffset;
if (pixelsToGo == 0)
{
TimeRemaining = TimeSpan.FromSeconds(0).ToString();
return;
}
double secondsToDone = pixelsToGo/_pixelsPerSecond;
_eta = new TimeSpan(0, 0, (int) secondsToDone);
TimeRemaining = _eta >= TimeSpan.FromSeconds(0) ? _eta.ToString() : "N/A";
_prevTime = DateTime.Now;
_prevScrollOffset = MainScrollerVerticalOffset;
}
public void InitializeConfig()
{
_configInitialized = true;
Speed = DefaultSpeed = Settings.Default.Speed;
DocumentPath = Settings.Default.DocumentPath;
if (!string.IsNullOrWhiteSpace(_documentPath) && File.Exists(DocumentPath))
{
LoadDocument(DocumentPath);
}
else
{
//Load default text
using (var ms = new MemoryStream(Encoding.Default.GetBytes(Resources.Proverbs_1)))
{
DocumentHelpers.LoadDocument(ms, MainDocument, DataFormats.Rtf);
}
}
SetDocumentConfig();
FlipTalentWindowVert = Settings.Default.FlipTalentWindowVert;
FlipTalentWindowHoriz = Settings.Default.FlipTalentWindowHoriz;
FlipMainWindowVert = Settings.Default.FlipMainWindowVert;
FlipMainWindowHoriz = Settings.Default.FlipMainWindowHoriz;
TalentWindowLeft = Settings.Default.TalentWindowLeft;
TalentWindowTop = Settings.Default.TalentWindowTop;
TalentWindowWidth = Settings.Default.TalentWindowWidth;
TalentWindowHeight = Settings.Default.TalentWindowHeight;
FullScreenTalentWindow = Settings.Default.TalentWindowState != WindowState.Normal;
SelectedTalentWindowDisplay = Settings.Default.SelectedTalentWindowDisplay;
TalentWindowState = Settings.Default.TalentWindowState;
EyelinePosition = Settings.Default.EyeLinePosition;
if (Settings.Default.TalentWindowVisible)
{
ToggleTalentWindow();
}
MainWindowState = Settings.Default.MainWindowState;
ReceiveGlobalKeystrokes = Settings.Default.ReceiveGlobalKeystrokes;
}
public void SetDocumentConfig()
{
string colorScheme = Settings.Default.ColorScheme;
if (colorScheme != null && colorScheme.ToLowerInvariant() == "whiteonblack")
{
if (IsWhiteOnBlack)
{
SetWhiteOnBlack();
}
IsWhiteOnBlack = true;
IsBlackOnWhite = false;
}
else
{
if (IsBlackOnWhite)
{
SetBlackOnWhite();
}
IsBlackOnWhite = true;
IsWhiteOnBlack = false;
}
FontSize = Settings.Default.FontSize;
LineHeight = Settings.Default.LineHeight;
LoadBookmarks(MainDocument);
TextMarginValue = Settings.Default.TextMarginValue;
OuterLeftRightMarginValue = Settings.Default.OuterLeftRightMarginValue;
EyelineHeight = Settings.Default.EyelineHeight;
EyelineWidth = Settings.Default.EyelineWidth;
}
public void LoadDocument(string fullFilePath)
{
try
{
string ext = Path.GetExtension(fullFilePath).ToLowerInvariant();
string dataFormat = DataFormats.Rtf;
if (ext.EndsWith("xaml"))
{
dataFormat = DataFormats.Xaml;
}
else if (ext.EndsWith("txt"))
{
dataFormat = DataFormats.Text;
}
using (var fStream = new FileStream(fullFilePath, FileMode.Open))
{
LoadDocument(fStream, dataFormat);
}
if (fullFilePath == DocumentPath)
{
IsDocumentDirty = false;
}
WatchDocumentForChanges(_documentPath, Document_Changed);
}
catch (Exception ex)
{
Debug.Write(ex.Message);
}
}
private void LoadDocument(Stream documentStream, string dataFormat)
{
documentStream.Seek(0, SeekOrigin.Begin);
DocumentHelpers.LoadDocument(documentStream, MainDocument, dataFormat);
SetDocumentConfig();
SetColorScheme();
}
public void SaveDocument(string fullFilePath)
{
TextRange range;
FileStream fStream;
try
{
UnWatchDocumentForChanges(fullFilePath, Document_Changed);
range = new TextRange(MainDocument.ContentStart, MainDocument.ContentEnd);
using (fStream = new FileStream(fullFilePath, FileMode.Create))
{
DocumentHelpers.SaveDocument(fStream, MainDocument, DataFormats.Rtf);
}
if (fullFilePath == DocumentPath)
{
IsDocumentDirty = false;
}
string xamlPath = Path.Combine(Path.GetDirectoryName(fullFilePath),
Path.GetFileNameWithoutExtension(fullFilePath) + ".xaml");
using (fStream = new FileStream(xamlPath, FileMode.Create))
{
DocumentHelpers.SaveDocument(fStream, MainDocument, DataFormats.Xaml);
}
}
finally
{
WatchDocumentForChanges(fullFilePath, Document_Changed);
}
}
private void WatchDocumentForChanges(string fullFilePath, Action<object, FileSystemEventArgs> onChangedAction)
{
if (!WatchedFiles.ContainsKey(fullFilePath))
{
var fsw = new FileSystemWatcher();
fsw.BeginInit();
fsw.Path = Path.GetDirectoryName(fullFilePath);
fsw.Filter = Path.GetFileName(fullFilePath);
fsw.IncludeSubdirectories = false;
fsw.NotifyFilter = NotifyFilters.LastWrite;
fsw.Changed += onChangedAction.Invoke;
fsw.EnableRaisingEvents = true;
fsw.EndInit();
WatchedFiles.Add(fullFilePath, fsw);
}
}
private void UnWatchDocumentForChanges(string fullFilePath, Action<object, FileSystemEventArgs> onChangedAction)
{
if (WatchedFiles.ContainsKey(fullFilePath))
{
WatchedFiles[fullFilePath].Changed -= onChangedAction.Invoke;
WatchedFiles[fullFilePath].EnableRaisingEvents = false;
WatchedFiles[fullFilePath].Dispose();
WatchedFiles.Remove(fullFilePath);
}
}
private void Document_Changed(object sender, FileSystemEventArgs e)
{
try
{
ChangeSemaphore.Wait();
var storeStream = new MemoryStream();
using (FileStream filestream = File.OpenRead(e.FullPath))
{
storeStream.SetLength(filestream.Length);
filestream.Read(storeStream.GetBuffer(), 0, (int) filestream.Length);
storeStream.Flush();
}
Application.Current.Dispatcher.Invoke((Action) (() =>
{
DocumentHelpers.LoadDocument(storeStream,
MainDocument,
DataFormats.Rtf);
storeStream.Dispose();
SetDocumentConfig();
}));
}
catch (Exception)
{
}
finally
{
ChangeSemaphore.Release();
}
}
private void SetColorScheme()
{
if (IsBlackOnWhite)
{
SetBlackOnWhite();
}
else if (IsWhiteOnBlack)
{
SetWhiteOnBlack();
}
}
private void SetWhiteOnBlack()
{
MainDocument.Background = Brushes.Black;
DocumentHelpers.ChangePropertyValue(MainDocument, TextElement.ForegroundProperty, Brushes.White,
Brushes.Black);
DocumentHelpers.ChangePropertyValue(MainDocument, TextElement.BackgroundProperty, Brushes.Black,
Brushes.White);
if (_configInitialized)
AppConfigHelper.SetUserSetting("ColorScheme", "WhiteOnBlack");
MainDocumentCaretBrush = Brushes.White;
}
private void SetBlackOnWhite()
{
MainDocument.Background = Brushes.White;
DocumentHelpers.ChangePropertyValue(MainDocument, TextElement.ForegroundProperty, Brushes.Black,
Brushes.White);
DocumentHelpers.ChangePropertyValue(MainDocument, TextElement.BackgroundProperty, Brushes.White,
Brushes.Black);
if (_configInitialized)
AppConfigHelper.SetUserSetting("ColorScheme", "BlackOnWhite");
MainDocumentCaretBrush = Brushes.Black;
}
public void EditInWordpad()
{
KillWordPadProcess();
//Cancelled from saving document
if (string.IsNullOrWhiteSpace(DocumentPath))
{
return;
}
TempDocumentPath = Path.Combine(Path.GetTempPath(), Path.GetFileName(DocumentPath));
using (var ms = new MemoryStream())
{
DocumentHelpers.SaveDocument(ms, MainDocument, DataFormats.Rtf);
// SaveDocument(_tempDocumentPath);
var tempDoc = new FlowDocument();
DocumentHelpers.LoadDocument(ms, tempDoc, DataFormats.Rtf);
ConvertDocumentToEditableFormat(tempDoc);
using (FileStream tempFileStream = File.OpenWrite(_tempDocumentPath))
{
DocumentHelpers.SaveDocument(tempFileStream, tempDoc, DataFormats.Rtf);
}
}
WatchDocumentForChanges(_tempDocumentPath, Document_Changed);
var info = new ProcessStartInfo();
info.Arguments = string.Format("\"{0}\"", _tempDocumentPath);
info.FileName = "wordpad.exe";
_wordpadProcess = Process.Start(info);
}
public static void ConvertDocumentToEditableFormat(FlowDocument document)
{
DocumentHelpers.ChangePropertyValue(document, TextElement.FontSizeProperty, (double) 12);
DocumentHelpers.ChangePropertyValue(document, TextElement.ForegroundProperty, Brushes.Black, Brushes.White);
DocumentHelpers.ChangePropertyValue(document, TextElement.BackgroundProperty, Brushes.White, Brushes.Black);
}
private void LoadBookmarks(FlowDocument document)
{
Bookmarks.Clear();
IEnumerable<Hyperlink> hyperlinks = document.GetLogicalChildren<Hyperlink>(true);
foreach (Hyperlink hyperlink in hyperlinks)
{
AddBookmarkFromHyperlink(hyperlink);
}
}
private void AddBookmarkFromHyperlink(Hyperlink hyperlink)
{
if (hyperlink.NavigateUri.IsAbsoluteUri && hyperlink.NavigateUri.Host.StartsWith("bookmark"))
{
var bm = new Bookmark();
bm.Name = Uri.UnescapeDataString(hyperlink.NavigateUri.Segments[1]);
bm.Hyperlink = hyperlink;
CalculateBookMarkInfo(bm);
Bookmarks.Add(bm);
bm.Ordinal = Bookmarks.Count;
//bm.Image = (hyperlink.Inlines.FirstInline as InlineUIContainer).Child as Image;
// bm.Image.Height = FontSizeSlider.Value;
}
}
private void SaveDocumentAs(string documentPath)
{
var dlg = new SaveFileDialog();
if (!string.IsNullOrWhiteSpace(documentPath))
{
dlg.FileName = Path.GetFileName(documentPath);
dlg.InitialDirectory = Path.GetDirectoryName(documentPath);
}
else
{
dlg.FileName = "untitled"; // Default file name
}
dlg.DefaultExt = ".rtf"; // Default file extension
dlg.Filter = "Rich Text Documents|*.rtf"; // Filter files by extension
// Show save file dialog box
bool? result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
DocumentPath = dlg.FileName;
if (!string.IsNullOrWhiteSpace(DocumentPath))
{
SaveDocument(DocumentPath);
}
}
}
private void LoadDocumentDialog(string documentPath)
{
var dlg = new OpenFileDialog();
if (!string.IsNullOrWhiteSpace(documentPath))
{
dlg.FileName = Path.GetFileName(documentPath);
dlg.InitialDirectory = Path.GetDirectoryName(documentPath);
dlg.Multiselect = false;
dlg.Title = "Load document for Proverb Teleprompter...";
}
dlg.DefaultExt = ".rtf"; // Default file extension
dlg.Filter = "Rich Text Documents|*.rtf|XAML Documents|*.xaml|Text Documents|*.txt";
// Filter files by extension
// Show save file dialog box
bool? result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Load document
DocumentPath = dlg.FileName;
if (!string.IsNullOrWhiteSpace(DocumentPath))
{
LoadDocument(DocumentPath);
}
}
}
private void InsertBookmarkAtCurrentEyelineMark()
{
double bookmarkOffset = MainScrollerVerticalOffset + EyelinePosition + (EyelineHeight / 2);
var bm = new Bookmark();
CalculateBookMarkInfo(bm, bookmarkOffset);
bm.Ordinal = Bookmarks.Count;
Bookmarks.Add(bm);
}
private void JumpToBookmark(Bookmark bookmark)
{
if (bookmark == null) return;
var rect = bookmark.Hyperlink.ContentStart.GetCharacterRect(LogicalDirection.Forward);
MainScrollerVerticalOffset = rect.Top - EyelinePosition;
_mainTextBox.CaretPosition = bookmark.Hyperlink.ContentStart;
SelectedBookmark = bookmark;
}
private void JumpToBookmarkByOrdinal(int ordinal)
{
int ct = 0;
foreach (Bookmark bookmark in Bookmarks)
{
ct++;
if (ct == ordinal)
{
JumpToBookmark(bookmark);
return;
}
}
}
public bool CanShutDownApp()
{
if (IsDocumentDirty)
{
string caption = "The document has unsaved changes, would you like to save them?";
if (!string.IsNullOrWhiteSpace(DocumentPath))
{
caption = string.Format("The document: {0} has unsaved changed, do you want to save them?",
DocumentPath);
}
MessageBoxResult result = MessageBox.Show(caption, caption, MessageBoxButton.YesNoCancel,
MessageBoxImage.Warning);
if (result == MessageBoxResult.Yes)
{
if(!string.IsNullOrWhiteSpace(DocumentPath) && File.Exists(DocumentPath))
{
SaveDocument(DocumentPath);
}
else
{
SaveDocumentAs(DocumentPath);
}
}
else if (result == MessageBoxResult.Cancel)
{
return false;
}
}
return true;
}
private void KillWordPadProcess()
{
if (_wordpadProcess != null && !_wordpadProcess.HasExited)
{
_wordpadProcess.CloseMainWindow();
_wordpadProcess.Close();
}
}
public void ToggleToolsWindow()
{
if (_toolsWindow == null)
{
_toolsWindow = new ToolsWindow();
_toolsWindow.DataContext = this;
_toolsWindow.Owner = Application.Current.MainWindow;
_toolsWindow.Topmost = true;
// _toolsWindow.ShowActivated = false;
_toolsWindow.PreviewKeyDown += KeyDown;
_toolsWindow.PreviewKeyUp += KeyUp;
_toolsWindow.Closing += _toolsWindow_Closing;
_toolsWindow.Loaded += _toolsWindow_Loaded;
}
if (_toolsWindow.Visibility == Visibility.Visible)
{
_toolsWindow.Visibility = Visibility.Collapsed;
_toolsWindow.Hide();
}
else
{
_toolsWindow.Show();
}
}
private void _toolsWindow_Loaded(object sender, RoutedEventArgs e)
{
var area = Screen.PrimaryScreen.WorkingArea;
var winHeight = ConvertFromDIPixelsToPixels(_toolsWindow.ActualHeight);
var winWidth = ConvertFromDIPixelsToPixels(_toolsWindow.Width);
var winTop = area.Height - winHeight;
_toolsWindow.Top = ConvertPixelsToDIPixels(area.Height - winHeight);
var leftPixels = area.Width/2.0 - winWidth/2.0;
//Check if right edge will be off screen
if(leftPixels + winWidth > area.Width)
{
_toolsWindow.SizeToContent = SizeToContent.Manual;
//resize and re-center
winWidth = area.Width;
leftPixels = 0;
_toolsWindow.Width = ConvertPixelsToDIPixels(winWidth);
_toolsWindow.Height = ConvertPixelsToDIPixels(winHeight);
}
_toolsWindow.Left = ConvertPixelsToDIPixels(leftPixels);
}
[DllImport("User32.dll")]
private static extern IntPtr GetDC(HandleRef hWnd);
[DllImport("User32.dll")]
private static extern int ReleaseDC(HandleRef hWnd, HandleRef hDC);
[DllImport("GDI32.dll")]
private static extern int GetDeviceCaps(HandleRef hDC, int nIndex);
private static int _dpi = 0;
public static int Dpi
{
get
{
if (_dpi == 0)
{
var desktopHwnd = new HandleRef(null, IntPtr.Zero);
var desktopDC = new HandleRef(null, GetDC(desktopHwnd));
try
{
_dpi = GetDeviceCaps(desktopDC, 88/*LOGPIXELSX*/);
}
finally
{
ReleaseDC(desktopHwnd, desktopDC);
}
}
return _dpi;
}
}
public static double ConvertPixelsToDIPixels(double pixels)
{
return (double)pixels * 96 / Dpi;
}
public static double ConvertFromDIPixelsToPixels(double pixels)
{
return (double)pixels / 96 * Dpi;
}
private static void _toolsWindow_Closing(object sender, CancelEventArgs e)
{
e.Cancel = true;
((Window) sender).Owner.Close();
}
#region Input Handlers
internal void GlobalKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
var key = KeyInterop.KeyFromVirtualKey(e.KeyValue);
if(!e.Alt && !e.Shift && !e.Control)
HandleKeyDown(key, true);
}
internal void GlobalKeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
var key = KeyInterop.KeyFromVirtualKey(e.KeyValue);
HandleKeyUp(key, true);
}
internal void KeyDown(object sender, KeyEventArgs e)
{
if (!ReceiveGlobalKeystrokes)
{
e.Handled = HandleKeyDown(e.Key, false);
}
}
internal void KeyUp(object sender, KeyEventArgs e)