File size: 54,213 Bytes
b1b3bae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
'Copyright (C) 2002 Microsoft Corporation
'All rights reserved.
'
'THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
'EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
'MERCHANTIBILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
'
'Date: June 2002
'Author: Duncan Mackenzie
'
'Requires the release version of .NET Framework

Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Runtime.Serialization
Imports System.Linq
Imports System.Collections.Generic
Imports System.Windows.Forms
Imports DWSIM.DrawingTools.GraphicObjects
Imports DWSIM.Interfaces.Enums.GraphicObjects

<System.Serializable()> Public Class GraphicsSurface

    Inherits System.Windows.Forms.UserControl

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call
        Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True)
        Me.SetStyle(ControlStyles.DoubleBuffer, True)
        Me.SetStyle(ControlStyles.UserPaint, True)
        Me.SetStyle(ControlStyles.ResizeRedraw, True)
    End Sub

    'UserControl1 overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.SuspendLayout()
        '
        'GraphicsSurface
        '
        Me.AutoScroll = True
        Me.BackColor = System.Drawing.SystemColors.Window
        Me.Name = "GraphicsSurface"
        Me.ResumeLayout(False)

    End Sub

#End Region

#Region "Events"

    Public Event SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
    Public Event StatusUpdate(ByVal sender As Object, ByVal e As StatusUpdateEventArgs)
#End Region

    Private Const MinimumGridSize As Single = 10
    Private dragOffset As New Point(0, 0)
    Private dragStart As New Point(0, 0)

    Public selectionDragging As Boolean = False
    Private selectable As Boolean = True
    Public dragging As Boolean = False
    Private draggingfs As Boolean = False
    Private rotating As Boolean = False
    Private hoverdraw As Boolean = False
    Private startingRotation As Single = 0
    Private originalRotation As Single = 0
    Private selectionRect As Rectangle
    Private rectp0 As New Point
    Private hoverRect As Rectangle
    Private hoverrotation As Integer = 0
    Private Size0 As Size

    Private justselected As Boolean = False

    Private m_SurfaceBounds As New Rectangle(0, 0, 10000, 7000)
    Private m_SurfaceMargins As New Rectangle(10, 10, 10000, 7000)
    Public m_HorizRes As Integer = 300
    Public m_VertRes As Integer = 300
    Private m_ShowGrid As Boolean = True
    Private m_NonPrintingAreaColor As Color = Color.Gray
    Private m_GridColor As Color = Color.LightBlue
    Private m_GridSize As Single = 50
    Private m_GridLineWidth As Integer = 1
    Private m_MarginLineWidth As Integer = 1
    Private m_MarginColor As Color = Color.Green
    Private m_SelectedObject As GraphicObject
    Private m_Zoom As Single = 0.5

    Private m_snaptogrid As Boolean = False
    Private m_mousehoverselect As Boolean = False
    Private m_quickconnectmode As Boolean = False

    Public m_drawingObjects As New GraphicObjectCollection()

    Public m_SelectedObjects As New Collections.Generic.Dictionary(Of String, GraphicObject)

    Public Enum AlignDirection
        Lefts
        Centers
        Rights
        Tops
        Middles
        Bottoms
        EqualizeHorizontal
        EqualizeVertical
    End Enum

#Region "Saving / Loading"

    Public Overridable Sub LoadFromFile(ByVal fileName As String)
        'load objects from a binary file
        Try
            Dim settingsPath As String = fileName
            Dim myBinarySerializer As New Formatters.Binary.BinaryFormatter()
            m_drawingObjects = myBinarySerializer.Deserialize( _
                New IO.FileStream(settingsPath, IO.FileMode.Open))
            Me.SelectedObject = Nothing
            RaiseEvent StatusUpdate(Me, _
                New StatusUpdateEventArgs(StatusUpdateType.FileLoaded, _
                Nothing, String.Format("file {0} loaded into the Graphic Surface", fileName), _
                Nothing, Nothing))
            Me.Invalidate()
        Catch e As Exception
            Throw New ApplicationException("File failed to load.", e)
        End Try

    End Sub


    Public Overridable Sub SaveToFile(ByVal fileName As String)
        'save objects to a binary file
        Try
            Dim settingsPath As String = fileName
            Dim myBinarySerializer As New Formatters.Binary.BinaryFormatter()
            myBinarySerializer.Serialize( _
                New IO.FileStream(settingsPath, IO.FileMode.Create), _
                Me.DrawingObjects)
            RaiseEvent StatusUpdate(Me, _
                New StatusUpdateEventArgs(StatusUpdateType.FileSaved, _
                m_SelectedObject, _
                String.Format("Graphic Surface saved to file {0}", fileName), _
                Nothing, Nothing))
        Catch e As Exception
            Throw New ApplicationException("Save Failed.", e)
        End Try
    End Sub

#End Region

    <Xml.Serialization.XmlIgnore> <NonSerialized> Private _editorform As System.Windows.Forms.Form

    Public Property Editor As Form
        Get
            Return _editorform
        End Get
        Set(value As Form)
            _editorform = value
        End Set
    End Property

    Public Property ResizingMode As Boolean = False
    Public Property ResizingMode_KeepAR As Boolean = True

    Public Property QuickConnect() As Boolean
        Get
            Return m_quickconnectmode
        End Get
        Set(ByVal value As Boolean)
            m_quickconnectmode = value
        End Set
    End Property

    Public Property SurfaceBounds() As Rectangle
        'bounds in 1/100ths of an inch, just like the printer objects use
        Get
            Return m_SurfaceBounds
        End Get
        Set(ByVal Value As Rectangle)
            m_SurfaceBounds = Value
            Me.Invalidate()
        End Set
    End Property

    Public Property SnapToGrid() As Boolean
        Get
            Return m_snaptogrid
        End Get
        Set(ByVal value As Boolean)
            m_snaptogrid = value
        End Set
    End Property

    Public Property MouseHoverSelect() As Boolean
        Get
            Return m_mousehoverselect
        End Get
        Set(ByVal value As Boolean)
            m_mousehoverselect = value
        End Set
    End Property

    Public Property SurfaceMargins() As Rectangle
        'bounds in 1/100ths of an inch, just like the printer objects use
        Get
            Return m_SurfaceMargins
        End Get
        Set(ByVal Value As Rectangle)
            m_SurfaceMargins = Value
        End Set
    End Property

    Public Property Zoom() As Single
        Get
            Return m_Zoom
        End Get
        Set(ByVal Value As Single)
            Dim xp, yp As Double
            xp = Me.HorizontalScroll.Value / (m_Zoom * Me.Width)
            yp = Me.VerticalScroll.Value / (m_Zoom * Me.Height)
            If Value > 0.05 Then
                If Value > 100 Then
                    m_Zoom = 100.0#
                    Me.Invalidate()
                    Me.HorizontalScroll.Value = xp * 100.0# * Me.Width
                    Me.VerticalScroll.Value = yp * 100.0# * Me.Height
                    Me.Invalidate()
                Else
                    m_Zoom = Value
                    Me.Invalidate()
                    If Not xp * Value * Me.Width < Me.HorizontalScroll.SmallChange And Not xp * Value * Me.Width > Me.HorizontalScroll.Maximum Then
                        Me.HorizontalScroll.Value = Convert.ToInt32(xp * Value * Me.Width)
                    End If
                    If Not yp * Value * Me.Height < Me.HorizontalScroll.SmallChange And Not yp * Value * Me.Height > Me.VerticalScroll.Maximum Then
                        Me.VerticalScroll.Value = Convert.ToInt32(yp * Value * Me.Height)
                    End If
                    Me.Invalidate()
                End If
            Else
                m_Zoom = 0.05
                Me.Invalidate()
                Me.HorizontalScroll.Value = xp * 0.05 * Me.Width
                Me.VerticalScroll.Value = yp * 0.05 * Me.Height
                Me.Invalidate()
            End If
        End Set
    End Property

    Public Property SelectRectangle() As Boolean
        Get
            Return selectable
        End Get
        Set(ByVal Value As Boolean)
            selectable = Value
        End Set
    End Property

    Public Overridable ReadOnly Property DrawingObjects() As GraphicObjectCollection
        Get
            Return m_drawingObjects
        End Get
    End Property

    Public Overridable Property MarginColor() As Color
        Get
            Return m_MarginColor
        End Get
        Set(ByVal Value As Color)
            m_MarginColor = Value
        End Set
    End Property

    Public Overridable Property MarginLineWidth() As Integer
        Get
            Return m_MarginLineWidth
        End Get
        Set(ByVal Value As Integer)
            If Value > 0 Then
                m_MarginLineWidth = Value
            Else
                Throw New ArgumentOutOfRangeException("MarginLineWidth", _
                    "MarginLineWidth must be greater than zero")
            End If
        End Set
    End Property

    Public Overridable Property ShowGrid() As Boolean
        Get
            Return m_ShowGrid
        End Get
        Set(ByVal Value As Boolean)
            m_ShowGrid = False
        End Set
    End Property

    Public Overridable Property GridColor() As Color
        Get
            Return m_GridColor
        End Get
        Set(ByVal Value As Color)
            m_GridColor = Value
        End Set
    End Property

    Public Overridable Property NonPrintingAreaColor() As Color
        Get
            Return m_NonPrintingAreaColor
        End Get
        Set(ByVal Value As Color)
            m_NonPrintingAreaColor = Value
        End Set
    End Property

    Public Overridable Property GridLineWidth() As Integer
        Get
            Return m_GridLineWidth
        End Get
        Set(ByVal Value As Integer)
            If Value > 0 Then
                m_GridLineWidth = Value
            Else
                Throw New ArgumentOutOfRangeException("GridLineWidth", _
                    "GridLineWidth must be greater than zero")
            End If
        End Set
    End Property

    Public Overridable Property GridSize() As Single
        'in 100ths of an inch
        Get
            Return m_GridSize
        End Get
        Set(ByVal Value As Single)
            If Value > MinimumGridSize Then
                m_GridSize = Value
            Else
                Throw New ArgumentOutOfRangeException("GridSize", _
                        String.Format("Grid Size must be greater than {0}", MinimumGridSize))
            End If
        End Set
    End Property

    Public Property DrawFloatingTables As Boolean = True

    Public Property DrawPropertyLists As Boolean = False

    Protected Function ConvertToHPixels(ByVal value As Single) As Single
        Return value * Me.m_HorizRes
    End Function

    Protected Function ConvertToVPixels(ByVal value As Single) As Single
        Return value * Me.m_VertRes
    End Function

    Protected Function ConvertToPixels(ByVal rect As Rectangle) As Rectangle
        'convert from 100ths of an inch to pixels
        Dim Bounds As Rectangle
        Bounds = New Rectangle(ConvertToHPixels(rect.X / 100), _
            ConvertToVPixels(rect.Y / 100), _
            ConvertToHPixels(rect.Width / 100), _
            ConvertToVPixels(rect.Height / 100))
        Return Bounds
    End Function

    Protected Function ZoomRectangle(ByVal originalRect As Rectangle) As Rectangle
        Dim myNewRect As New Rectangle(originalRect.X * Me.Zoom, _
                originalRect.Y * Me.Zoom, _
                originalRect.Width * Me.Zoom, _
                originalRect.Height * Me.Zoom)
        Return myNewRect
    End Function

    Protected Function DeZoomRectangle(ByVal originalRect As Rectangle) As Rectangle
        Dim myNewRect As New Rectangle(originalRect.X / Me.Zoom, _
                originalRect.Y / Me.Zoom, _
                originalRect.Width / Me.Zoom, _
                originalRect.Height / Me.Zoom)
        Return myNewRect
    End Function

    Public Overridable Sub DrawGrid(ByVal g As Graphics)
        Dim bounds As Rectangle
        Dim horizGridSize As Integer = ConvertToHPixels(GridSize / 100) '* Me.Zoom
        Dim vertGridSize As Integer = ConvertToVPixels(GridSize / 100) '* Me.Zoom
        bounds = ConvertToPixels(SurfaceBounds)
        bounds = ZoomRectangle(bounds)
        If Me.AutoScrollMinSize.Height <> bounds.Height _
            AndAlso Me.AutoScrollMinSize.Width <> bounds.Width Then
            Me.AutoScrollMinSize = New Size(bounds.Width, bounds.Height)
        End If

        g.Clear(m_NonPrintingAreaColor)
        g.FillRectangle(New SolidBrush(Me.BackColor), bounds)

        Dim gridPen As New Pen(GridColor, m_GridLineWidth)
        'gridPen.DashStyle = DashStyle.Dot
        Dim i As Integer
        For i = vertGridSize To bounds.Height Step vertGridSize
            g.DrawLine(gridPen, 0, i, bounds.Width, i)
        Next
        For i = horizGridSize To bounds.Width Step horizGridSize
            g.DrawLine(gridPen, i, 0, i, bounds.Height)
        Next
    End Sub

    Protected Overridable Sub DrawMargins(ByVal g As Graphics)
        Dim margins As Rectangle = ZoomRectangle(ConvertToPixels(Me.m_SurfaceMargins))
        Dim marginPen As New Pen(m_MarginColor)
        marginPen.DashStyle = Drawing2D.DashStyle.Dash
        marginPen.Width = m_MarginLineWidth
        g.DrawRectangle(marginPen, margins)
    End Sub

    Public Function IsRunningOnMono() As Boolean
        Return Not Type.GetType("Mono.Runtime") Is Nothing
    End Function

    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)

        'Try
        Dim g As Graphics = e.Graphics

        With g

            If Not dragging Then

                .InterpolationMode = InterpolationMode.Bilinear
                .PixelOffsetMode = PixelOffsetMode.HighSpeed
                .CompositingMode = CompositingMode.SourceOver
                .CompositingQuality = CompositingQuality.HighSpeed
                .TextRenderingHint = Drawing.Text.TextRenderingHint.SystemDefault
                .SmoothingMode = SmoothingMode.AntiAlias

            Else

                .InterpolationMode = InterpolationMode.NearestNeighbor
                .PixelOffsetMode = PixelOffsetMode.HighSpeed
                .CompositingMode = CompositingMode.SourceOver
                .CompositingQuality = CompositingQuality.HighSpeed
                .TextRenderingHint = Drawing.Text.TextRenderingHint.SingleBitPerPixel
                .SmoothingMode = SmoothingMode.None

            End If

        End With


        'get the dpi settings of the graphics context,
        'for example; 96dpi on screen, 600dpi for the printer
        'used to adjust grid and margin sizing.

        Me.m_HorizRes = g.DpiX
        Me.m_VertRes = g.DpiY

        'handle the possibility that the viewport is scrolled,
        'adjust my origin coordintates to compensate
        Dim pt As Point = New Point(Me.AutoScrollPosition.X, Me.AutoScrollPosition.Y)
        g.TranslateTransform(pt.X, pt.Y)

        DrawGrid(g)

        If hoverdraw Then

            Dim myOriginalMatrix As New Drawing2D.Matrix

            Dim gCon1 As Drawing2D.GraphicsContainer = g.BeginContainer

            If Not IsRunningOnMono() Then myOriginalMatrix = g.Transform()

            If hoverrotation <> 0 Then
                myOriginalMatrix.RotateAt(hoverrotation, New PointF((hoverRect.X + hoverRect.Width / 2) * Zoom, (hoverRect.Y + hoverRect.Height / 2) * Zoom), _
                    Drawing2D.MatrixOrder.Append)
                g.Transform = myOriginalMatrix
            End If

            g.ScaleTransform(Zoom, Zoom)

            g.PageUnit = GraphicsUnit.Pixel

            Dim color1, color2, color3 As Color
            color1 = Color.FromArgb(50, 170, 215, 230)
            color2 = Color.FromArgb(50, 2, 140, 140)
            color3 = Color.FromArgb(50, 2, 140, 140)

            Dim gbrush As New LinearGradientBrush(hoverRect, color1, color2, LinearGradientMode.Vertical)
            DrawRoundRect(g, New Pen(color3, 1), hoverRect.X, hoverRect.Y, hoverRect.Width, hoverRect.Height, 15, gbrush)

            If Not IsRunningOnMono() Then g.Transform = myOriginalMatrix
            g.EndContainer(gCon1)

        End If

        'draw the actual objects onto the page, on top of the grid

        If Me.SelectedObject Is Nothing Then Me.SelectedObjects.Clear()

        For Each gr As GraphicObject In Me.SelectedObjects.Values
            gr.Selected = True
            Me.DrawingObjects.DrawSelectedObject(g, gr, Me.Zoom)
        Next

        For Each gr As GraphicObject In Me.DrawingObjects
            If Not Me.SelectedObjects.ContainsKey(gr.Name) Then gr.Selected = False
        Next

        With Me.DrawingObjects
            .HorizontalResolution = g.DpiX
            .VerticalResolution = g.DpiY
            .DrawObjects(g, Me.Zoom, dragging)
        End With

        If DrawPropertyLists Then
            For Each gr As GraphicObject In Me.DrawingObjects
                If gr.Calculated Then
                    DrawPropertyListBlock(g, gr)
                End If
            Next
        End If

        'Draw dashed line margin indicators, over top of objects
        DrawMargins(g)

        'draw selection rectangle (click and drag to select interface)
        'on top of everything else, but transparent
        If selectionDragging Then
            DrawSelectionRectangle(g, selectionRect)
        End If
        'Catch ex As System.Exception
        'Debug.WriteLine(ex.ToString)
        'Throw New System.ApplicationException("Error Drawing Graphics Surface", ex)
        ' End Try

        If ResizingMode Then
            For Each obj In DrawingObjects
                If obj.ObjectType <> ObjectType.Nenhum And obj.ObjectType <> ObjectType.GO_FloatingTable And
                    obj.ObjectType <> ObjectType.GO_MasterTable And obj.ObjectType <> ObjectType.GO_SpreadsheetTable And
                    obj.ObjectType <> ObjectType.GO_Table Then
                    DrawResizingAnchors(g, Me.Zoom, obj)
                End If
            Next
        End If

    End Sub

    Sub DrawResizingAnchors(g As Graphics, Scale As Single, gobj As GraphicObject)

        Dim gCon As Drawing2D.GraphicsContainer

        Dim myOriginalMatrix As Drawing2D.Matrix
        myOriginalMatrix = g.Transform()

        gCon = g.BeginContainer()

        g.PageUnit = GraphicsUnit.Pixel
        g.ScaleTransform(Scale, Scale)

        g.DrawRectangle(New Pen(Brushes.SteelBlue, 2), gobj.GetBoundsRectangle)

        g.DrawRectangle(New Pen(Brushes.SteelBlue, 2), gobj.X - 2, gobj.Y - 2, 4, 4)
        g.DrawRectangle(New Pen(Brushes.SteelBlue, 2), gobj.X + gobj.Width - 2, gobj.Y - 2, 4, 4)
        g.DrawRectangle(New Pen(Brushes.SteelBlue, 2), gobj.X - 2, gobj.Y + gobj.Height - 2, 4, 4)
        g.DrawRectangle(New Pen(Brushes.SteelBlue, 2), gobj.X + gobj.Width - 2, gobj.Y + gobj.Height - 2, 4, 4)

        g.EndContainer(gCon)
        g.Transform = myOriginalMatrix

    End Sub


    Protected Overrides Function IsInputKey(ByVal keyData As Keys) As Boolean
        Select Case keyData
            Case Keys.Up
                Return True
            Case Keys.Down
                Return True
            Case Keys.Left
                Return True
            Case Keys.Right
                Return True
            Case Else
                Return MyBase.IsInputKey(keyData)
        End Select
    End Function

    Public Sub AlignSelectedObjects(direction As AlignDirection)

        If Me.SelectedObjects.Count > 1 Then

            Dim refpos As Integer = 0

            Select Case direction
                Case AlignDirection.Lefts
                    refpos = 10000000
                    For Each obj As GraphicObject In Me.SelectedObjects.Values
                        If obj.X < refpos Then refpos = obj.X
                    Next
                    For Each obj As GraphicObject In Me.SelectedObjects.Values
                        obj.X = refpos
                    Next
                Case AlignDirection.Centers
                    For Each obj As GraphicObject In Me.SelectedObjects.Values
                        refpos += obj.X + obj.Width / 2
                    Next
                    refpos /= Me.SelectedObjects.Count
                    For Each obj As GraphicObject In Me.SelectedObjects.Values
                        obj.X = refpos - obj.Width / 2
                    Next
                Case AlignDirection.Rights
                    For Each obj As GraphicObject In Me.SelectedObjects.Values
                        refpos += obj.X + obj.Width
                    Next
                    refpos /= Me.SelectedObjects.Count
                    For Each obj As GraphicObject In Me.SelectedObjects.Values
                        obj.X = refpos - obj.Width
                    Next
                Case AlignDirection.Tops
                    refpos = 10000000
                    For Each obj As GraphicObject In Me.SelectedObjects.Values
                        If obj.Y < refpos Then refpos = obj.Y
                    Next
                    For Each obj As GraphicObject In Me.SelectedObjects.Values
                        obj.Y = refpos
                    Next
                Case AlignDirection.Middles
                    For Each obj As GraphicObject In Me.SelectedObjects.Values
                        refpos += obj.Y + obj.Height / 2
                    Next
                    refpos /= Me.SelectedObjects.Count
                    For Each obj As GraphicObject In Me.SelectedObjects.Values
                        obj.Y = refpos - obj.Height / 2
                    Next
                Case AlignDirection.Bottoms
                    For Each obj As GraphicObject In Me.SelectedObjects.Values
                        refpos += obj.Y + obj.Height
                    Next
                    refpos /= Me.SelectedObjects.Count
                    For Each obj As GraphicObject In Me.SelectedObjects.Values
                        obj.Y = refpos - obj.Height
                    Next
                Case AlignDirection.EqualizeHorizontal
                    Dim orderedlist As List(Of GraphicObject) = Me.SelectedObjects.Values.OrderBy(Function(o) o.X).ToList
                    Dim avgdist As Integer, i As Integer
                    For i = 1 To orderedlist.Count - 1
                        avgdist += (orderedlist(i).X) - (orderedlist(i - 1).X + orderedlist(i - 1).Width)
                    Next
                    avgdist /= (orderedlist.Count - 1)
                    For i = 1 To orderedlist.Count - 1
                        orderedlist(i).X = orderedlist(i - 1).X + orderedlist(i - 1).Width + avgdist
                    Next
                Case AlignDirection.EqualizeVertical
                    Dim orderedlist As List(Of GraphicObject) = Me.SelectedObjects.Values.OrderBy(Function(o) o.Y).ToList
                    Dim avgdist As Integer, i As Integer
                    For i = 1 To orderedlist.Count - 1
                        avgdist += (orderedlist(i).Y) - (orderedlist(i - 1).Y + orderedlist(i - 1).Height)
                    Next
                    avgdist /= (orderedlist.Count - 1)
                    For i = 1 To orderedlist.Count - 1
                        orderedlist(i).Y = orderedlist(i - 1).Y + orderedlist(i - 1).Height + avgdist
                    Next
            End Select

            Me.Invalidate()
            Application.DoEvents()
            Me.Invalidate()
            Application.DoEvents()

        End If

    End Sub

    Private Sub DrawSelectionRectangle(ByVal g As Graphics, _
            ByVal selectionRect As Rectangle)

        Dim selectionBrush As New SolidBrush(Color.FromArgb(25, Color.LightSalmon))
        Dim normalizedRectangle As Rectangle

        'make sure the rectangle's upper left point is
        'up and to the left relative to the other points of the rectangle by
        'ensuring that it has a positive width and height.
        normalizedRectangle.Size = selectionRect.Size
        If selectionRect.Width < 0 Then
            normalizedRectangle.X = selectionRect.X - normalizedRectangle.Width
        Else
            normalizedRectangle.X = selectionRect.X
        End If

        If selectionRect.Height < 0 Then
            normalizedRectangle.Y = selectionRect.Y - normalizedRectangle.Height
        Else
            normalizedRectangle.Y = selectionRect.Y
        End If

        g.FillRectangle(selectionBrush, normalizedRectangle)

    End Sub

    Public Overloads Function gscTogoc( _
            ByVal gsPT As Point) As Point
        Dim myNewPoint As New Point
        myNewPoint.X = Convert.ToInt32((gsPT.X - Me.AutoScrollPosition.X) / Me.Zoom)
        myNewPoint.Y = Convert.ToInt32((gsPT.Y - Me.AutoScrollPosition.Y) / Me.Zoom)
        Return myNewPoint
    End Function
    Public Overloads Function gscTogoc( _
            ByVal X As Integer, ByVal Y As Integer) As Point
        Dim myNewPoint As New Point
        myNewPoint.X = Convert.ToInt32((X - Me.AutoScrollPosition.X) / Me.Zoom)
        myNewPoint.Y = Convert.ToInt32((Y - Me.AutoScrollPosition.Y) / Me.Zoom)
        Return myNewPoint
    End Function

    Public Overloads Function gocTogsc( _
            ByVal goPT As Point) As Point
        'note that there is no need for a New for my Point
        'before I can assign values to X and Y
        'as it is a structure not an object
        Dim myNewPoint As New Point
        myNewPoint.X = Convert.ToInt32((goPT.X) * Me.Zoom)
        myNewPoint.Y = Convert.ToInt32((goPT.Y) * Me.Zoom)

        Return myNewPoint
    End Function
    Public Overloads Function gocTogsc( _
            ByVal X As Integer, ByVal Y As Integer) As Point
        Dim myNewPoint As New Point
        myNewPoint.X = Convert.ToInt32(X * Me.Zoom)
        myNewPoint.Y = Convert.ToInt32(Y * Me.Zoom)
        Return myNewPoint
    End Function

    Private Sub GraphicsSurface_MouseClick(ByVal sender As Object, _
            ByVal e As MouseEventArgs) _
            Handles MyBase.MouseDown

        Me.Invalidate()

        Dim mousePT As Point = gscTogoc(e.X, e.Y)

        dragStart = New Point(e.X, e.Y)

        Me.SelectedObject = Me.DrawingObjects.FindObjectAtPoint(mousePT)

        If Not SelectedObject Is Nothing Then Size0 = SelectedObject.GetSize

        If Not ResizingMode Then

            If Me.SelectedObject Is Nothing Then
                Me.SelectedObjects.Clear()
                justselected = False
                If My.Computer.Keyboard.ShiftKeyDown Then
                    draggingfs = True
                End If
            Else
                If My.Computer.Keyboard.CtrlKeyDown Then
                    If Not Me.SelectedObjects.ContainsKey(Me.SelectedObject.Name) Then
                        Me.SelectedObjects.Add(Me.SelectedObject.Name, Me.SelectedObject)
                    Else
                        Me.SelectedObjects.Remove(Me.SelectedObject.Name)
                    End If
                    justselected = True
                Else
                    If Not justselected Then Me.SelectedObjects.Clear()
                    If Not Me.SelectedObjects.ContainsKey(Me.SelectedObject.Name) Then
                        Me.SelectedObjects.Add(Me.SelectedObject.Name, Me.SelectedObject)
                    End If
                    justselected = False
                End If
            End If

            If Not m_SelectedObject Is Nothing Then
                If e.Button And Windows.Forms.MouseButtons.Right Then
                    'rotating = True
                    dragging = True
                    startingRotation = AngleToPoint(m_SelectedObject.GetPosition, mousePT)
                    originalRotation = m_SelectedObject.Rotation
                Else
                    dragging = True
                    dragOffset.X = m_SelectedObject.X - mousePT.X
                    dragOffset.Y = m_SelectedObject.Y - mousePT.Y
                End If
            Else
                If e.Button And Windows.Forms.MouseButtons.Left And Me.SelectRectangle And Not My.Computer.Keyboard.ShiftKeyDown Then
                    selectionDragging = True
                    rectp0.X = mousePT.X * Me.Zoom
                    rectp0.Y = mousePT.Y * Me.Zoom
                    selectionRect.Height = 0
                    selectionRect.Width = 0
                End If
            End If

        Else

            Cursor = Cursors.SizeNWSE

        End If

    End Sub

    Public Sub ZoomAll()

        Dim minx As Integer = 10000
        Dim miny As Integer = 10000
        Dim maxx As Integer = 0
        Dim maxy As Integer = 0

        For Each gobj As GraphicObject In Me.DrawingObjects
            If gobj.ObjectType <> ObjectType.Nenhum Then
                If gobj.X <= minx Then minx = gobj.X
                If gobj.X + gobj.Width >= maxx Then maxx = gobj.X + gobj.Width + 60
                If gobj.Y <= miny Then miny = gobj.Y
                If gobj.Y + gobj.Height >= maxy Then maxy = gobj.Y + gobj.Height + 60
            End If
        Next

        Dim windowheight, windowwidth, fsx, fsy, fsheight, fswidth As Integer

        windowheight = Me.Height
        windowwidth = Me.Width

        fsx = Me.HorizontalScroll.Value
        fsy = Me.VerticalScroll.Value
        fswidth = fsx + windowwidth
        fsheight = fsy + windowheight

        Dim newx, newy As Integer

        newx = minx - 30
        newy = miny - 30

        If newx < 0 Then newx = 0
        If newy < 0 Then newy = 0

        Dim zoomx As Double = 1.0#
        Dim zoomy As Double = 1.0#

        zoomx = windowwidth / (maxx - newx)
        zoomy = windowheight / (maxy - newy)

        If zoomx > zoomy Then Me.Zoom = zoomy Else Me.Zoom = zoomx

        If newx * Me.Zoom < Me.HorizontalScroll.Maximum Then Me.HorizontalScroll.Value = Convert.ToInt32(newx * Me.Zoom)
        If newy * Me.Zoom < Me.VerticalScroll.Maximum Then Me.VerticalScroll.Value = Convert.ToInt32(newy * Me.Zoom)

        Me.Invalidate()

    End Sub

    Public Sub Center()

        Dim minx As Integer = 10000
        Dim miny As Integer = 10000
        Dim maxx As Integer = 0
        Dim maxy As Integer = 0
        Dim middlex, middley As Integer

        For Each gobj As GraphicObject In Me.DrawingObjects
            If gobj.ObjectType <> ObjectType.Nenhum Then
                If gobj.X <= minx Then minx = gobj.X
                If gobj.X + gobj.Width >= maxx Then maxx = gobj.X + gobj.Width + 60
                If gobj.Y <= miny Then miny = gobj.Y
                If gobj.Y + gobj.Height >= maxy Then maxy = gobj.Y + gobj.Height + 60
            End If
        Next

        middlex = (minx + maxx) / 2
        middley = (miny + maxy) / 2



        Me.HorizontalScroll.Value = middlex * Me.Zoom - Me.Width / 2
        Me.VerticalScroll.Value = middley * Me.Zoom - Me.Height / 2

        Me.Invalidate()
        Me.Invalidate()

    End Sub

    Private Sub GraphicsSurface_MouseMove(ByVal sender As Object, _
            ByVal e As MouseEventArgs) Handles MyBase.MouseMove

        Dim dx As Integer = -(e.X - dragStart.X)
        Dim dy As Integer = -(e.Y - dragStart.Y)

        If Not ResizingMode Then

            If draggingfs Then
                If Not My.Computer.Keyboard.ShiftKeyDown Then
                    draggingfs = False
                    Cursor.Current = Cursors.Default
                Else
                    Cursor.Current = Cursors.Hand
                End If


                If Me.HorizontalScroll.Value + dx > Me.HorizontalScroll.Minimum Then
                    Me.HorizontalScroll.Value += dx
                Else
                    Me.HorizontalScroll.Value += Me.HorizontalScroll.Minimum
                End If
                If Me.VerticalScroll.Value + dy > Me.VerticalScroll.Minimum Then
                    Me.VerticalScroll.Value += dy
                Else
                    Me.VerticalScroll.Value += Me.VerticalScroll.Minimum
                End If
                dragStart = New Point(e.X, e.Y)
            Else
                'Cursor.Current = Cursors.Default
                If Not Me.QuickConnect Or Not My.Computer.Keyboard.CtrlKeyDown Then
                    Dim dragPoint As Point = gscTogoc(e.X, e.Y)

                    Dim obj As GraphicObject = Me.DrawingObjects.FindObjectAtPoint(dragPoint)

                    If Not obj Is Nothing Then
                        If obj.ObjectType <> ObjectType.GO_FloatingTable And obj.ObjectType <> ObjectType.GO_Text _
                        And obj.ObjectType <> ObjectType.GO_Image And obj.ObjectType <> ObjectType.GO_Table _
                        And obj.ObjectType <> ObjectType.Nenhum And obj.ObjectType <> ObjectType.GO_SpreadsheetTable _
                        And obj.ObjectType <> ObjectType.GO_MasterTable And obj.ObjectType <> ObjectType.GO_Rectangle Then
                            With Me.hoverRect
                                hoverrotation = obj.Rotation
                                .X = obj.X - 10
                                .Y = obj.Y - 10
                                Select Case obj.ObjectType
                                    Case ObjectType.GO_Animation, ObjectType.GO_Image, ObjectType.GO_Table, ObjectType.GO_FloatingTable, ObjectType.GO_Text, ObjectType.GO_MasterTable, ObjectType.GO_SpreadsheetTable, ObjectType.GO_Rectangle
                                        .Height = obj.Height + 20
                                        .Width = obj.Width + 20
                                    Case Else
                                        .Height = obj.Height + 30
                                        .Width = obj.Width + 20
                                        Dim g As Drawing.Graphics = Drawing.Graphics.FromHwnd(Me.Handle)
                                        Dim strdist As SizeF = g.MeasureString(obj.Tag, New Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel, 0, False), New PointF(0, 0), New StringFormat(StringFormatFlags.NoClip, 0))
                                        If strdist.Width > obj.Width Then
                                            .X = obj.X + (obj.Width - strdist.Width) / 2 - 10
                                            .Width = strdist.Width + 20
                                        End If
                                End Select
                            End With
                            hoverdraw = True
                        End If
                    Else
                        hoverdraw = False
                    End If

                    If Not m_SelectedObject Is Nothing Then

                        If Not m_SelectedObject.IsConnector And SelectRectangle Then

                            If dragging Then

                                Cursor.Current = Cursors.Hand

                                dragPoint.Offset(dragOffset.X, dragOffset.Y)
                                'm_SelectedObject.SetPosition(dragPoint)

                                For Each gr As GraphicObject In Me.SelectedObjects.Values
                                    Dim p As Point = New Point(gr.X, gr.Y)
                                    p.Offset((e.X - dragStart.X) / Me.Zoom, (e.Y - dragStart.Y) / Me.Zoom)
                                    gr.SetPosition(p)
                                Next

                                dragStart = New Point(e.X, e.Y)

                                RaiseEvent StatusUpdate(Me, _
                                    New StatusUpdateEventArgs(StatusUpdateType.ObjectMoved, _
                                        Me.SelectedObject, _
                                        String.Format("Object Moved to {0}, {1}", dragPoint.X, dragPoint.Y), _
                                        dragPoint, 0))

                            ElseIf rotating Then

                                Cursor.Current = Cursors.SizeAll

                                Dim currentRotation As Single

                                currentRotation = _
                                    AngleToPoint(m_SelectedObject.GetPosition, dragPoint)
                                currentRotation = _
                                    Convert.ToInt32((currentRotation - startingRotation + originalRotation) Mod 360)

                                m_SelectedObject.Rotation = currentRotation

                                RaiseEvent StatusUpdate(Me, _
                                    New StatusUpdateEventArgs(StatusUpdateType.ObjectRotated, _
                                            Me.SelectedObject, _
                                            String.Format("Object Rotated to {0} degrees", currentRotation), _
                                            Nothing, currentRotation))


                            Else

                                Cursor.Current = Cursors.Default

                            End If

                        Else

                            Cursor.Current = Cursors.Default

                        End If
                    Else

                        If selectionDragging And SelectRectangle Then

                            Dim x0, y0, x1, y1 As Integer

                            x0 = rectp0.X
                            y0 = rectp0.Y
                            x1 = dragPoint.X * Me.Zoom
                            y1 = dragPoint.Y * Me.Zoom

                            If x1 > x0 Then
                                selectionRect.X = x0
                            Else
                                selectionRect.X = x1
                            End If

                            If y1 > y0 Then
                                selectionRect.Y = y0
                            Else
                                selectionRect.Y = y1
                            End If

                            selectionRect.Width = Math.Abs(x1 - x0)
                            selectionRect.Height = Math.Abs(y1 - y0)

                            Cursor.Current = Cursors.Default

                        Else

                            Cursor.Current = Cursors.Default

                        End If
                    End If

                Else

                    Cursor.Current = Cursors.Default

                End If

            End If

        Else

            If Not Me.SelectedObject Is Nothing And Cursor = Cursors.SizeNWSE Then

                Dim neww, newh As Integer

                If ResizingMode_KeepAR Then
                    neww = Size0.Width - Convert.ToDouble(Size0.Width / Size0.Height) * Math.Min(dx, dy)
                    newh = Size0.Height - Math.Min(dx, dy)
                Else
                    neww = Size0.Width - dx
                    newh = Size0.Height - dy
                End If

                If neww > 10 And newh > 10 Then
                    Me.SelectedObject.Width = neww
                    Me.SelectedObject.Height = newh
                Else
                    Me.SelectedObject.Width = 10
                    Me.SelectedObject.Height = 10
                End If

            End If

            Me.Invalidate()

        End If

    End Sub

    Private Sub GraphicsSurface_MouseUp(ByVal sender As Object, _
            ByVal e As MouseEventArgs) Handles MyBase.MouseUp

        If Not ResizingMode Then

            draggingfs = False

            If dragging And SnapToGrid Then
                Dim horizGridSize As Integer = ConvertToHPixels(GridSize / 100) '* Me.Zoom
                Dim vertGridSize As Integer = ConvertToVPixels(GridSize / 100) '* Me.Zoom
                Dim bounds As Rectangle = ConvertToPixels(SurfaceBounds)
                bounds = ZoomRectangle(bounds)
                Dim oc As Point
                Dim nlh, nlv, snapx, snapy As Integer
                nlh = bounds.Width / horizGridSize
                nlv = bounds.Height / vertGridSize
                For Each go As GraphicObject In Me.SelectedObjects.Values
                    oc = New Point(go.X + go.Width / 2, go.Y + go.Height / 2)
                    snapx = Math.Round(oc.X / horizGridSize) * horizGridSize - go.Width / 2
                    snapy = Math.Round(oc.Y / vertGridSize) * vertGridSize - go.Height / 2
                    go.SetPosition(New Point(snapx, snapy))
                Next
            End If
            dragging = False
            rotating = False
            If selectionDragging Then
                Dim zoomedSelection As Rectangle = DeZoomRectangle(selectionRect)
                Dim graphicObj As GraphicObject
                For Each graphicObj In Me.DrawingObjects
                    If graphicObj.HitTest(zoomedSelection) Then
                        Me.SelectedObject = graphicObj
                        Exit For
                    End If
                Next
                For Each graphicObj In Me.DrawingObjects
                    If graphicObj.HitTest(zoomedSelection) Then
                        If Not Me.SelectedObjects.ContainsKey(graphicObj.Name) Then Me.SelectedObjects.Add(graphicObj.Name, graphicObj)
                    End If
                Next
                selectionDragging = False
                justselected = True
            End If

        Else

            Cursor = Cursors.Default
            Size0 = Nothing

        End If

        Me.Invalidate()

    End Sub

    Protected Overrides Sub OnMouseWheel(ByVal e As System.Windows.Forms.MouseEventArgs)

        If e.Delta <> 0 Then 'has wheel been moved?

            'The .NET docs suggest that e.Delta returns the actual number of notches
            'the mouse wheel has been rotated, but in actuality each roll of the mouse wheel
            'returns a value of +/- 120 (depending on the direction of rotation).
            '120 is actually a system constant, and therefore there is a possibility that it could
            'change to allow for higher-resolution mouse wheels.

            'check out <http://msdn.microsoft.com/library/en-us/winui/winui/windowsuserinterface/userinput/mouseinput/mouseinputreference/mouseinputmessages/wm_mousewheel.asp>
            'for more information

            If My.Computer.Keyboard.CtrlKeyDown Then

                Dim dx, dy As Integer

                Dim Cursorpos, Pos1, Pos2 As Drawing.Point
                Cursorpos = Cursor.Position
                Pos1 = gscTogoc(Cursorpos.X, Cursorpos.Y).ToSDPoint

                'do zoom
                If e.Delta > 0 Then Me.Zoom += 0.05 Else Me.Zoom -= 0.05
                Pos2 = gscTogoc(Cursorpos.X, Cursorpos.Y).ToSDPoint

                dx = Pos1.X - Pos2.X
                dy = Pos1.Y - Pos2.Y

                Try
                    'adjust viewpoint to keep same position
                    Me.HorizontalScroll.Value += dx
                    Me.VerticalScroll.Value += dy
                Catch ex As Exception

                End Try

                RaiseEvent StatusUpdate(Me, New StatusUpdateEventArgs(StatusUpdateType.SurfaceZoomChanged,
                        Me.SelectedObject, String.Format("Zoom set to {0}", Me.Zoom * 100),
                        Nothing, Me.Zoom))

            Else

                Dim detents As Integer = e.Delta / 120

                Dim deltascroll As Integer = 3
                If My.Computer.Mouse.WheelExists Then deltascroll = My.Computer.Mouse.WheelScrollLines

                If detents > 0 Then
                    If Me.VerticalScroll.Value > 4 * deltascroll Then
                        If 4 * deltascroll > Me.VerticalScroll.SmallChange Then
                            Me.VerticalScroll.Value -= 4 * deltascroll
                        End If
                    Else
                        Me.VerticalScroll.Value = 0
                    End If
                ElseIf detents < 0 Then
                    If Me.VerticalScroll.Value > 4 * deltascroll Then
                        If 4 * deltascroll > Me.VerticalScroll.SmallChange Then
                            Me.VerticalScroll.Value += 4 * deltascroll
                        End If
                    Else
                        Me.VerticalScroll.Value = 0
                    End If
                End If

            End If

            Me.Invalidate()

        End If
    End Sub

    'TODO: Rewrite to handle multiple selected objects
    Public Property SelectedObject() As GraphicObject
        Get
            Return m_SelectedObject
        End Get
        Set(ByVal Value As GraphicObject)
            If Not Value Is m_SelectedObject Then
                If m_drawingObjects.Contains(Value) OrElse Value Is Nothing Then
                    m_SelectedObject = Value
                    RaiseEvent SelectionChanged(Me, New SelectionChangedEventArgs(Value))
                    If Value Is Nothing Then
                        RaiseEvent StatusUpdate(Me, _
                            New StatusUpdateEventArgs(StatusUpdateType.SelectionChanged, _
                                Value, "No Object Selected", _
                                Nothing, 0))
                    Else
                        RaiseEvent StatusUpdate(Me, _
                            New StatusUpdateEventArgs(StatusUpdateType.SelectionChanged, _
                                Value, "Selected Object Changed", _
                                Value.GetPosition, 0))
                    End If
                    Me.Invalidate()
                End If
            End If
        End Set
    End Property

    Public ReadOnly Property SelectedObjects() As Generic.Dictionary(Of String, GraphicObject)
        Get
            Return m_SelectedObjects
        End Get
    End Property

    Public Sub DeleteSelectedObject(gobj As GraphicObject)
        Dim objectToDelete As GraphicObject = gobj
        If Not objectToDelete Is Nothing Then
            If Me.DrawingObjects.Contains(objectToDelete) Then
                Me.DrawingObjects.Remove(objectToDelete)
                Me.SelectedObject = Nothing
                Me.Invalidate()
            End If
        End If
    End Sub

    Public Sub DeleteAllObjects()
        Me.DrawingObjects.Clear()
        Me.Invalidate()
    End Sub

    Private Function AngleToPoint(ByVal Origin As Point, _
            ByVal Target As Point) As Single
        'a cool little utility function, 
        'given two points finds the angle between them....
        'forced me to recall my highschool math, 
        'but the task is made easier by a special overload to
        'Atan that takes X,Y co-ordinates.
        Dim Angle As Single
        Target.X = Target.X - Origin.X
        Target.Y = Target.Y - Origin.Y
        Angle = Math.Atan2(Target.Y, Target.X) / (Math.PI / 180)
        Return Angle
    End Function

    Public Sub DrawRoundRect(ByVal g As Graphics, ByVal p As Pen, ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer, ByVal radius As Integer, ByVal myBrush As Brush)

        If width / 2 < radius Then
            radius = width / 2 - 2
        ElseIf height / 2 < radius Then
            radius = height / 2 - 2
        End If

        Dim gp As Drawing2D.GraphicsPath = New Drawing2D.GraphicsPath

        gp.AddLine(x + radius, y, x + width - radius, y)
        gp.AddArc(x + width - radius, y, radius, radius, 270, 90)
        gp.AddLine(x + width, y + radius, x + width, y + height - radius)
        gp.AddArc(x + width - radius, y + height - radius, radius, radius, 0, 90)
        gp.AddLine(x + width - radius, y + height, x + radius, y + height)
        gp.AddArc(x, y + height - radius, radius, radius, 90, 90)
        gp.AddLine(x, y + height - radius, x, y + radius)
        gp.AddArc(x, y, radius, radius, 180, 90)

        gp.CloseFigure()

        g.DrawPath(p, gp)
        g.FillPath(myBrush, gp)

        gp.Dispose()

    End Sub

    Private Sub DrawPropertyListBlock(canvas As Graphics, gobj As GraphicObject)

        If gobj.Owner Is Nothing Then Exit Sub

        Dim gCon As Drawing2D.GraphicsContainer
        gCon = canvas.BeginContainer()
        canvas.ScaleTransform(Zoom, Zoom)

        Dim X, Y, Padding, Height, Width As Double

        Padding = gobj.Owner.GetFlowsheet.FlowsheetOptions.DisplayCornerPropertyListPadding

        X = gobj.X + gobj.Width + 15
        Y = gobj.Y + gobj.Height + 20

        Dim tpaint As New SolidBrush(Color.DimGray)

        Dim bgpaint As New SolidBrush(Color.FromArgb(200, 255, 255, 255))

        Dim tfont As New Font(gobj.Owner.GetFlowsheet.FlowsheetOptions.DisplayCornerPropertyListFontName, gobj.Owner.GetFlowsheet.FlowsheetOptions.DisplayCornerPropertyListFontSize, GraphicsUnit.Pixel)

        If Not gobj.Owner Is Nothing Then

            If gobj.Owner.GetFlowsheet IsNot Nothing Then

                Dim count As Integer

                Dim fs = gobj.Owner.GetFlowsheet
                Dim props As New List(Of String)(fs.FlowsheetOptions.VisibleProperties(gobj.Owner.GetType.Name))
                props.AddRange(DirectCast(gobj.Owner.ExtraProperties, IDictionary(Of String, Object)).Keys.ToArray)

                If gobj.Owner.GraphicObject.ObjectType = DWSIM.Interfaces.Enums.GraphicObjects.ObjectType.CapeOpenUO Then props = gobj.Owner.GetProperties(Interfaces.Enums.PropertyType.ALL).ToList

                Dim propstoremove As New List(Of String)

                If gobj.Owner.GraphicObject.ObjectType = DWSIM.Interfaces.Enums.GraphicObjects.ObjectType.MaterialStream Then
                    For Each p In props
                        If gobj.Owner.GetPropertyValue(p).Equals(Double.MinValue) Then
                            propstoremove.Add(p)
                        End If
                    Next
                    For i As Integer = 0 To propstoremove.Count - 1
                        props.Remove(propstoremove(i))
                    Next
                End If

                count = props.Count

                Dim fsize = canvas.MeasureString("MEASURE", tfont)

                Height = (count - 1) * (fsize.Height + Padding) + Padding

                Dim propstring, propval, propunit, text As String
                Dim pval0 As Object = Nothing

                Dim texts As New List(Of String)

                Dim n As Integer = 1
                For Each prop In props
                    propstring = gobj.Owner.GetFlowsheet.GetTranslatedString(prop)
                    pval0 = gobj.Owner.GetPropertyValue(prop, gobj.Owner.GetFlowsheet.FlowsheetOptions.SelectedUnitSystem)
                    If pval0 Is Nothing Then Exit For
                    If TypeOf pval0 Is Double Then
                        propval = Convert.ToDouble(pval0).ToString(gobj.Owner.GetFlowsheet.FlowsheetOptions.NumberFormat)
                    Else
                        propval = pval0.ToString
                    End If
                    propunit = gobj.Owner.GetPropertyUnit(prop, gobj.Owner.GetFlowsheet.FlowsheetOptions.SelectedUnitSystem)
                    text = propstring + ": " + propval + " " + propunit
                    If canvas.MeasureString(text, tfont).Width > Width Then Width = canvas.MeasureString(text, tfont).Width
                    texts.Add(text)
                    n += 1
                Next

                canvas.FillRectangle(bgpaint, Convert.ToInt32(X), Convert.ToInt32(Y + Padding), Convert.ToInt32(Width), Convert.ToInt32(Height + Padding))

                n = 0
                For Each text In texts
                    canvas.DrawString(text, tfont, tpaint, X, Y + n * (fsize.Height + Padding))
                    n += 1
                Next

                props.Clear()
                props = Nothing

            End If

        End If

        canvas.EndContainer(gCon)

    End Sub


End Class