프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ f676f99a

이력 | 보기 | 이력해설 | 다운로드 (276 KB)

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Threading.Tasks;
6
using System.Data;
7
using Llama;
8
using Plaice;
9
using Ingr.RAD2D.Interop.RAD2D;
10
using Ingr.RAD2D.Internal;
11
using Ingr.RAD2D.Helper;
12
using Converter.BaseModel;
13
using Converter.SPPID.Model;
14
using Converter.SPPID.Properties;
15
using Converter.SPPID.Util;
16
using Converter.SPPID.DB;
17
using Ingr.RAD2D.MacroControls.CmdCtrl;
18
using Ingr.RAD2D;
19
using System.Windows;
20
using System.Threading;
21
using System.Drawing;
22
using Microsoft.VisualBasic;
23
using Newtonsoft.Json;
24
using DevExpress.XtraSplashScreen;
25
namespace Converter.SPPID
26
{
27
    public class AutoModeling : IDisposable
28
    {
29
        Placement _placement;
30
        LMADataSource dataSource;
31
        string drawingID;
32
        dynamic newDrawing;
33
        dynamic application;
34
        bool closeDocument;
35
        Ingr.RAD2D.Application radApp;
36
        SPPID_Document document;
37
        ETCSetting _ETCSetting;
38

    
39
        public string DocumentLabelText { get; set; }
40

    
41
        List<Line> BranchLines = new List<Line>();
42
        List<string> ZeroLengthSymbolToSymbolModelItemID = new List<string>();
43
        List<string> ZeroLengthModelItemID = new List<string>();
44
        List<string> ZeroLengthModelItemIDReverse = new List<string>();
45
        List<Symbol> prioritySymbols;
46
        List<string> FlowMarkRepIds = new List<string>();
47

    
48
        public AutoModeling(SPPID_Document document, bool closeDocument)
49
        {
50
            application = Interaction.GetObject("", "PIDAutomation.Application");
51
            WrapperApplication wApp = new WrapperApplication(application.Application);
52
            radApp = wApp.RADApplication;
53

    
54
            this.closeDocument = closeDocument;
55
            this.document = document;
56
            this._ETCSetting = ETCSetting.GetInstance();
57
        }
58

    
59
        private void SetSystemEditingCommand(bool value)
60
        {
61
            foreach (var item in radApp.Commands)
62
            {
63
                if (item.Argument == "SystemEditingCmd.SystemEditing")
64
                {
65
                    if (item.Checked != value)
66
                    {
67
                        radApp.RunMacro("systemeditingcmd.dll");
68
                        break;
69
                    }
70

    
71
                }
72
            }
73
        }
74

    
75
        /// <summary>
76
        /// 도면 단위당 실행되는 메서드
77
        /// </summary>
78
        public void Run()
79
        {
80
            string drawingNumber = document.DrawingNumber;
81
            string drawingName = document.DrawingName;
82
            try
83
            {
84
                _placement = new Placement();
85
                dataSource = _placement.PIDDataSource;
86
                
87
                if (CreateDocument(ref drawingNumber, ref drawingName) && DocumentCoordinateCorrection())
88
                {
89
                    Log.Write("Start Modeling");
90
                    SplashScreenManager.ShowForm(typeof(SPPIDSplashScreen), true, true);
91
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetParent, (IntPtr)radApp.HWnd);
92
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllStepCount, 24);
93
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetDocumentName, DocumentLabelText);
94

    
95
                    // VendorPackage Modeling
96
                    RunVendorPackageModeling();
97
                    // Equipment Modeling
98
                    RunEquipmentModeling();
99
                    // Symbol Modeling
100
                    RunSymbolModeling();
101
                    // LineRun Line Modeling
102
                    RunLineModeling();
103
                    // Vent Drain Modeling
104
                    RunVentDrainModeling();
105
                    // Clear Attribute
106
                    RunClearNominalDiameter();
107
                    // Join SameConnector
108
                    RunJoinRunForSameConnector();
109
                    // Join Run
110
                    RunJoinRun();
111
                    // EndBreak Modeling
112
                    RunEndBreakModeling();
113
                    // SpecBreak Modeling
114
                    RunSpecBreakModeling();
115
                    //Line Number Modeling
116
                    RunLineNumberModeling();
117
                    // Note Modeling
118
                    RunNoteModeling();
119
                    // Text Modeling
120
                    RunTextModeling();
121
                    // Input LineNumber Attribute
122
                    RunInputLineNumberAttribute();
123
                    // Input Symbol Attribute
124
                    RunInputSymbolAttribute();
125
                    // Input SpecBreak Attribute
126
                    RunInputSpecBreakAttribute();
127
                    // Input EndBreak Attribute
128
                    RunInputEndBreakAttribute();
129
                    // Label Symbol Modeling
130
                    RunLabelSymbolModeling();
131
                    // Correct Text
132
                    RunCorrectAssociationText();
133
                    // ETC
134
                    RunETC();
135

    
136
                    // Result Logging
137
                    document.CheckModelingResult();
138
                }
139
            }
140
            catch (Exception ex)
141
            {
142
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
143
                {
144
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
145
                    SplashScreenManager.CloseForm(false);
146
                    Log.Write("\r\n");
147
                }
148
                System.Windows.Forms.MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
149
            }
150
            finally
151
            {
152
                Project_DB.InsertDrawingInfoAndOPCInfo(document.PATH, drawingNumber, drawingName, document);
153
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
154
                {
155
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
156
                    SplashScreenManager.CloseForm(false);
157
                    Log.Write("\r\n");
158
                }
159
                Thread.Sleep(1000);
160

    
161
                Log.Write("End Modeling");
162
                radApp.ActiveWindow.Fit();
163

    
164
                ReleaseCOMObjects(application);
165
                application = null;
166
                if (radApp.ActiveDocument != null)
167
                {
168
                    if (closeDocument && newDrawing != null)
169
                    {
170
                        newDrawing.Save();
171
                        newDrawing.CloseDrawing(true);
172
                        ReleaseCOMObjects(newDrawing);
173
                        newDrawing = null;
174
                    }
175
                    else if (newDrawing == null)
176
                    {
177
                        Log.Write("error document");
178
                    }
179
                }
180

    
181
                ReleaseCOMObjects(dataSource);
182
                dataSource = null;
183
                ReleaseCOMObjects(_placement);
184
                _placement = null;
185

    
186
                Thread.Sleep(1000);
187
            }
188
        }
189

    
190
        private void RunVendorPackageModeling()
191
        {
192
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.VendorPackages.Count);
193
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "VendorPackages Modeling");
194
            foreach (VendorPackage item in document.VendorPackages)
195
            {
196
                try
197
                {
198
                    VendorPackageModeling(item);
199
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
200
                }
201
                catch (Exception ex)
202
                {
203
                    Log.Write("Error in RunVendorPackageModeling");
204
                    Log.Write("UID : " + item.UID);
205
                    Log.Write(ex.Message);
206
                    Log.Write(ex.StackTrace);
207
                }
208
            }
209
        }
210
        private void RunEquipmentModeling()
211
        {
212
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.Equipments.Count);
213
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Equipments Modeling");
214
            foreach (Equipment item in document.Equipments)
215
            {
216
                try
217
                {
218
                    EquipmentModeling(item);
219
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.Equipments.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
220
                }
221
                catch (Exception ex)
222
                {
223
                    Log.Write("Error in EquipmentModeling");
224
                    Log.Write("UID : " + item.UID);
225
                    Log.Write(ex.Message);
226
                    Log.Write(ex.StackTrace);
227
                }
228
            }
229
        }
230
        private void RunSymbolModeling()
231
        {
232
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
233
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Symbol Modeling");
234
            prioritySymbols = GetPrioritySymbol();
235
            foreach (var item in prioritySymbols)
236
            {
237
                try
238
                {
239
                    if (document.VentDrainSymbol.Contains(item))
240
                        continue;
241
                    SymbolModelingBySymbol(item);
242
                }
243
                catch (Exception ex)
244
                {
245
                    Log.Write("Error in SymbolModelingByPriority");
246
                    Log.Write("UID : " + item.UID);
247
                    Log.Write(ex.Message);
248
                    Log.Write(ex.StackTrace);
249
                }
250
            }
251
        }
252
        private void RunLineModeling()
253
        {
254
            List<Line> AllLine = document.LINES.ToList();
255
            List<Line> stepLast_Line = document.LINES.FindAll(x => x.CONNECTORS.FindAll(y => y.ConnectedObject != null && y.ConnectedObject.GetType() == typeof(Symbol)).Count == 2 &&
256
            !SPPIDUtil.IsBranchedLine(document, x));
257
            List<Line> step1_Line = AllLine.FindAll(x => !stepLast_Line.Contains(x));
258

    
259
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
260
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
261

    
262
            SetPriorityLine(step1_Line);
263
            foreach (var item in step1_Line)
264
            {
265
                try
266
                {
267
                    if (document.VentDrainLine.Contains(item))
268
                        continue;
269
                    NewLineModeling(item);
270
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
271
                }
272
                catch (Exception ex)
273
                {
274
                    Log.Write("Error in NewLineModeling");
275
                    Log.Write("UID : " + item.UID);
276
                    Log.Write(ex.Message);
277
                    Log.Write(ex.StackTrace);
278
                }
279
            }
280

    
281
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, BranchLines.Count);
282
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 2");
283
            int branchCount = BranchLines.Count;
284
            while (BranchLines.Count > 0)
285
            {
286
                try
287
                {
288
                    SortBranchLines();
289
                    Line item = BranchLines[0];
290
                    NewLineModeling(item, true);
291
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
292
                }
293
                catch (Exception ex)
294
                {
295
                    Log.Write("Error in NewLineModeling");
296
                    Log.Write("UID : " + BranchLines[0].UID);
297
                    Log.Write(ex.Message);
298
                    Log.Write(ex.StackTrace);
299
                    BranchLines.Remove(BranchLines[0]);
300
                }
301
            }
302

    
303
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, stepLast_Line.Count);
304
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 3");
305
            foreach (var item in stepLast_Line)
306
            {
307
                try
308
                {
309
                    if (document.VentDrainLine.Contains(item))
310
                        continue;
311
                    NewLineModeling(item);
312
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
313
                }
314
                catch (Exception ex)
315
                {
316
                    Log.Write("Error in NewLineModeling");
317
                    Log.Write("UID : " + item.UID);
318
                    Log.Write(ex.Message);
319
                    Log.Write(ex.StackTrace);
320
                }
321
            }
322
        }
323
        private void RunVentDrainModeling()
324
        {
325
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.VentDrainLine.Count);
326
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Vent Drain Modeling");
327
            foreach (var item in document.VentDrainLine)
328
            {
329
                try
330
                {
331
                    Connector connector = item.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
332
                    if (connector != null)
333
                    {
334
                        SetCoordinate();
335
                        Symbol connSymbol = connector.ConnectedObject as Symbol;
336
                        SymbolModeling(connSymbol, null);
337
                        NewLineModeling(item, true);
338

    
339
                        GridSetting grid = GridSetting.GetInstance();
340
                        int count = grid.DrainValveCellCount;
341
                        double length = grid.Length;
342

    
343
                        // 길이 확인
344
                        if (!string.IsNullOrEmpty(item.SPPID.ModelItemId))
345
                        {
346
                            LMConnector _LMConnector = GetLMConnectorOnlyOne(item.SPPID.ModelItemId);
347
                            if (_LMConnector != null)
348
                            {
349
                                double[] connectorRange = GetConnectorRange(_LMConnector);
350
                                double connectorLength = double.NaN;
351
                                if (item.SlopeType == SlopeType.HORIZONTAL)
352
                                    connectorLength = connectorRange[2] - connectorRange[0];
353
                                else if (item.SlopeType == SlopeType.VERTICAL)
354
                                    connectorLength = connectorRange[3] - connectorRange[1];
355

    
356
                                if (!double.IsNaN(connectorLength) && connectorLength != count * length)
357
                                {
358
                                    double move = count * length - connectorLength;
359
                                    List<Symbol> group = new List<Symbol>();
360
                                    SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
361
                                    foreach (var symbol in group)
362
                                    {
363
                                        int connSymbolIndex = item.CONNECTORS.IndexOf(item.CONNECTORS.Find(x => x.ConnectedObject == connSymbol));
364
                                        if (item.SlopeType == SlopeType.HORIZONTAL)
365
                                        {
366
                                            if (connSymbolIndex == 0)
367
                                            {
368
                                                if (item.SPPID.START_X > item.SPPID.END_X)
369
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X + move;
370
                                                else
371
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X - move;
372
                                            }
373
                                            else
374
                                            {
375
                                                if (item.SPPID.START_X < item.SPPID.END_X)
376
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X + move;
377
                                                else
378
                                                    symbol.SPPID.ORIGINAL_X = symbol.SPPID.ORIGINAL_X - move;
379
                                            }
380
                                        }
381
                                        else if (item.SlopeType == SlopeType.VERTICAL)
382
                                        {
383
                                            if (connSymbolIndex == 0)
384
                                            {
385
                                                if (item.SPPID.START_Y > item.SPPID.END_Y)
386
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y + move;
387
                                                else
388
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y - move;
389
                                            }
390
                                            else
391
                                            {
392
                                                if (item.SPPID.START_Y < item.SPPID.END_Y)
393
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y + move;
394
                                                else
395
                                                    symbol.SPPID.ORIGINAL_Y = symbol.SPPID.ORIGINAL_Y - move;
396
                                            }
397
                                        }
398
                                    }
399

    
400
                                    // 제거
401
                                    RemoveSymbol(connSymbol);
402
                                    RemoveLine(item);
403

    
404
                                    // 재생성
405
                                    SymbolModelingBySymbol(connSymbol);
406
                                    NewLineModeling(item, true);
407
                                }
408
                            }
409

    
410
                            ReleaseCOMObjects(_LMConnector);
411
                            _LMConnector = null;
412
                        }
413
                    }
414
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
415
                }
416
                catch (Exception ex)
417
                {
418
                    Log.Write("Error in NewLineModeling");
419
                    Log.Write("UID : " + item.UID);
420
                    Log.Write(ex.Message);
421
                    Log.Write(ex.StackTrace);
422
                }
423

    
424
                void SetCoordinate()
425
                {
426
                    Connector branchConnector = item.CONNECTORS.Find(loop => loop.ConnectedObject != null && loop.ConnectedObject.GetType() == typeof(Line));
427
                    if (branchConnector != null)
428
                    {
429
                        Line connLine = branchConnector.ConnectedObject as Line;
430
                        double x = 0;
431
                        double y = 0;
432
                        GetTargetLineConnectorPoint(branchConnector, item, ref x, ref y);
433
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(item, connLine, ref x, ref y);
434
                        if (targetConnector != null)
435
                        {
436
                            List<Symbol> group = new List<Symbol>();
437
                            SPPIDUtil.FindConnectedSymbolGroup(document, item.CONNECTORS.Find(loop => loop != branchConnector).ConnectedObject as Symbol, group);
438
                            if (item.SlopeType == SlopeType.HORIZONTAL)
439
                            {
440
                                item.SPPID.START_Y = y;
441
                                item.SPPID.END_Y = y;
442
                                foreach (var symbol in group)
443
                                {
444
                                    symbol.SPPID.ORIGINAL_Y = y;
445
                                    symbol.SPPID.SPPID_Y = y;
446
                                }
447
                            }
448
                            else if (item.SlopeType == SlopeType.VERTICAL)
449
                            {
450
                                item.SPPID.START_X = x;
451
                                item.SPPID.END_X = x;
452
                                foreach (var symbol in group)
453
                                {
454
                                    symbol.SPPID.ORIGINAL_X = x;
455
                                    symbol.SPPID.SPPID_X = x;
456
                                }
457
                            }
458
                        }
459
                        ReleaseCOMObjects(targetConnector);
460
                        targetConnector = null;
461
                    }
462
                }
463
            }
464
        }
465
        private void RunClearNominalDiameter()
466
        {
467
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.LINES.Count);
468
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Attribute");
469
            List<string> endClearModelItemID = new List<string>();
470
            for (int i = 0; i < document.LINES.Count; i++)
471
            {
472
                Line item = document.LINES[i];
473
                string modelItemID = item.SPPID.ModelItemId;
474
                if (!string.IsNullOrEmpty(modelItemID))
475
                {
476
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
477
                    if (modelItem != null)
478
                    {
479
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
480
                        if (attribute != null)
481
                            attribute.set_Value(DBNull.Value);
482

    
483
                        modelItem.Commit();
484
                        ReleaseCOMObjects(modelItem);
485
                        modelItem = null;
486
                    }
487
                }
488
                if (!endClearModelItemID.Contains(modelItemID))
489
                    endClearModelItemID.Add(modelItemID);
490
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
491
            }
492
            for (int i = 0; i < document.SYMBOLS.Count; i++)
493
            {
494
                Symbol item = document.SYMBOLS[i];
495
                string repID = item.SPPID.RepresentationId;
496
                string modelItemID = item.SPPID.ModelItemID;
497
                if (!string.IsNullOrEmpty(modelItemID))
498
                {
499
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
500
                    if (modelItem != null)
501
                    {
502
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
503
                        if (attribute != null)
504
                            attribute.set_Value(DBNull.Value);
505
                        int index = 1;
506
                        while (true)
507
                        {
508
                            attribute = modelItem.Attributes[string.Format("PipingPoint{0}.NominalDiameter", index)];
509
                            if (attribute != null)
510
                                attribute.set_Value(DBNull.Value);
511
                            else
512
                                break;
513
                            index++;
514
                        }
515
                        modelItem.Commit();
516
                        ReleaseCOMObjects(modelItem);
517
                        modelItem = null;
518
                    }
519
                }
520
                if (!string.IsNullOrEmpty(repID))
521
                {
522
                    LMSymbol symbol = dataSource.GetSymbol(repID);
523
                    if (symbol != null)
524
                    {
525
                        foreach (LMConnector connector in symbol.Connect1Connectors)
526
                        {
527
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
528
                            {
529
                                endClearModelItemID.Add(connector.ModelItemID);
530
                                LMModelItem modelItem = connector.ModelItemObject;
531
                                if (modelItem != null)
532
                                {
533
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
534
                                    if (attribute != null)
535
                                        attribute.set_Value(DBNull.Value);
536

    
537
                                    modelItem.Commit();
538
                                    ReleaseCOMObjects(modelItem);
539
                                    modelItem = null;
540
                                }
541
                            }
542
                        }
543
                        foreach (LMConnector connector in symbol.Connect2Connectors)
544
                        {
545
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
546
                            {
547
                                endClearModelItemID.Add(connector.ModelItemID);
548
                                LMModelItem modelItem = connector.ModelItemObject;
549
                                if (modelItem != null)
550
                                {
551
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
552
                                    if (attribute != null)
553
                                        attribute.set_Value(DBNull.Value);
554

    
555
                                    modelItem.Commit();
556
                                    ReleaseCOMObjects(modelItem);
557
                                    modelItem = null;
558
                                }
559
                            }
560
                        }
561
                    }
562
                    ReleaseCOMObjects(symbol);
563
                    symbol = null;
564
                }
565
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
566
            }
567
        }
568
        private void RunClearValueInconsistancy()
569
        {
570
            int count = 1;
571
            bool loop = true;
572
            while (loop)
573
            {
574
                loop = false;
575
                LMAFilter filter = new LMAFilter();
576
                LMACriterion criterion = new LMACriterion();
577
                filter.ItemType = "Relationship";
578
                criterion.SourceAttributeName = "SP_DRAWINGID";
579
                criterion.Operator = "=";
580
                criterion.set_ValueAttribute(drawingID);
581
                filter.get_Criteria().Add(criterion);
582

    
583
                LMRelationships relationships = new LMRelationships();
584
                relationships.Collect(dataSource, Filter: filter);
585

    
586
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, relationships.Count);
587
                if (count > 1)
588
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStepMinus, null);
589
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Inconsistent Property Value - " + count);
590
                foreach (LMRelationship relationship in relationships)
591
                {
592
                    foreach (LMInconsistency inconsistency in relationship.Inconsistencies)
593
                    {
594
                        if (inconsistency.get_InconsistencyTypeIndex() == 1)
595
                        {
596
                            LMModelItem modelItem1 = relationship.Item1RepresentationObject == null ? null : relationship.Item1RepresentationObject.ModelItemObject;
597
                            LMModelItem modelItem2 = relationship.Item2RepresentationObject == null ? null : relationship.Item2RepresentationObject.ModelItemObject;
598
                            string[] array = inconsistency.get_Name().ToString().Split(new char[] { '=' });
599
                            if (modelItem1 != null)
600
                            {
601
                                string attrName = array[0];
602
                                if (attrName.Contains("PipingPoint"))
603
                                {
604
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
605
                                    int index = Convert.ToInt32(relationship.get_Item1Location());
606
                                    LMAAttribute attribute1 = modelItem1.Attributes["PipingPoint" + index + "." + originalAttr];
607
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
608
                                    {
609
                                        loop = true;
610
                                        attribute1.set_Value(DBNull.Value);
611
                                    }
612
                                    attribute1 = null;
613
                                }
614
                                else
615
                                {
616
                                    LMAAttribute attribute1 = modelItem1.Attributes[attrName];
617
                                    if (attribute1 != null && !DBNull.Value.Equals(attribute1.get_Value()))
618
                                    {
619
                                        loop = true;
620
                                        attribute1.set_Value(DBNull.Value);
621
                                    }
622
                                    attribute1 = null;
623
                                }
624
                                modelItem1.Commit();
625
                            }
626
                            if (modelItem2 != null)
627
                            {
628
                                string attrName = array[1];
629
                                if (attrName.Contains("PipingPoint"))
630
                                {
631
                                    string originalAttr = attrName.Split(new char[] { '.' })[1];
632
                                    int index = Convert.ToInt32(relationship.get_Item2Location());
633
                                    LMAAttribute attribute2 = modelItem2.Attributes["PipingPoint" + index + "." + originalAttr];
634
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
635
                                    {
636
                                        attribute2.set_Value(DBNull.Value);
637
                                        loop = true;
638
                                    }
639
                                    attribute2 = null;
640
                                }
641
                                else
642
                                {
643
                                    LMAAttribute attribute2 = modelItem2.Attributes[attrName];
644
                                    if (attribute2 != null && !DBNull.Value.Equals(attribute2.get_Value()))
645
                                    {
646
                                        attribute2.set_Value(DBNull.Value);
647
                                        loop = true;
648
                                    }
649
                                    attribute2 = null;
650
                                }
651
                                modelItem2.Commit();
652
                            }
653
                            ReleaseCOMObjects(modelItem1);
654
                            modelItem1 = null;
655
                            ReleaseCOMObjects(modelItem2);
656
                            modelItem2 = null;
657
                            inconsistency.Commit();
658
                        }
659
                        ReleaseCOMObjects(inconsistency);
660
                    }
661
                    relationship.Commit();
662
                    ReleaseCOMObjects(relationship);
663
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
664
                }
665
                ReleaseCOMObjects(filter);
666
                filter = null;
667
                ReleaseCOMObjects(criterion);
668
                criterion = null;
669
                ReleaseCOMObjects(relationships);
670
                relationships = null;
671
                count++;
672
            }
673
        }
674
        private void RunEndBreakModeling()
675
        {
676
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
677
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "EndBreaks Modeling");
678
            foreach (var item in document.EndBreaks)
679
                try
680
                {
681
                    EndBreakModeling(item);
682
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
683
                }
684
                catch (Exception ex)
685
                {
686
                    Log.Write("Error in EndBreakModeling");
687
                    Log.Write("UID : " + item.UID);
688
                    Log.Write(ex.Message);
689
                    Log.Write(ex.StackTrace);
690
                }
691
        }
692
        private void RunSpecBreakModeling()
693
        {
694
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
695
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "SpecBreaks Modeling");
696
            foreach (var item in document.SpecBreaks)
697
                try
698
                {
699
                    SpecBreakModeling(item);
700
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
701
                }
702
                catch (Exception ex)
703
                {
704
                    Log.Write("Error in SpecBreakModeling");
705
                    Log.Write("UID : " + item.UID);
706
                    Log.Write(ex.Message);
707
                    Log.Write(ex.StackTrace);
708
                }
709
        }
710
        private void RunJoinRunForSameConnector()
711
        {
712
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
713
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 1");
714
            foreach (var line in document.LINES)
715
            {
716
                Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(line.SPPID.ModelItemId, false);
717
                List<List<double[]>> result = new List<List<double[]>>();
718
                foreach (var item in vertices)
719
                {
720
                    ReleaseCOMObjects(item.Key);
721
                    result.Add(item.Value);
722
                }
723
                line.SPPID.Vertices = result;
724
                vertices = null;
725
            }
726

    
727
            foreach (var line in document.LINES)
728
            {
729
                foreach (var connector in line.CONNECTORS)
730
                {
731
                    if (connector.ConnectedObject != null &&
732
                        connector.ConnectedObject.GetType() == typeof(Line) &&
733
                        !SPPIDUtil.IsBranchLine(line, connector.ConnectedObject as Line))
734
                    {
735
                        Line connLine = connector.ConnectedObject as Line;
736
                        if (line.SPPID.ModelItemId != connLine.SPPID.ModelItemId &&
737
                            !string.IsNullOrEmpty(line.SPPID.ModelItemId) &&
738
                            !string.IsNullOrEmpty(connLine.SPPID.ModelItemId) &&
739
                            !SPPIDUtil.IsSegment(document, line, connLine))
740
                        {
741
                            string survivorId = string.Empty;
742
                            JoinRun(connLine.SPPID.ModelItemId, line.SPPID.ModelItemId, ref survivorId);
743
                        }
744

    
745
                    }
746
                }
747
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
748
            }
749

    
750
            foreach (var line in document.LINES)
751
                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
752
        }
753
        private void RunJoinRun()
754
        {
755
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINES.Count);
756
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "PipeRun Join - 2");
757
            List<string> endModelID = new List<string>();
758
            foreach (var line in document.LINES)
759
            {
760
                if (!endModelID.Contains(line.SPPID.ModelItemId))
761
                {
762
                    while (!endModelID.Contains(line.SPPID.ModelItemId))
763
                    {
764
                        string survivorId = string.Empty;
765
                        JoinRunBySameType(line.SPPID.ModelItemId, ref survivorId);
766
                        if (string.IsNullOrEmpty(survivorId))
767
                        {
768
                            endModelID.Add(line.SPPID.ModelItemId);
769
                        }
770
                    }
771
                }
772
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
773
            }
774
        }
775
        private void RunLineNumberModeling()
776
        {
777
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
778
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Number Modeling");
779
            foreach (var item in document.LINENUMBERS)
780
            {
781
                LMLabelPersist label = dataSource.GetLabelPersist(item.SPPID.RepresentationId);
782
                if (label == null || (label != null && label.get_ItemStatus() != "Active"))
783
                {
784
                    ReleaseCOMObjects(label);
785
                    item.SPPID.RepresentationId = null;
786
                    LineNumberModeling(item);
787
                }
788
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
789
            }
790
        }
791
        private void RunNoteModeling()
792
        {
793
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
794
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Notes Modeling");
795
            List<Note> correctList = new List<Note>();
796
            foreach (var item in document.NOTES)
797
                try
798
                {
799
                    NoteModeling(item, correctList);
800
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
801
                }
802
                catch (Exception ex)
803
                {
804
                    Log.Write("Error in NoteModeling");
805
                    Log.Write("UID : " + item.UID);
806
                    Log.Write(ex.Message);
807
                    Log.Write(ex.StackTrace);
808
                }
809

    
810
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
811
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
812
            SortNote(correctList);
813
            List<Note> endList = new List<Note>();
814
            if (correctList.Count > 0)
815
                endList.Add(correctList[0]);
816
            foreach (var item in correctList)
817
                try
818
                {
819
                    if (!endList.Contains(item))
820
                        NoteCorrectModeling(item, endList);
821
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
822
                }
823
                catch (Exception ex)
824
                {
825
                    Log.Write("Error in NoteModeling");
826
                    Log.Write("UID : " + item.UID);
827
                    Log.Write(ex.Message);
828
                    Log.Write(ex.StackTrace);
829
                }
830
        }
831
        private void RunTextModeling()
832
        {
833
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
834
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
835
            SortText(document.TEXTINFOS);
836
            foreach (var item in document.TEXTINFOS)
837
                try
838
                {
839
                    if (item.ASSOCIATION)
840
                        AssociationTextModeling(item);
841
                    else
842
                        NormalTextModeling(item);
843
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
844
                }
845
                catch (Exception ex)
846
                {
847
                    Log.Write("Error in TextModeling");
848
                    Log.Write("UID : " + item.UID);
849
                    Log.Write(ex.Message);
850
                    Log.Write(ex.StackTrace);
851
                }
852
        }
853
        private void RunInputLineNumberAttribute()
854
        {
855
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
856
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
857
            List<string> endLine = new List<string>();
858
            foreach (var item in document.LINENUMBERS)
859
                try
860
                {
861
                    InputLineNumberAttribute(item, endLine);
862
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
863
                }
864
                catch (Exception ex)
865
                {
866
                    Log.Write("Error in InputLineNumberAttribute");
867
                    Log.Write("UID : " + item.UID);
868
                    Log.Write(ex.Message);
869
                    Log.Write(ex.StackTrace);
870
                }
871
        }
872
        private void RunInputSymbolAttribute()
873
        {
874
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
875
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
876
            foreach (var item in document.SYMBOLS)
877
                try
878
                {
879
                    InputSymbolAttribute(item, item.ATTRIBUTES);
880
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
881
                }
882
                catch (Exception ex)
883
                {
884
                    Log.Write("Error in InputSymbolAttribute");
885
                    Log.Write("UID : " + item.UID);
886
                    Log.Write(ex.Message);
887
                    Log.Write(ex.StackTrace);
888
                }
889
        }
890
        private void RunInputSpecBreakAttribute()
891
        {
892
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
893
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set SpecBreak Attribute");
894
            foreach (var item in document.SpecBreaks)
895
                try
896
                {
897
                    InputSpecBreakAttribute(item);
898
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
899
                }
900
                catch (Exception ex)
901
                {
902
                    Log.Write("Error in InputSpecBreakAttribute");
903
                    Log.Write("UID : " + item.UID);
904
                    Log.Write(ex.Message);
905
                    Log.Write(ex.StackTrace);
906
                }
907
        }
908
        private void RunInputEndBreakAttribute()
909
        {
910
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
911
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set EndBreak Attribute");
912
            foreach (var item in document.EndBreaks)
913
                try
914
                {
915
                    InputEndBreakAttribute(item);
916
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
917
                }
918
                catch (Exception ex)
919
                {
920
                    Log.Write("Error in RunInputEndBreakAttribute");
921
                    Log.Write("UID : " + item.UID);
922
                    Log.Write(ex.Message);
923
                    Log.Write(ex.StackTrace);
924
                }
925
        }
926
        private void RunLabelSymbolModeling()
927
        {
928
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
929
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
930
            foreach (var item in document.SYMBOLS)
931
                try
932
                {
933
                    LabelSymbolModeling(item);
934
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
935
                }
936
                catch (Exception ex)
937
                {
938
                    Log.Write("Error in LabelSymbolModeling");
939
                    Log.Write("UID : " + item.UID);
940
                    Log.Write(ex.Message);
941
                    Log.Write(ex.StackTrace);
942
                }
943
        }
944
        private void RunCorrectAssociationText()
945
        {
946
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count + document.LINENUMBERS.Count);
947
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Labels");
948
            List<Text> endTexts = new List<Text>();
949
            foreach (var item in document.TEXTINFOS)
950
            {
951
                try
952
                {
953
                    if (item.ASSOCIATION && !endTexts.Contains(item))
954
                        AssociationTextCorrectModeling(item, endTexts);
955
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
956
                }
957
                catch (Exception ex)
958
                {
959
                    Log.Write("Error in RunCorrectAssociationText");
960
                    Log.Write("UID : " + item.UID);
961
                    Log.Write(ex.Message);
962
                    Log.Write(ex.StackTrace);
963
                }
964
                
965
            }
966

    
967
            foreach (var item in document.LINENUMBERS)
968
            {
969
                try
970
                {
971
                    LineNumberCorrectModeling(item);
972
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
973
                }
974
                catch (Exception ex)
975
                {
976
                    Log.Write("Error in RunCorrectAssociationText");
977
                    Log.Write("UID : " + item.UID);
978
                    Log.Write(ex.Message);
979
                    Log.Write(ex.StackTrace);
980
                }
981
            }
982
        }
983
        private void RunETC()
984
        {
985
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, FlowMarkRepIds.Count);
986
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "ETC");
987
            foreach (var item in FlowMarkRepIds)
988
            {
989
                LMLabelPersist label = dataSource.GetLabelPersist(item);
990
                if (label != null)
991
                {
992
                    label.get_GraphicOID();
993
                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[label.get_GraphicOID().ToString()] as DependencyObject;
994
                    if (dependency != null)
995
                        dependency.BringToFront();
996
                }
997
                ReleaseCOMObjects(label);
998
                label = null;
999
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1000
            }
1001
        }
1002
        /// <summary>
1003
        /// 도면 생성 메서드
1004
        /// </summary>
1005
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
1006
        {
1007
            Log.Write("------------------ Start create document ------------------");
1008
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
1009
            Log.Write("Drawing name : " + drawingName);
1010
            Log.Write("Drawing number : " + drawingNumber);
1011
            Thread.Sleep(1000);
1012
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
1013
            if (newDrawing != null)
1014
            {
1015
                document.SPPID_DrawingNumber = drawingNumber;
1016
                document.SPPID_DrawingName = drawingName;
1017
                Thread.Sleep(1000);
1018
                radApp.ActiveWindow.Fit();
1019
                Thread.Sleep(1000);
1020
                radApp.ActiveWindow.Zoom = 2000;
1021
                Thread.Sleep(2000);
1022

    
1023
                //current LMDrawing 가져오기
1024
                LMAFilter filter = new LMAFilter();
1025
                LMACriterion criterion = new LMACriterion();
1026
                filter.ItemType = "Drawing";
1027
                criterion.SourceAttributeName = "Name";
1028
                criterion.Operator = "=";
1029
                criterion.set_ValueAttribute(drawingName);
1030
                filter.get_Criteria().Add(criterion);
1031

    
1032
                LMDrawings drawings = new LMDrawings();
1033
                drawings.Collect(dataSource, Filter: filter);
1034

    
1035
                drawingID = ((dynamic)drawings).Nth(1).Id;
1036
                ReleaseCOMObjects(filter);
1037
                ReleaseCOMObjects(criterion);
1038
                ReleaseCOMObjects(drawings);
1039
                filter = null;
1040
                criterion = null;
1041
                drawings = null;
1042
            }
1043
            else
1044
                Log.Write("Fail Create Drawing");
1045

    
1046
            if (newDrawing != null)
1047
                return true;
1048
            else
1049
                return false;
1050
        }
1051

    
1052
        /// <summary>
1053
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
1054
        /// </summary>
1055
        /// <param name="drawingName"></param>
1056
        /// <param name="drawingNumber"></param>
1057
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
1058
        {
1059
            LMDrawings drawings = new LMDrawings();
1060
            drawings.Collect(dataSource);
1061

    
1062
            List<string> drawingNameList = new List<string>();
1063
            List<string> drawingNumberList = new List<string>();
1064

    
1065
            foreach (LMDrawing item in drawings)
1066
            {
1067
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
1068
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
1069
            }
1070

    
1071
            int nameLength = drawingName.Length;
1072
            while (drawingNameList.Contains(drawingName))
1073
            {
1074
                if (nameLength == drawingName.Length)
1075
                    drawingName += "-1";
1076
                else
1077
                {
1078
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1079
                    drawingName = drawingName.Substring(0, nameLength + 1);
1080
                    drawingName += ++index;
1081
                }
1082
            }
1083

    
1084
            int numberLength = drawingNumber.Length;
1085
            while (drawingNameList.Contains(drawingNumber))
1086
            {
1087
                if (numberLength == drawingNumber.Length)
1088
                    drawingNumber += "-1";
1089
                else
1090
                {
1091
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1092
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1093
                    drawingNumber += ++index;
1094
                }
1095
            }
1096
            ReleaseCOMObjects(drawings);
1097
            drawings = null;
1098
        }
1099

    
1100
        /// <summary>
1101
        /// 도면 크기 구하는 메서드
1102
        /// </summary>
1103
        /// <returns></returns>
1104
        private bool DocumentCoordinateCorrection()
1105
        {
1106
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1107
            {
1108
                Log.Write("Setting Drawing X, Drawing Y");
1109
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1110
                Log.Write("Start coordinate correction");
1111
                document.CoordinateCorrection();
1112
                return true;
1113
            }
1114
            else
1115
            {
1116
                Log.Write("Need Drawing X, Y");
1117
                return false;
1118
            }
1119
        }
1120

    
1121
        /// <summary>
1122
        /// 심볼을 실제로 Modeling 메서드
1123
        /// </summary>
1124
        /// <param name="symbol">생성할 심볼</param>
1125
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1126
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1127
        {
1128
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1129
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1130
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1131
                return;
1132
            // 이미 모델링 됐을 경우
1133
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1134
                return;
1135

    
1136
            LMSymbol _LMSymbol = null;
1137

    
1138
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1139
            double x = symbol.SPPID.ORIGINAL_X;
1140
            double y = symbol.SPPID.ORIGINAL_Y;
1141
            int mirror = 0;
1142
            double angle = symbol.ANGLE;
1143

    
1144
            // OPC 일경우 180도 일때 Mirror
1145
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1146
                mirror = 1;
1147

    
1148
            // Mirror 계산
1149
            if (symbol.FLIP == 1)
1150
            {
1151
                mirror = 1;
1152
                angle += Math.PI;
1153
            }
1154

    
1155
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1156
            {
1157
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1158
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1159
                if (connector != null)
1160
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1161

    
1162
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1163
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1164
                if (temp != null)
1165
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1166
                ReleaseCOMObjects(temp);
1167
                temp = null;
1168

    
1169
                if (_LMSymbol != null && _TargetItem != null)
1170
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1171

    
1172
                ReleaseCOMObjects(_TargetItem);
1173
            }
1174
            else
1175
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1176

    
1177
            if (_LMSymbol != null)
1178
            {
1179
                _LMSymbol.Commit();
1180

    
1181
                // ConnCheck
1182
                List<string> ids = new List<string>();
1183
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1184
                {
1185
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1186
                        ids.Add(item.Id);
1187
                    ReleaseCOMObjects(item);
1188
                }
1189
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1190
                {
1191
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1192
                        ids.Add(item.Id);
1193
                    ReleaseCOMObjects(item);
1194
                }
1195

    
1196
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1197
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1198
                {
1199
                    double currentX = _LMSymbol.get_XCoordinate();
1200
                    double currentY = _LMSymbol.get_YCoordinate();
1201

    
1202

    
1203
                }
1204

    
1205
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1206
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1207
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1208

    
1209
                foreach (var item in symbol.ChildSymbols)
1210
                    CreateChildSymbol(item, _LMSymbol, symbol);
1211

    
1212
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1213
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1214

    
1215
                double[] range = null;
1216
                GetSPPIDSymbolRange(symbol, ref range);
1217
                symbol.SPPID.SPPID_Min_X = range[0];
1218
                symbol.SPPID.SPPID_Min_Y = range[1];
1219
                symbol.SPPID.SPPID_Max_X = range[2];
1220
                symbol.SPPID.SPPID_Max_Y = range[3];
1221

    
1222
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1223
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1224
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1225
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1226

    
1227
                ReleaseCOMObjects(_LMSymbol);
1228
            }
1229
        }
1230
        /// <summary>
1231
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1232
        /// Signal Point는 고려하지 않음
1233
        /// </summary>
1234
        /// <param name="symbol"></param>
1235
        /// <param name="_TargetItem"></param>
1236
        /// <param name="targetX"></param>
1237
        /// <param name="targetY"></param>
1238
        /// <returns></returns>
1239
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1240
        {
1241
            LMConnector tempConnector = null;
1242

    
1243
            List<Symbol> group = new List<Symbol>();
1244
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1245
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1246
            {
1247
                List<Connector> connectors = new List<Connector>();
1248
                foreach (var item in group)
1249
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1250
                /// Primary or Secondary Type Line만 고려
1251
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1252
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1253
                if (_connector != null)
1254
                {
1255
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1256
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1257
                    /// PipingPoint가 2개 이상만
1258
                    if (pointInfos.Count >= 2)
1259
                    {
1260
                        double lineX = 0;
1261
                        double lineY = 0;
1262
                        double length = 0;
1263
                        foreach (var item in pointInfos)
1264
                        {
1265
                            double tempX = item[1];
1266
                            double tempY = item[2];
1267

    
1268
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1269
                            if (calcDistance > length)
1270
                            {
1271
                                lineX = tempX;
1272
                                lineY = tempY;
1273
                            }
1274
                        }
1275

    
1276
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1277
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1278
                        placeRunInputs.AddPoint(-1, -1);
1279
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1280
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1281
                        if (tempConnector != null)
1282
                            tempConnector.Commit();
1283
                        ReleaseCOMObjects(_LMAItem);
1284
                        _LMAItem = null;
1285
                        ReleaseCOMObjects(placeRunInputs);
1286
                        placeRunInputs = null;
1287
                    }
1288
                }
1289
            }
1290

    
1291
            return tempConnector;
1292
        }
1293
        /// <summary>
1294
        /// Symbol의 PipingPoints를 구함
1295
        /// SignalPoint는 고려하지 않음
1296
        /// </summary>
1297
        /// <param name="symbol"></param>
1298
        /// <returns></returns>
1299
        private List<double[]> getPipingPoints(LMSymbol symbol)
1300
        {
1301
            LMModelItem modelItem = symbol.ModelItemObject;
1302
            LMPipingPoints pipingPoints = null;
1303
            if (modelItem.get_ItemTypeName() == "PipingComp")
1304
            {
1305
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1306
                pipingPoints = pipingComp.PipingPoints;
1307
                ReleaseCOMObjects(pipingComp);
1308
                pipingComp = null;
1309
            }
1310
            else if (modelItem.get_ItemTypeName() == "Instrument")
1311
            {
1312
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1313
                pipingPoints = instrument.PipingPoints;
1314
                ReleaseCOMObjects(instrument);
1315
                instrument = null;
1316
            }
1317
            else
1318
                Log.Write("다른 Type");
1319

    
1320
            List<double[]> info = new List<double[]>();
1321
            if (pipingPoints != null)
1322
            {
1323
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1324
                {
1325
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1326
                    {
1327
                        if (attribute.Name == "PipingPointNumber")
1328
                        {
1329
                            int index = Convert.ToInt32(attribute.get_Value());
1330
                            if (info.Find(loopX => loopX[0] == index) == null)
1331
                            {
1332
                                double x = 0;
1333
                                double y = 0;
1334
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1335
                                    info.Add(new double[] { index, x, y });
1336
                            }
1337
                        }
1338
                    }
1339
                }
1340
            }
1341
            ReleaseCOMObjects(modelItem);
1342
            modelItem = null;
1343
            ReleaseCOMObjects(pipingPoints);
1344
            pipingPoints = null;
1345

    
1346
            return info;
1347
        }
1348

    
1349
        private void RemoveSymbol(Symbol symbol)
1350
        {
1351
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1352
            {
1353
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1354
                if (_LMSymbol != null)
1355
                {
1356
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1357
                    ReleaseCOMObjects(_LMSymbol);
1358
                }
1359
            }
1360

    
1361
            symbol.SPPID.RepresentationId = string.Empty;
1362
            symbol.SPPID.ModelItemID = string.Empty;
1363
            symbol.SPPID.SPPID_X = double.NaN;
1364
            symbol.SPPID.SPPID_Y = double.NaN;
1365
            symbol.SPPID.SPPID_Min_X = double.NaN;
1366
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1367
            symbol.SPPID.SPPID_Max_X = double.NaN;
1368
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1369
        }
1370

    
1371
        private void RemoveSymbol(List<Symbol> symbols)
1372
        {
1373
            foreach (var symbol in symbols)
1374
            {
1375
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1376
                {
1377
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1378
                    if (_LMSymbol != null)
1379
                    {
1380
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1381
                        ReleaseCOMObjects(_LMSymbol);
1382
                    }
1383
                }
1384

    
1385
                symbol.SPPID.RepresentationId = string.Empty;
1386
                symbol.SPPID.ModelItemID = string.Empty;
1387
                symbol.SPPID.SPPID_X = double.NaN;
1388
                symbol.SPPID.SPPID_Y = double.NaN;
1389
                symbol.SPPID.SPPID_Min_X = double.NaN;
1390
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1391
                symbol.SPPID.SPPID_Max_X = double.NaN;
1392
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1393
            }
1394
        }
1395

    
1396
        /// <summary>
1397
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1398
        /// </summary>
1399
        /// <param name="targetConnector"></param>
1400
        /// <param name="targetSymbol"></param>
1401
        /// <param name="x"></param>
1402
        /// <param name="y"></param>
1403
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1404
        {
1405
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1406

    
1407
            double[] range = null;
1408
            List<double[]> points = new List<double[]>();
1409
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1410
            double x1 = range[0];
1411
            double y1 = range[1];
1412
            double x2 = range[2];
1413
            double y2 = range[3];
1414

    
1415
            // Origin 기준 Connector의 위치차이
1416
            double sceneX = 0;
1417
            double sceneY = 0;
1418
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1419
            double originX = 0;
1420
            double originY = 0;
1421
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1422
            double gapX = originX - sceneX;
1423
            double gapY = originY - sceneY;
1424

    
1425
            // SPPID Symbol과 ID2 심볼의 크기 차이
1426
            double sizeWidth = 0;
1427
            double sizeHeight = 0;
1428
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1429
            if (sizeWidth == 0 || sizeHeight == 0)
1430
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1431

    
1432
            double percentX = (x2 - x1) / sizeWidth;
1433
            double percentY = (y2 - y1) / sizeHeight;
1434

    
1435
            double SPPIDgapX = gapX * percentX;
1436
            double SPPIDgapY = gapY * percentY;
1437

    
1438
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1439
            double distance = double.MaxValue;
1440
            double[] resultPoint;
1441
            foreach (var point in points)
1442
            {
1443
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1444
                if (distance > result)
1445
                {
1446
                    distance = result;
1447
                    resultPoint = point;
1448
                    x = point[0];
1449
                    y = point[1];
1450
                }
1451
            }
1452

    
1453
            ReleaseCOMObjects(_TargetItem);
1454
        }
1455

    
1456
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1457
        {
1458
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1459
            if (index == 0)
1460
            {
1461
                x = targetLine.SPPID.START_X;
1462
                y = targetLine.SPPID.START_Y;
1463
            }
1464
            else
1465
            {
1466
                x = targetLine.SPPID.END_X;
1467
                y = targetLine.SPPID.END_Y;
1468
            }
1469
        }
1470

    
1471
        /// <summary>
1472
        /// SPPID Symbol의 Range를 구한다.
1473
        /// </summary>
1474
        /// <param name="symbol"></param>
1475
        /// <param name="range"></param>
1476
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1477
        {
1478
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1479
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1480
            double x1 = 0;
1481
            double y1 = 0;
1482
            double x2 = 0;
1483
            double y2 = 0;
1484
            symbol2d.Range(out x1, out y1, out x2, out y2);
1485
            range = new double[] { x1, y1, x2, y2 };
1486

    
1487
            for (int i = 1; i < int.MaxValue; i++)
1488
            {
1489
                double connX = 0;
1490
                double connY = 0;
1491
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1492
                    points.Add(new double[] { connX, connY });
1493
                else
1494
                    break;
1495
            }
1496

    
1497
            foreach (var childSymbol in symbol.ChildSymbols)
1498
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1499

    
1500
            ReleaseCOMObjects(_TargetItem);
1501
        }
1502

    
1503
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1504
        {
1505
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1506
            if (_TargetItem != null)
1507
            {
1508
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1509
                double x1 = 0;
1510
                double y1 = 0;
1511
                double x2 = 0;
1512
                double y2 = 0;
1513
                if (!bForGraphic)
1514
                {
1515
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1516
                    range = new double[] { x1, y1, x2, y2 };
1517
                }
1518
                else
1519
                {
1520
                    x1 = double.MaxValue;
1521
                    y1 = double.MaxValue;
1522
                    x2 = double.MinValue;
1523
                    y2 = double.MinValue;
1524
                    range = new double[] { x1, y1, x2, y2 };
1525

    
1526
                    foreach (var item in symbol2d.DrawingObjects)
1527
                    {
1528
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1529
                        {
1530
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1531
                            if (rangeObject.Layer == "Default")
1532
                            {
1533
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1534
                                range = new double[] {
1535
                                Math.Min(x1, range[0]),
1536
                                Math.Min(y1, range[1]),
1537
                                Math.Max(x2, range[2]),
1538
                                Math.Max(y2, range[3])
1539
                            };
1540
                            }
1541
                        }
1542
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1543
                        {
1544
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1545
                            if (rangeObject.Layer == "Default")
1546
                            {
1547
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1548
                                range = new double[] {
1549
                                Math.Min(x1, range[0]),
1550
                                Math.Min(y1, range[1]),
1551
                                Math.Max(x2, range[2]),
1552
                                Math.Max(y2, range[3])
1553
                            };
1554
                            }
1555
                        }
1556
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1557
                        {
1558
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1559
                            if (rangeObject.Layer == "Default")
1560
                            {
1561
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1562
                                range = new double[] {
1563
                                Math.Min(x1, range[0]),
1564
                                Math.Min(y1, range[1]),
1565
                                Math.Max(x2, range[2]),
1566
                                Math.Max(y2, range[3])
1567
                            };
1568
                            }
1569
                        }
1570
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1571
                        {
1572
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1573
                            if (rangeObject.Layer == "Default")
1574
                            {
1575
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1576
                                range = new double[] {
1577
                                Math.Min(x1, range[0]),
1578
                                Math.Min(y1, range[1]),
1579
                                Math.Max(x2, range[2]),
1580
                                Math.Max(y2, range[3])
1581
                            };
1582
                            }
1583
                        }
1584
                    }
1585
                }
1586

    
1587
                if (!bOnlySymbol)
1588
                {
1589
                    foreach (var childSymbol in symbol.ChildSymbols)
1590
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1591
                }
1592
                ReleaseCOMObjects(_TargetItem);
1593
            }
1594
        }
1595

    
1596
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1597
        {
1598
            if (labelPersist != null)
1599
            {
1600
                double x1 = double.MaxValue;
1601
                double y1 = double.MaxValue;
1602
                double x2 = double.MinValue;
1603
                double y2 = double.MinValue;
1604
                range = new double[] { x1, y1, x2, y2 };
1605

    
1606
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1607
                foreach (var item in dependency.DrawingObjects)
1608
                {
1609
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1610
                    if (textBox != null)
1611
                    {
1612
                        if (dependency != null)
1613
                        {
1614
                            double tempX1;
1615
                            double tempY1;
1616
                            double tempX2;
1617
                            double tempY2;
1618
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1619
                            x1 = Math.Min(x1, tempX1);
1620
                            y1 = Math.Min(y1, tempY1);
1621
                            x2 = Math.Max(x2, tempX2);
1622
                            y2 = Math.Max(y2, tempY2);
1623

    
1624
                            range = new double[] { x1, y1, x2, y2 };
1625
                        }
1626
                    }
1627
                }
1628
                
1629
            }
1630
        }
1631

    
1632
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1633
        {
1634
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1635
            foreach (var symbol in symbols)
1636
            {
1637
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1638
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1639
                double x1 = 0;
1640
                double y1 = 0;
1641
                double x2 = 0;
1642
                double y2 = 0;
1643
                symbol2d.Range(out x1, out y1, out x2, out y2);
1644

    
1645
                tempRange[0] = Math.Min(tempRange[0], x1);
1646
                tempRange[1] = Math.Min(tempRange[1], y1);
1647
                tempRange[2] = Math.Max(tempRange[2], x2);
1648
                tempRange[3] = Math.Max(tempRange[3], y2);
1649

    
1650
                foreach (var childSymbol in symbol.ChildSymbols)
1651
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1652

    
1653
                ReleaseCOMObjects(_TargetItem);
1654
            }
1655

    
1656
            range = tempRange;
1657
        }
1658

    
1659
        /// <summary>
1660
        /// Child Modeling 된 Symbol의 Range를 구한다.
1661
        /// </summary>
1662
        /// <param name="childSymbol"></param>
1663
        /// <param name="range"></param>
1664
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1665
        {
1666
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1667
            if (_ChildSymbol != null)
1668
            {
1669
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1670
                double x1 = 0;
1671
                double y1 = 0;
1672
                double x2 = 0;
1673
                double y2 = 0;
1674
                symbol2d.Range(out x1, out y1, out x2, out y2);
1675
                range[0] = Math.Min(range[0], x1);
1676
                range[1] = Math.Min(range[1], y1);
1677
                range[2] = Math.Max(range[2], x2);
1678
                range[3] = Math.Max(range[3], y2);
1679

    
1680
                for (int i = 1; i < int.MaxValue; i++)
1681
                {
1682
                    double connX = 0;
1683
                    double connY = 0;
1684
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1685
                        points.Add(new double[] { connX, connY });
1686
                    else
1687
                        break;
1688
                }
1689

    
1690
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1691
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1692

    
1693
                ReleaseCOMObjects(_ChildSymbol);
1694
            }
1695
        }
1696

    
1697
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1698
        {
1699
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1700
            if (_ChildSymbol != null)
1701
            {
1702
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1703
                double x1 = 0;
1704
                double y1 = 0;
1705
                double x2 = 0;
1706
                double y2 = 0;
1707
                symbol2d.Range(out x1, out y1, out x2, out y2);
1708
                range[0] = Math.Min(range[0], x1);
1709
                range[1] = Math.Min(range[1], y1);
1710
                range[2] = Math.Max(range[2], x2);
1711
                range[3] = Math.Max(range[3], y2);
1712

    
1713
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1714
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1715
                ReleaseCOMObjects(_ChildSymbol);
1716
            }
1717
        }
1718

    
1719
        /// <summary>
1720
        /// Label Symbol Modeling
1721
        /// </summary>
1722
        /// <param name="symbol"></param>
1723
        private void LabelSymbolModeling(Symbol symbol)
1724
        {
1725
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1726
            {
1727
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1728
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1729
                    return;
1730
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1731

    
1732
                string symbolUID = itemAttribute.VALUE;
1733
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1734
                if (targetItem != null &&
1735
                    (targetItem.GetType() == typeof(Symbol) ||
1736
                    targetItem.GetType() == typeof(Equipment)))
1737
                {
1738
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1739
                    string sRep = null;
1740
                    if (targetItem.GetType() == typeof(Symbol))
1741
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1742
                    else if (targetItem.GetType() == typeof(Equipment))
1743
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1744
                    if (!string.IsNullOrEmpty(sRep))
1745
                    {
1746
                        // LEADER Line 검사
1747
                        bool leaderLine = false;
1748
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1749
                        if (symbolMapping != null)
1750
                            leaderLine = symbolMapping.LEADERLINE;
1751

    
1752
                        // Target Symbol Item 가져오고 Label Modeling
1753
                        LMSymbol _TargetItem = dataSource.GetSymbol(sRep);
1754
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: _TargetItem.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1755

    
1756
                        //Leader 선 센터로
1757
                        if (_LMLabelPresist != null)
1758
                        {
1759
                            // Target Item에 Label의 Attribute Input
1760
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1761

    
1762
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1763
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1764
                            if (dependency != null)
1765
                            {
1766
                                bool result = false;
1767
                                foreach (var attributes in dependency.AttributeSets)
1768
                                {
1769
                                    foreach (var attribute in attributes)
1770
                                    {
1771
                                        string name = attribute.Name;
1772
                                        string value = attribute.GetValue().ToString();
1773
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1774
                                        {
1775
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1776
                                            {
1777
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1778
                                                {
1779
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1780
                                                    double prevX = _TargetItem.get_XCoordinate();
1781
                                                    double prevY = _TargetItem.get_YCoordinate();
1782
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1783
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1784
                                                    result = true;
1785
                                                    break;
1786
                                                }
1787
                                            }
1788
                                        }
1789

    
1790
                                        if (result)
1791
                                            break;
1792
                                    }
1793

    
1794
                                    if (result)
1795
                                        break;
1796
                                }
1797
                            }
1798

    
1799
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1800
                            _LMLabelPresist.Commit();
1801
                            ReleaseCOMObjects(_LMLabelPresist);
1802
                        }
1803

    
1804
                        ReleaseCOMObjects(_TargetItem);
1805
                    }
1806
                }
1807
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1808
                {
1809
                    Line targetLine = targetItem as Line;
1810
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1811
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1812
                    if (connectedLMConnector != null)
1813
                    {
1814
                        // LEADER Line 검사
1815
                        bool leaderLine = false;
1816
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1817
                        if (symbolMapping != null)
1818
                            leaderLine = symbolMapping.LEADERLINE;
1819

    
1820
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1821
                        if (_LMLabelPresist != null)
1822
                        {
1823
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1824
                            _LMLabelPresist.Commit();
1825
                            ReleaseCOMObjects(_LMLabelPresist);
1826
                        }
1827
                        ReleaseCOMObjects(connectedLMConnector);
1828
                    }
1829

    
1830
                    foreach (var item in connectorVertices)
1831
                        if (item.Key != null)
1832
                            ReleaseCOMObjects(item.Key);
1833
                }
1834
            }
1835
        }
1836

    
1837
        /// <summary>
1838
        /// Equipment를 실제로 Modeling 메서드
1839
        /// </summary>
1840
        /// <param name="equipment"></param>
1841
        private void EquipmentModeling(Equipment equipment)
1842
        {
1843
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1844
                return;
1845

    
1846
            LMSymbol _LMSymbol = null;
1847
            LMSymbol targetItem = null;
1848
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1849
            double x = equipment.SPPID.ORIGINAL_X;
1850
            double y = equipment.SPPID.ORIGINAL_Y;
1851
            int mirror = 0;
1852
            double angle = equipment.ANGLE;
1853

    
1854
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1855

    
1856
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1857
            if (connector != null)
1858
            {
1859
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1860
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
1861
                if (connEquipment != null)
1862
                {
1863
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1864
                        EquipmentModeling(connEquipment);
1865

    
1866
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1867
                    {
1868
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1869
                        if (targetItem != null)
1870
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1871
                        else
1872
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1873
                    }
1874
                    else
1875
                    {
1876
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1877
                    }
1878
                }
1879
                else if (connVendorPackage != null)
1880
                {
1881
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
1882
                    {
1883
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
1884
                        if (targetItem != null)
1885
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1886
                        else
1887
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1888
                    }
1889
                }
1890
                else
1891
                {
1892
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1893
                }
1894
            }
1895
            else
1896
            {
1897
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1898
            }
1899

    
1900
            if (_LMSymbol != null)
1901
            {
1902
                _LMSymbol.Commit();
1903
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1904
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1905
                ReleaseCOMObjects(_LMSymbol);
1906
            }
1907

    
1908
            if (targetItem != null)
1909
            {
1910
                ReleaseCOMObjects(targetItem);
1911
            }
1912

    
1913
            ReleaseCOMObjects(_LMSymbol);
1914
        }
1915

    
1916
        private void VendorPackageModeling(VendorPackage vendorPackage)
1917
        {
1918
            ETCSetting setting = ETCSetting.GetInstance();
1919
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
1920
            {
1921
                string symbolPath = setting.VendorPackageSymbolPath;
1922
                double x = vendorPackage.SPPID.ORIGINAL_X;
1923
                double y = vendorPackage.SPPID.ORIGINAL_Y;
1924

    
1925
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
1926
                if (symbol != null)
1927
                {
1928
                    symbol.Commit();
1929
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
1930
                }
1931

    
1932
                ReleaseCOMObjects(symbol);
1933
                symbol = null;
1934
            }
1935
        }
1936

    
1937
        /// <summary>
1938
        /// 첫 진입점
1939
        /// </summary>
1940
        /// <param name="symbol"></param>
1941
        private void SymbolModelingBySymbol(Symbol symbol)
1942
        {
1943
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
1944
            List<object> endObjects = new List<object>();
1945
            endObjects.Add(symbol);
1946

    
1947
            /// 심볼에 연결되어 있는 항목들을 모델링한다
1948
            foreach (var connector in symbol.CONNECTORS)
1949
            {
1950
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1951
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1952
                {
1953
                    endObjects.Add(connItem);
1954
                    if (connItem.GetType() == typeof(Symbol))
1955
                    {
1956
                        Symbol connSymbol = connItem as Symbol;
1957
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1958
                        {
1959
                            SymbolModeling(connSymbol, symbol);
1960
                        }
1961
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1962
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1963
                    }
1964
                    else if (connItem.GetType() == typeof(Line))
1965
                    {
1966
                        Line connLine = connItem as Line;
1967
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1968
                    }
1969
                }
1970
            }
1971
        }
1972

    
1973
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
1974
        {
1975
            foreach (var connector in symbol.CONNECTORS)
1976
            {
1977
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
1978
                if (connItem != null && connItem.GetType() != typeof(Equipment))
1979
                {
1980
                    if (!endObjects.Contains(connItem))
1981
                    {
1982
                        endObjects.Add(connItem);
1983
                        if (connItem.GetType() == typeof(Symbol))
1984
                        {
1985
                            Symbol connSymbol = connItem as Symbol;
1986
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
1987
                            {
1988
                                SymbolModeling(connSymbol, symbol);
1989
                            }
1990
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
1991
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
1992
                        }
1993
                        else if (connItem.GetType() == typeof(Line))
1994
                        {
1995
                            Line connLine = connItem as Line;
1996
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
1997
                        }
1998
                    }
1999
                }
2000
            }
2001
        }
2002

    
2003
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
2004
        {
2005
            foreach (var connector in line.CONNECTORS)
2006
            {
2007
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2008
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2009
                {
2010
                    if (!endObjects.Contains(connItem))
2011
                    {
2012
                        endObjects.Add(connItem);
2013
                        if (connItem.GetType() == typeof(Symbol))
2014
                        {
2015
                            Symbol connSymbol = connItem as Symbol;
2016
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2017
                            {
2018
                                Line connLine = SPPIDUtil.GetConnectedLine(prevSymbol, connSymbol);
2019
                                int branchCount = 0;
2020
                                if (connLine != null)
2021
                                    branchCount = SPPIDUtil.GetBranchLineCount(document, connLine);
2022

    
2023
                                List<Symbol> group = new List<Symbol>();
2024
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2025
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2026
                                List<Symbol> endModelingGroup = new List<Symbol>();
2027
                                if (priority != null)
2028
                                {
2029
                                    SymbolGroupModeling(priority, group);
2030

    
2031
                                    // Range 겹치는지 확인해야함
2032
                                    double[] prevRange = null;
2033
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2034
                                    double[] groupRange = null;
2035
                                    GetSPPIDSymbolRange(group, ref groupRange);
2036

    
2037
                                    double distanceX = 0;
2038
                                    double distanceY = 0;
2039
                                    bool overlapX = false;
2040
                                    bool overlapY = false;
2041
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2042
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2043
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2044
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2045
                                    {
2046
                                        RemoveSymbol(group);
2047
                                        foreach (var _temp in group)
2048
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
2049

    
2050
                                        SymbolGroupModeling(priority, group);
2051
                                    }
2052
                                    else if (branchCount > 0)
2053
                                    {
2054
                                        LMConnector _connector = JustLineModeling(connLine);
2055
                                        if (_connector != null)
2056
                                        {
2057
                                            double distance = GetConnectorDistance(_connector);
2058
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2059
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2060
                                            _connector.Commit();
2061
                                            ReleaseCOMObjects(_connector);
2062
                                            _connector = null;
2063
                                            if (cellCount < branchCount + 1)
2064
                                            {
2065
                                                int moveCount = branchCount - cellCount;
2066
                                                RemoveSymbol(group);
2067
                                                foreach (var _temp in group)
2068
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2069

    
2070
                                                SymbolGroupModeling(priority, group);
2071
                                            }
2072
                                        }
2073
                                    }
2074
                                }
2075
                                else
2076
                                {
2077
                                    SymbolModeling(connSymbol, null);
2078
                                    // Range 겹치는지 확인해야함
2079
                                    double[] prevRange = null;
2080
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2081
                                    double[] connRange = null;
2082
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
2083

    
2084
                                    double distanceX = 0;
2085
                                    double distanceY = 0;
2086
                                    bool overlapX = false;
2087
                                    bool overlapY = false;
2088
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2089
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2090
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2091
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2092
                                    {
2093
                                        RemoveSymbol(connSymbol);
2094
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
2095

    
2096
                                        SymbolModeling(connSymbol, null);
2097
                                    }
2098
                                    else if (branchCount > 0)
2099
                                    {
2100
                                        LMConnector _connector = JustLineModeling(connLine);
2101
                                        if (_connector != null)
2102
                                        {
2103
                                            double distance = GetConnectorDistance(_connector);
2104
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2105
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2106
                                            _connector.Commit();
2107
                                            ReleaseCOMObjects(_connector);
2108
                                            _connector = null;
2109
                                            if (cellCount < branchCount + 1)
2110
                                            {
2111
                                                int moveCount = branchCount - cellCount;
2112
                                                RemoveSymbol(group);
2113
                                                foreach (var _temp in group)
2114
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2115

    
2116
                                                SymbolGroupModeling(priority, group);
2117
                                            }
2118
                                        }
2119
                                    }
2120
                                }
2121
                            }
2122
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2123
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2124
                        }
2125
                        else if (connItem.GetType() == typeof(Line))
2126
                        {
2127
                            Line connLine = connItem as Line;
2128
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
2129
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
2130
                        }
2131
                    }
2132
                }
2133
            }
2134
        }
2135

    
2136
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
2137
        {
2138
            List<Symbol> endModelingGroup = new List<Symbol>();
2139
            SymbolModeling(firstSymbol, null);
2140
            endModelingGroup.Add(firstSymbol);
2141
            while (endModelingGroup.Count != group.Count)
2142
            {
2143
                foreach (var _symbol in group)
2144
                {
2145
                    if (!endModelingGroup.Contains(_symbol))
2146
                    {
2147
                        foreach (var _connector in _symbol.CONNECTORS)
2148
                        {
2149
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2150
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2151
                            {
2152
                                SymbolModeling(_symbol, _connSymbol);
2153
                                endModelingGroup.Add(_symbol);
2154
                                break;
2155
                            }
2156
                        }
2157
                    }
2158
                }
2159
            }
2160
        }
2161

    
2162
        /// <summary>
2163
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2164
        /// </summary>
2165
        /// <param name="childSymbol"></param>
2166
        /// <param name="parentSymbol"></param>
2167
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2168
        {
2169
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2170
            double x1 = 0;
2171
            double x2 = 0;
2172
            double y1 = 0;
2173
            double y2 = 0;
2174
            symbol2d.Range(out x1, out y1, out x2, out y2);
2175

    
2176
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2177
            if (_LMSymbol != null)
2178
            {
2179
                _LMSymbol.Commit();
2180
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2181
                foreach (var item in childSymbol.ChildSymbols)
2182
                    CreateChildSymbol(item, _LMSymbol, parent);
2183
            }
2184

    
2185

    
2186
            ReleaseCOMObjects(_LMSymbol);
2187
        }
2188
        double index = 0;
2189
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2190
        {
2191
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2192
                return;
2193

    
2194
            List<Line> group = new List<Line>();
2195
            GetConnectedLineGroup(line, group);
2196
            LineCoordinateCorrection(group);
2197

    
2198
            foreach (var groupLine in group)
2199
            {
2200
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2201
                {
2202
                    BranchLines.Add(groupLine);
2203
                    continue;
2204
                }
2205

    
2206
                bool diagonal = false;
2207
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
2208
                    diagonal = true;
2209
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
2210
                LMSymbol _LMSymbolStart = null;
2211
                LMSymbol _LMSymbolEnd = null;
2212
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2213
                foreach (var connector in groupLine.CONNECTORS)
2214
                {
2215
                    double x = 0;
2216
                    double y = 0;
2217
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
2218
                    if (connector.ConnectedObject == null)
2219
                    {
2220
                        placeRunInputs.AddPoint(x, y);
2221
                    }
2222
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2223
                    {
2224
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2225
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
2226
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2227
                        {
2228
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
2229
                            if (_LMSymbolStart != null)
2230
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2231
                            else
2232
                                placeRunInputs.AddPoint(x, y);
2233
                        }
2234
                        else
2235
                        {
2236
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
2237
                            if (_LMSymbolEnd != null)
2238
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2239
                            else
2240
                                placeRunInputs.AddPoint(x, y);
2241
                        }
2242
                    }
2243
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2244
                    {
2245
                        Line targetLine = connector.ConnectedObject as Line;
2246
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2247
                        {
2248
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2249
                            if (targetConnector != null)
2250
                            {
2251
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2252
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2253
                            }
2254
                            else
2255
                            {
2256
                                placeRunInputs.AddPoint( x, y);
2257
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2258
                            }
2259
                        }
2260
                        else
2261
                        {
2262
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2263
                            {
2264
                                index += 0.01;
2265
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2266
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2267
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2268
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2269
                                else
2270
                                {
2271
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
2272
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2273
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2274
                                    else
2275
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2276
                                }
2277
                            }
2278

    
2279
                            placeRunInputs.AddPoint(x, y);
2280

    
2281
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2282
                            {
2283
                                index += 0.01;
2284
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2285
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2286
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2287
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2288
                                else
2289
                                {
2290
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2291
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2292
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2293
                                    else
2294
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2295
                                }
2296
                            }
2297
                        }
2298
                    }
2299
                }
2300

    
2301
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2302
                if (_lMConnector != null)
2303
                {
2304
                    _lMConnector.Commit();
2305
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2306

    
2307
                    bool bRemodelingStart = false;
2308
                    if (_LMSymbolStart != null)
2309
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2310
                    bool bRemodelingEnd = false;
2311
                    if (_LMSymbolEnd != null)
2312
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2313

    
2314
                    if (bRemodelingStart || bRemodelingEnd)
2315
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2316

    
2317
                    FlowMarkModeling(groupLine);
2318
                    LineNumberModelingOnlyOne(groupLine);
2319

    
2320
                    ReleaseCOMObjects(_lMConnector);
2321

    
2322
                    LMModelItem modelItem = dataSource.GetModelItem(groupLine.SPPID.ModelItemId);
2323
                    if (modelItem != null)
2324
                    {
2325
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2326
                        if (attribute != null)
2327
                            attribute.set_Value("End 1 is upstream (Inlet)");
2328
                        modelItem.Commit();
2329
                    }
2330
                    ReleaseCOMObjects(modelItem);
2331
                    modelItem = null;
2332
                }
2333
                else if (!isBranchModeling)
2334
                {
2335
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2336
                }
2337

    
2338
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2339
                x.ConnectedObject != null &&
2340
                x.ConnectedObject.GetType() == typeof(Line) &&
2341
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2342
                .Select(x => x.ConnectedObject)
2343
                .ToList();
2344

    
2345
                foreach (var item in removeLines)
2346
                    RemoveLineForModeling(item as Line);
2347

    
2348
                ReleaseCOMObjects(_LMAItem);
2349
                _LMAItem = null;
2350
                ReleaseCOMObjects(placeRunInputs);
2351
                placeRunInputs = null;
2352
                ReleaseCOMObjects(_LMSymbolStart);
2353
                _LMSymbolStart = null;
2354
                ReleaseCOMObjects(_LMSymbolEnd);
2355
                _LMSymbolEnd = null;
2356

    
2357
                if (isBranchModeling && BranchLines.Contains(groupLine))
2358
                    BranchLines.Remove(groupLine);
2359
            }
2360
        }
2361

    
2362
        private LMConnector JustLineModeling(Line line)
2363
        {
2364
            bool diagonal = false;
2365
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2366
                diagonal = true;
2367
            _LMAItem _LMAItem = _placement.PIDCreateItem(line.SPPID.MAPPINGNAME);
2368
            LMSymbol _LMSymbolStart = null;
2369
            LMSymbol _LMSymbolEnd = null;
2370
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2371
            foreach (var connector in line.CONNECTORS)
2372
            {
2373
                double x = 0;
2374
                double y = 0;
2375
                GetTargetLineConnectorPoint(connector, line, ref x, ref y);
2376
                if (connector.ConnectedObject == null)
2377
                {
2378
                    placeRunInputs.AddPoint(x, y);
2379
                }
2380
                else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2381
                {
2382
                    Symbol targetSymbol = connector.ConnectedObject as Symbol;
2383
                    GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line), targetSymbol, ref x, ref y);
2384
                    if (line.CONNECTORS.IndexOf(connector) == 0)
2385
                    {
2386
                        _LMSymbolStart = GetTargetSymbol(targetSymbol, line);
2387
                        if (_LMSymbolStart != null)
2388
                            placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2389
                        else
2390
                            placeRunInputs.AddPoint(x, y);
2391
                    }
2392
                    else
2393
                    {
2394
                        _LMSymbolEnd = GetTargetSymbol(targetSymbol, line);
2395
                        if (_LMSymbolEnd != null)
2396
                            placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2397
                        else
2398
                            placeRunInputs.AddPoint(x, y);
2399
                    }
2400
                }
2401
                else if (connector.ConnectedObject.GetType() == typeof(Line))
2402
                {
2403
                    Line targetLine = connector.ConnectedObject as Line;
2404
                    if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2405
                    {
2406
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2407
                        if (targetConnector != null)
2408
                        {
2409
                            placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2410
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2411
                        }
2412
                        else
2413
                        {
2414
                            placeRunInputs.AddPoint(x, y);
2415
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2416
                        }
2417
                    }
2418
                    else
2419
                        placeRunInputs.AddPoint(x, y);
2420
                }
2421
            }
2422

    
2423
            LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2424
            if (_lMConnector != null)
2425
                _lMConnector.Commit();
2426

    
2427
            ReleaseCOMObjects(_LMAItem);
2428
            _LMAItem = null;
2429
            ReleaseCOMObjects(placeRunInputs);
2430
            placeRunInputs = null;
2431
            ReleaseCOMObjects(_LMSymbolStart);
2432
            _LMSymbolStart = null;
2433
            ReleaseCOMObjects(_LMSymbolEnd);
2434
            _LMSymbolEnd = null;
2435

    
2436
            return _lMConnector;
2437
        }
2438

    
2439
        private void RemoveLineForModeling(Line line)
2440
        {
2441
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2442
            if (modelItem != null)
2443
            {
2444
                foreach (LMRepresentation rep in modelItem.Representations)
2445
                {
2446
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2447
                    {
2448
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2449
                        dynamic OID = rep.get_GraphicOID().ToString();
2450
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2451
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2452
                        int verticesCount = lineStringGeometry.VertexCount;
2453
                        double[] vertices = null;
2454
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2455
                        for (int i = 0; i < verticesCount; i++)
2456
                        {
2457
                            double x = 0;
2458
                            double y = 0;
2459
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2460
                            if (verticesCount == 2 && (x < 0 || y < 0))
2461
                                _placement.PIDRemovePlacement(rep);
2462
                        }
2463
                        ReleaseCOMObjects(_LMConnector);
2464
                    }
2465
                }
2466

    
2467
                ReleaseCOMObjects(modelItem);
2468
            }
2469
        }
2470

    
2471
        private void RemoveLine(Line line)
2472
        {
2473
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2474
            if (modelItem != null)
2475
            {
2476
                foreach (LMRepresentation rep in modelItem.Representations)
2477
                {
2478
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2479
                        _placement.PIDRemovePlacement(rep);
2480
                }
2481
                ReleaseCOMObjects(modelItem);
2482
            }
2483
            line.SPPID.ModelItemId = null;
2484
        }
2485

    
2486
        private void GetConnectedLineGroup(Line line, List<Line> group)
2487
        {
2488
            if (!group.Contains(line))
2489
                group.Add(line);
2490
            foreach (var connector in line.CONNECTORS)
2491
            {
2492
                if (connector.ConnectedObject != null &&
2493
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2494
                    !group.Contains(connector.ConnectedObject) &&
2495
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2496
                {
2497
                    Line connLine = connector.ConnectedObject as Line;
2498
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2499
                    {
2500
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2501
                            group.Insert(0, connLine);
2502
                        else
2503
                            group.Add(connLine);
2504
                        GetConnectedLineGroup(connLine, group);
2505
                    }
2506
                }
2507
            }
2508
        }
2509

    
2510
        private void LineCoordinateCorrection(List<Line> group)
2511
        {
2512
            // 순서대로 전 Item 기준 정렬
2513
            LineCoordinateCorrectionByStart(group);
2514

    
2515
            // 역으로 심볼이 있을 경우 좌표 보정
2516
            LineCoordinateCorrectionForLastLine(group);
2517
        }
2518

    
2519
        private void LineCoordinateCorrectionByStart(List<Line> group)
2520
        {
2521
            for (int i = 0; i < group.Count; i++)
2522
            {
2523
                Line line = group[i];
2524
                if (i == 0)
2525
                {
2526
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2527
                    if (symbolConnector != null)
2528
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2529
                }
2530
                else if (i != 0)
2531
                {
2532
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2533
                }
2534
            }
2535
        }
2536

    
2537
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2538
        {
2539
            Line checkLine = group[group.Count - 1];
2540
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2541
            if (lastSymbolConnector != null)
2542
            {
2543
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2544
                for (int i = group.Count - 2; i >= 0; i--)
2545
                {
2546
                    Line line = group[i + 1];
2547
                    Line prevLine = group[i];
2548

    
2549
                    // 같으면 보정
2550
                    if (line.SlopeType == prevLine.SlopeType)
2551
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2552
                    else
2553
                    {
2554
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2555
                        {
2556
                            double prevX = 0;
2557
                            double prevY = 0;
2558
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2559
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2560

    
2561
                            double x = 0;
2562
                            double y = 0;
2563
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2564
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2565
                        }
2566
                        else if (line.SlopeType == SlopeType.VERTICAL)
2567
                        {
2568
                            double prevX = 0;
2569
                            double prevY = 0;
2570
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2571
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2572

    
2573
                            double x = 0;
2574
                            double y = 0;
2575
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2576
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2577
                        }
2578
                        break;
2579
                    }
2580
                }
2581
            }
2582
        }
2583

    
2584
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2585
        {
2586
            double x = 0;
2587
            double y = 0;
2588
            if (connItem.GetType() == typeof(Symbol))
2589
            {
2590
                Symbol targetSymbol = connItem as Symbol;
2591
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2592
                if (targetConnector != null)
2593
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2594
                else
2595
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2596
            }
2597
            else if (connItem.GetType() == typeof(Line))
2598
            {
2599
                Line targetLine = connItem as Line;
2600
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2601
            }
2602

    
2603
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2604
        }
2605

    
2606
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2607
        {
2608
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2609
            int index = line.CONNECTORS.IndexOf(connector);
2610
            if (index == 0)
2611
            {
2612
                line.SPPID.START_X = x;
2613
                line.SPPID.START_Y = y;
2614
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2615
                    line.SPPID.END_Y = y;
2616
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2617
                    line.SPPID.END_X = x;
2618
            }
2619
            else
2620
            {
2621
                line.SPPID.END_X = x;
2622
                line.SPPID.END_Y = y;
2623
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2624
                    line.SPPID.START_Y = y;
2625
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2626
                    line.SPPID.START_X = x;
2627
            }
2628
        }
2629

    
2630
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2631
        {
2632
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2633
            int index = line.CONNECTORS.IndexOf(connector);
2634
            if (index == 0)
2635
            {
2636
                line.SPPID.START_X = x;
2637
                if (line.SlopeType == SlopeType.VERTICAL)
2638
                    line.SPPID.END_X = x;
2639
            }
2640
            else
2641
            {
2642
                line.SPPID.END_X = x;
2643
                if (line.SlopeType == SlopeType.VERTICAL)
2644
                    line.SPPID.START_X = x;
2645
            }
2646
        }
2647

    
2648
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2649
        {
2650
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2651
            int index = line.CONNECTORS.IndexOf(connector);
2652
            if (index == 0)
2653
            {
2654
                line.SPPID.START_Y = y;
2655
                if (line.SlopeType == SlopeType.HORIZONTAL)
2656
                    line.SPPID.END_Y = y;
2657
            }
2658
            else
2659
            {
2660
                line.SPPID.END_Y = y;
2661
                if (line.SlopeType == SlopeType.HORIZONTAL)
2662
                    line.SPPID.START_Y = y;
2663
            }
2664
        }
2665

    
2666
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2667
        {
2668
            if (symbol != null)
2669
            {
2670
                string repID = symbol.AsLMRepresentation().Id;
2671
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2672
                string lineUID = line.UID;
2673

    
2674
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2675
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2676
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2677

    
2678
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2679
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2680
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2681

    
2682
                if (startSpecBreak != null || startEndBreak != null)
2683
                    result = true;
2684
            }
2685
        }
2686

    
2687
        /// <summary>
2688
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2689
        /// </summary>
2690
        /// <param name="lines"></param>
2691
        /// <param name="prevLMConnector"></param>
2692
        /// <param name="startSymbol"></param>
2693
        /// <param name="endSymbol"></param>
2694
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2695
        {
2696
            string symbolPath = string.Empty;
2697
            #region get symbol path
2698
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2699
            symbolPath = GetSPPIDFileName(modelItem);
2700
            ReleaseCOMObjects(modelItem);
2701
            #endregion
2702
            bool diagonal = false;
2703
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2704
                diagonal = true;
2705
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2706
            LMConnector newConnector = null;
2707
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2708
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2709
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2710
            int verticesCount = lineStringGeometry.VertexCount;
2711
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2712

    
2713
            List<double[]> vertices = new List<double[]>();
2714
            for (int i = 1; i <= verticesCount; i++)
2715
            {
2716
                double x = 0;
2717
                double y = 0;
2718
                lineStringGeometry.GetVertex(i, ref x, ref y);
2719
                vertices.Add(new double[] { x, y });
2720
            }
2721

    
2722
            for (int i = 0; i < vertices.Count; i++)
2723
            {
2724
                double[] points = vertices[i];
2725
                // 시작 심볼이 있고 첫번째 좌표일 때
2726
                if (startSymbol != null && i == 0)
2727
                {
2728
                    if (bStart)
2729
                    {
2730
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2731
                        if (slopeType == SlopeType.HORIZONTAL)
2732
                            placeRunInputs.AddPoint(points[0], -0.1);
2733
                        else if (slopeType == SlopeType.VERTICAL)
2734
                            placeRunInputs.AddPoint(-0.1, points[1]);
2735
                        else
2736
                            placeRunInputs.AddPoint(points[0], -0.1);
2737

    
2738
                        placeRunInputs.AddPoint(points[0], points[1]);
2739
                    }
2740
                    else
2741
                    {
2742
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2743
                    }
2744
                }
2745
                // 마지막 심볼이 있고 마지막 좌표일 때
2746
                else if (endSymbol != null && i == vertices.Count - 1)
2747
                {
2748
                    if (bEnd)
2749
                    {
2750
                        placeRunInputs.AddPoint(points[0], points[1]);
2751

    
2752
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2753
                        if (slopeType == SlopeType.HORIZONTAL)
2754
                            placeRunInputs.AddPoint(points[0], -0.1);
2755
                        else if (slopeType == SlopeType.VERTICAL)
2756
                            placeRunInputs.AddPoint(-0.1, points[1]);
2757
                        else
2758
                            placeRunInputs.AddPoint(points[0], -0.1);
2759
                    }
2760
                    else
2761
                    {
2762
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2763
                    }
2764
                }
2765
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2766
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2767
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2768
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2769
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2770
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2771
                else
2772
                    placeRunInputs.AddPoint(points[0], points[1]);
2773
            }
2774

    
2775
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2776
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2777

    
2778
            ReleaseCOMObjects(placeRunInputs);
2779
            ReleaseCOMObjects(_LMAItem);
2780
            ReleaseCOMObjects(modelItem);
2781

    
2782
            if (newConnector != null)
2783
            {
2784
                newConnector.Commit();
2785
                if (startSymbol != null && bStart)
2786
                {
2787
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2788
                    placeRunInputs = new PlaceRunInputs();
2789
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2790
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2791
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2792
                    if (_LMConnector != null)
2793
                    {
2794
                        _LMConnector.Commit();
2795
                        RemoveConnectorForReModelingLine(newConnector);
2796
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2797
                        ReleaseCOMObjects(_LMConnector);
2798
                    }
2799
                    ReleaseCOMObjects(placeRunInputs);
2800
                    ReleaseCOMObjects(_LMAItem);
2801
                }
2802

    
2803
                if (endSymbol != null && bEnd)
2804
                {
2805
                    if (startSymbol != null)
2806
                    {
2807
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2808
                        newConnector = dicVertices.First().Key;
2809
                    }
2810

    
2811
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2812
                    placeRunInputs = new PlaceRunInputs();
2813
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2814
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2815
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2816
                    if (_LMConnector != null)
2817
                    {
2818
                        _LMConnector.Commit();
2819
                        RemoveConnectorForReModelingLine(newConnector);
2820
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2821
                        ReleaseCOMObjects(_LMConnector);
2822
                    }
2823
                    ReleaseCOMObjects(placeRunInputs);
2824
                    ReleaseCOMObjects(_LMAItem);
2825
                }
2826

    
2827
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2828
                ReleaseCOMObjects(newConnector);
2829
            }
2830

    
2831
            ReleaseCOMObjects(modelItem);
2832
        }
2833

    
2834
        /// <summary>
2835
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2836
        /// </summary>
2837
        /// <param name="connector"></param>
2838
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2839
        {
2840
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2841
            foreach (var item in dicVertices)
2842
            {
2843
                if (item.Value.Count == 2)
2844
                {
2845
                    bool result = false;
2846
                    foreach (var point in item.Value)
2847
                    {
2848
                        if (point[0] < 0 || point[1] < 0)
2849
                        {
2850
                            result = true;
2851
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2852
                            break;
2853
                        }
2854
                    }
2855

    
2856
                    if (result)
2857
                        break;
2858
                }
2859
            }
2860
            foreach (var item in dicVertices)
2861
                ReleaseCOMObjects(item.Key);
2862
        }
2863

    
2864
        /// <summary>
2865
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2866
        /// </summary>
2867
        /// <param name="symbol"></param>
2868
        /// <param name="line"></param>
2869
        /// <returns></returns>
2870
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2871
        {
2872
            LMSymbol _LMSymbol = null;
2873
            foreach (var connector in symbol.CONNECTORS)
2874
            {
2875
                if (connector.CONNECTEDITEM == line.UID)
2876
                {
2877
                    if (connector.Index == 0)
2878
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2879
                    else
2880
                    {
2881
                        ChildSymbol child = null;
2882
                        foreach (var childSymbol in symbol.ChildSymbols)
2883
                        {
2884
                            if (childSymbol.Connectors.Contains(connector))
2885
                                child = childSymbol;
2886
                            else
2887
                                child = GetChildSymbolByConnector(childSymbol, connector);
2888

    
2889
                            if (child != null)
2890
                                break;
2891
                        }
2892

    
2893
                        if (child != null)
2894
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2895
                    }
2896

    
2897
                    break;
2898
                }
2899
            }
2900

    
2901
            return _LMSymbol;
2902
        }
2903

    
2904
        /// <summary>
2905
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2906
        /// </summary>
2907
        /// <param name="item"></param>
2908
        /// <param name="connector"></param>
2909
        /// <returns></returns>
2910
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2911
        {
2912
            foreach (var childSymbol in item.ChildSymbols)
2913
            {
2914
                if (childSymbol.Connectors.Contains(connector))
2915
                    return childSymbol;
2916
                else
2917
                    return GetChildSymbolByConnector(childSymbol, connector);
2918
            }
2919

    
2920
            return null;
2921
        }
2922

    
2923
        /// <summary>
2924
        /// EndBreak 모델링 메서드
2925
        /// </summary>
2926
        /// <param name="endBreak"></param>
2927
        private void EndBreakModeling(EndBreak endBreak)
2928
        {
2929
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
2930
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
2931

    
2932
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
2933
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
2934
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
2935

    
2936
            if (targetLMConnector != null)
2937
            {
2938
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
2939
                Array array = null;
2940
                if (point != null)
2941
                    array = new double[] { 0, point[0], point[1] };
2942
                else
2943
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
2944
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: true);
2945
                if (_LmLabelPersist != null)
2946
                {
2947
                    _LmLabelPersist.Commit();
2948
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
2949
                    if (_LmLabelPersist.ModelItemObject != null)
2950
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
2951
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
2952
                    ReleaseCOMObjects(_LmLabelPersist);
2953
                }
2954
                ReleaseCOMObjects(targetLMConnector);
2955
            }
2956
            else
2957
            {
2958
                Log.Write("End Break UID : " + endBreak.UID);
2959
                Log.Write("Can't find targetLMConnector");
2960
            }
2961
        }
2962

    
2963
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
2964
        {
2965
            string symbolPath = string.Empty;
2966
            #region get symbol path
2967
            if (string.IsNullOrEmpty(changeSymbolPath))
2968
            {
2969
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
2970
                symbolPath = GetSPPIDFileName(modelItem);
2971
                ReleaseCOMObjects(modelItem);
2972
            }
2973
            else
2974
                symbolPath = changeSymbolPath;
2975
            
2976
            #endregion
2977

    
2978
            LMConnector newConnector = null;
2979
            dynamic OID = connector.get_GraphicOID().ToString();
2980
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2981
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2982
            int verticesCount = lineStringGeometry.VertexCount;
2983
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2984
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2985

    
2986
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
2987
            {
2988
                double[] vertices = null;
2989
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2990
                double x = 0;
2991
                double y = 0;
2992
                lineStringGeometry.GetVertex(1, ref x, ref y);
2993

    
2994
                string flowDirection = string.Empty;
2995
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
2996
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
2997
                    flowDirection = flowAttribute.get_Value().ToString();
2998

    
2999
                if (flowDirection == "End 1 is downstream (Outlet)")
3000
                {
3001
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3002
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3003
                    flowDirection = "End 1 is upstream (Inlet)";
3004
                }
3005
                else
3006
                {
3007
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3008
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3009
                }
3010
                string oldModelItemId = connector.ModelItemID;
3011
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3012
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3013
                newConnector.Commit();
3014
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3015
                if (!string.IsNullOrEmpty(flowDirection))
3016
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3017
                ReleaseCOMObjects(connector);
3018

    
3019
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3020
                {
3021
                    foreach (var repId in line.SPPID.Representations)
3022
                    {
3023
                        LMConnector _connector = dataSource.GetConnector(repId);
3024
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3025
                        {
3026
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3027
                            {
3028
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3029
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3030
                            }
3031
                        }
3032
                        ReleaseCOMObjects(_connector);
3033
                        _connector = null;
3034
                    }
3035
                }
3036
            }
3037

    
3038
            return newConnector;
3039
        }
3040

    
3041
        /// <summary>
3042
        /// SpecBreak Modeling 메서드
3043
        /// </summary>
3044
        /// <param name="specBreak"></param>
3045
        private void SpecBreakModeling(SpecBreak specBreak)
3046
        {
3047
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3048
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3049

    
3050
            if (upStreamObj != null &&
3051
                downStreamObj != null)
3052
            {
3053
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3054
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && targetLMConnector != null)
3055
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3056

    
3057
                if (targetLMConnector != null)
3058
                {
3059
                    foreach (var attribute in specBreak.ATTRIBUTES)
3060
                    {
3061
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3062
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3063
                        {
3064
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3065
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
3066
                            Array array = null;
3067
                            if (point != null)
3068
                                array = new double[] { 0, point[0], point[1] };
3069
                            else
3070
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3071
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3072

    
3073
                            if (_LmLabelPersist != null)
3074
                            {
3075
                                _LmLabelPersist.Commit();
3076
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3077
                                if (_LmLabelPersist.ModelItemObject != null)
3078
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3079
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3080
                                ReleaseCOMObjects(_LmLabelPersist);
3081
                            }
3082

    
3083
                            // temp
3084
                            ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3085
                        }
3086
                    }
3087
                    ReleaseCOMObjects(targetLMConnector);
3088
                }
3089
                else
3090
                {
3091
                    Log.Write("Spec Break UID : " + specBreak.UID);
3092
                    Log.Write("Can't find targetLMConnector");
3093
                }
3094
            }
3095
        }
3096

    
3097
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3098
        {
3099
            LMConnector targetConnector = null;
3100
            Symbol targetSymbol = targetObj as Symbol;
3101
            Symbol connectedSymbol = connectedObj as Symbol;
3102
            Line targetLine = targetObj as Line;
3103
            Line connectedLine = connectedObj as Line;
3104
            if (targetSymbol != null && connectedSymbol != null)
3105
            {
3106
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3107
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3108

    
3109
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3110
                {
3111
                    if (connector.get_ItemStatus() != "Active")
3112
                        continue;
3113

    
3114
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3115
                    {
3116
                        targetConnector = connector;
3117
                        break;
3118
                    }
3119
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3120
                    {
3121
                        targetConnector = connector;
3122
                        break;
3123
                    }
3124
                }
3125

    
3126
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3127
                {
3128
                    if (connector.get_ItemStatus() != "Active")
3129
                        continue;
3130

    
3131
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3132
                    {
3133
                        targetConnector = connector;
3134
                        break;
3135
                    }
3136
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3137
                    {
3138
                        targetConnector = connector;
3139
                        break;
3140
                    }
3141
                }
3142

    
3143
                ReleaseCOMObjects(targetLMSymbol);
3144
                ReleaseCOMObjects(connectedLMSymbol);
3145
            }
3146
            else if (targetLine != null && connectedLine != null)
3147
            {
3148
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3149
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3150

    
3151
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
3152
                {
3153
                    foreach (LMRepresentation rep in targetModelItem.Representations)
3154
                    {
3155
                        if (targetConnector != null)
3156
                            break;
3157

    
3158
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3159
                        {
3160
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3161

    
3162
                            if (IsConnected(_LMConnector, connectedModelItem))
3163
                                targetConnector = _LMConnector;
3164
                            else
3165
                                ReleaseCOMObjects(_LMConnector);
3166
                        }
3167
                    }
3168

    
3169
                    ReleaseCOMObjects(targetModelItem);
3170
                }
3171
            }
3172
            else
3173
            {
3174
                LMSymbol connectedLMSymbol = null;
3175
                if (connectedSymbol != null)
3176
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3177
                else if (targetSymbol != null)
3178
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3179
                else
3180
                {
3181

    
3182
                }
3183
                LMModelItem targetModelItem = null;
3184
                if (targetLine != null)
3185
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3186
                else if (connectedLine != null)
3187
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3188
                else
3189
                {
3190

    
3191
                }
3192
                if (connectedLMSymbol != null && targetModelItem != null)
3193
                {
3194
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
3195
                    {
3196
                        if (connector.get_ItemStatus() != "Active")
3197
                            continue;
3198

    
3199
                        if (IsConnected(connector, targetModelItem))
3200
                        {
3201
                            targetConnector = connector;
3202
                            break;
3203
                        }
3204
                    }
3205

    
3206
                    if (targetConnector == null)
3207
                    {
3208
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
3209
                        {
3210
                            if (connector.get_ItemStatus() != "Active")
3211
                                continue;
3212

    
3213
                            if (IsConnected(connector, targetModelItem))
3214
                            {
3215
                                targetConnector = connector;
3216
                                break;
3217
                            }
3218
                        }
3219
                    }
3220
                }
3221

    
3222
            }
3223

    
3224
            return targetConnector;
3225
        }
3226

    
3227
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
3228
        {
3229
            double[] result = null;
3230
            Line targetLine = targetObj as Line;
3231
            Symbol targetSymbol = targetObj as Symbol;
3232
            Line connLine = connObj as Line;
3233
            Symbol connSymbol = connObj as Symbol;
3234

    
3235
            double zeroLengthMove = GridSetting.GetInstance().Length * 3;
3236
            double lineMove = GridSetting.GetInstance().Length * 3;
3237
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
3238
            {
3239
                result = GetConnectorVertices(targetConnector)[0];
3240
                if (targetSymbol != null && connSymbol != null)
3241
                {
3242
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
3243
                    if (slopeType == SlopeType.HORIZONTAL)
3244
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3245
                    else if (slopeType == SlopeType.VERTICAL)
3246
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3247
                }
3248
                else if (targetLine != null)
3249
                {
3250
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3251
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3252
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
3253
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3254
                }
3255
                else if (connLine != null)
3256
                {
3257
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
3258
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3259
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3260
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3261
                }
3262
            }
3263
            else
3264
            {
3265
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3266
                {
3267
                    Line line = connObj as Line;
3268
                    LMConnector connectedConnector = null;
3269
                    int connIndex = 0;
3270
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3271
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3272

    
3273
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3274

    
3275
                    ReleaseCOMObjects(modelItem);
3276
                    ReleaseCOMObjects(connectedConnector);
3277

    
3278
                    if (vertices.Count > 0)
3279
                    {
3280
                        if (connIndex == 1)
3281
                            result = vertices[0];
3282
                        else if (connIndex == 2)
3283
                            result = vertices[vertices.Count - 1];
3284

    
3285
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3286
                        {
3287
                            result = new double[] { result[0], result[1] - lineMove };
3288
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3289
                            {
3290
                                result = new double[] { result[0] - lineMove, result[1] };
3291
                            }
3292
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3293
                            {
3294
                                result = new double[] { result[0] + lineMove, result[1] };
3295
                            }
3296
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3297
                            {
3298
                                result = new double[] { result[0] + lineMove, result[1] };
3299
                            }
3300
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3301
                            {
3302
                                result = new double[] { result[0] - lineMove, result[1] };
3303
                            }
3304
                        }
3305
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3306
                        {
3307
                            result = new double[] { result[0] - lineMove, result[1] };
3308
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3309
                            {
3310
                                result = new double[] { result[0], result[1] - lineMove };
3311
                            }
3312
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3313
                            {
3314
                                result = new double[] { result[0], result[1] + lineMove };
3315
                            }
3316
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3317
                            {
3318
                                result = new double[] { result[0], result[1] + lineMove };
3319
                            }
3320
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3321
                            {
3322
                                result = new double[] { result[0], result[1] - lineMove };
3323
                            }
3324
                        }
3325
                            
3326
                    }
3327
                }
3328
                else
3329
                {
3330
                    Log.Write("error in GetSegemtPoint");
3331
                }
3332
            }
3333

    
3334
            return result;
3335
        }
3336

    
3337
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3338
        {
3339
            bool result = false;
3340

    
3341
            foreach (LMRepresentation rep in modelItem.Representations)
3342
            {
3343
                if (result)
3344
                    break;
3345

    
3346
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3347
                {
3348
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3349

    
3350
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3351
                        connector.ConnectItem1SymbolObject != null &&
3352
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3353
                    {
3354
                        result = true;
3355
                        ReleaseCOMObjects(_LMConnector);
3356
                        break;
3357
                    }
3358
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3359
                        connector.ConnectItem2SymbolObject != null &&
3360
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3361
                    {
3362
                        result = true;
3363
                        ReleaseCOMObjects(_LMConnector);
3364
                        break;
3365
                    }
3366
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3367
                        connector.ConnectItem1SymbolObject != null &&
3368
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3369
                    {
3370
                        result = true;
3371
                        ReleaseCOMObjects(_LMConnector);
3372
                        break;
3373
                    }
3374
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3375
                        connector.ConnectItem2SymbolObject != null &&
3376
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3377
                    {
3378
                        result = true;
3379
                        ReleaseCOMObjects(_LMConnector);
3380
                        break;
3381
                    }
3382

    
3383
                    ReleaseCOMObjects(_LMConnector);
3384
                }
3385
            }
3386

    
3387

    
3388
            return result;
3389
        }
3390

    
3391
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3392
        {
3393
            foreach (LMRepresentation rep in modelItem.Representations)
3394
            {
3395
                if (connectedConnector != null)
3396
                    break;
3397

    
3398
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3399
                {
3400
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3401

    
3402
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3403
                        connector.ConnectItem1SymbolObject != null &&
3404
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3405
                    {
3406
                        connectedConnector = _LMConnector;
3407
                        connectorIndex = 1;
3408
                        break;
3409
                    }
3410
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3411
                        connector.ConnectItem2SymbolObject != null &&
3412
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3413
                    {
3414
                        connectedConnector = _LMConnector;
3415
                        connectorIndex = 2;
3416
                        break;
3417
                    }
3418
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3419
                        connector.ConnectItem1SymbolObject != null &&
3420
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3421
                    {
3422
                        connectedConnector = _LMConnector;
3423
                        connectorIndex = 1;
3424
                        break;
3425
                    }
3426
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3427
                        connector.ConnectItem2SymbolObject != null &&
3428
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3429
                    {
3430
                        connectedConnector = _LMConnector;
3431
                        connectorIndex = 2;
3432
                        break;
3433
                    }
3434

    
3435
                    if (connectedConnector == null)
3436
                        ReleaseCOMObjects(_LMConnector);
3437
                }
3438
            }
3439
        }
3440

    
3441
        /// <summary>
3442
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
3443
        /// </summary>
3444
        /// <param name="modelItemID1"></param>
3445
        /// <param name="modelItemID2"></param>
3446
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
3447
        {
3448
            try
3449
            {
3450
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
3451
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
3452
                List<double[]> vertices1 = null;
3453
                string graphicOID1 = string.Empty;
3454
                if (connector1 != null)
3455
                {
3456
                    vertices1 = GetConnectorVertices(connector1);
3457
                    graphicOID1 = connector1.get_GraphicOID();
3458
                }
3459
                _LMAItem item1 = modelItem1.AsLMAItem();
3460
                ReleaseCOMObjects(connector1);
3461
                connector1 = null;
3462

    
3463
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3464
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
3465
                List<double[]> vertices2 = null;
3466
                string graphicOID2 = string.Empty;
3467
                if (connector2 != null)
3468
                {
3469
                    vertices2 = GetConnectorVertices(connector2);
3470
                    graphicOID2 = connector2.get_GraphicOID();
3471
                }
3472
                _LMAItem item2 = modelItem2.AsLMAItem();
3473
                ReleaseCOMObjects(connector2);
3474
                connector2 = null;
3475

    
3476
                // item2가 item1으로 조인
3477
                _placement.PIDJoinRuns(ref item1, ref item2);
3478
                item1.Commit();
3479
                item2.Commit();
3480

    
3481
                string beforeID = string.Empty;
3482
                string afterID = string.Empty;
3483

    
3484
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3485
                {
3486
                    beforeID = modelItem2.Id;
3487
                    afterID = modelItem1.Id;
3488
                    survivorId = afterID;
3489
                }
3490
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3491
                {
3492
                    beforeID = modelItem1.Id;
3493
                    afterID = modelItem2.Id;
3494
                    survivorId = afterID;
3495
                }
3496
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3497
                {
3498
                    int model1Cnt = GetConnectorCount(modelId1);
3499
                    int model2Cnt = GetConnectorCount(modelId2);
3500
                    if (model1Cnt == 0)
3501
                    {
3502
                        beforeID = modelItem1.Id;
3503
                        afterID = modelItem2.Id;
3504
                        survivorId = afterID;
3505
                    }
3506
                    else if (model2Cnt == 0)
3507
                    {
3508
                        beforeID = modelItem2.Id;
3509
                        afterID = modelItem1.Id;
3510
                        survivorId = afterID;
3511
                    }
3512
                    else
3513
                        survivorId = null;
3514
                }
3515
                else
3516
                {
3517
                    Log.Write("잘못된 경우");
3518
                    survivorId = null;
3519
                }
3520

    
3521
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3522
                {
3523
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3524
                    foreach (var line in lines)
3525
                        line.SPPID.ModelItemId = afterID;
3526
                }
3527

    
3528
                ReleaseCOMObjects(modelItem1);
3529
                ReleaseCOMObjects(item1);
3530
                ReleaseCOMObjects(modelItem2);
3531
                ReleaseCOMObjects(item2);
3532
            }
3533
            catch (Exception ex)
3534
            {
3535
                Log.Write("Join Error");
3536
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3537
            }
3538
        }
3539

    
3540
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3541
        {
3542
            List<string> temp = new List<string>();
3543
            List<LMConnector> connectors = new List<LMConnector>();
3544
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3545
            {
3546
                if (connector.get_ItemStatus() != "Active")
3547
                    continue;
3548

    
3549
                LMModelItem modelItem = connector.ModelItemObject;
3550
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3551
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3552
                    temp.Add(modelItem.Id);
3553

    
3554
                if (temp.Contains(modelItem.Id) &&
3555
                    connOtherSymbol != null &&
3556
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3557
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3558
                    temp.Remove(modelItem.Id);
3559

    
3560

    
3561
                if (temp.Contains(modelItem.Id))
3562
                    connectors.Add(connector);
3563
                ReleaseCOMObjects(connOtherSymbol);
3564
                connOtherSymbol = null;
3565
                ReleaseCOMObjects(modelItem);
3566
                modelItem = null;
3567
            }
3568

    
3569
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3570
            {
3571
                if (connector.get_ItemStatus() != "Active")
3572
                    continue;
3573

    
3574
                LMModelItem modelItem = connector.ModelItemObject;
3575
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3576
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3577
                    temp.Add(modelItem.Id);
3578

    
3579
                if (temp.Contains(modelItem.Id) &&
3580
                    connOtherSymbol != null &&
3581
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3582
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3583
                    temp.Remove(modelItem.Id);
3584

    
3585
                if (temp.Contains(modelItem.Id))
3586
                    connectors.Add(connector);
3587
                ReleaseCOMObjects(connOtherSymbol);
3588
                connOtherSymbol = null;
3589
                ReleaseCOMObjects(modelItem);
3590
                modelItem = null;
3591
            }
3592

    
3593

    
3594
            List<string> result = new List<string>();
3595
            string originalName = GetSPPIDFileName(modelId);
3596
            foreach (var connector in connectors)
3597
            {
3598
                string fileName = GetSPPIDFileName(connector.ModelItemID);
3599
                if (originalName == fileName)
3600
                    result.Add(connector.ModelItemID);
3601
                else
3602
                {
3603
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
3604
                        result.Add(connector.ModelItemID);
3605
                    else
3606
                    {
3607
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
3608
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
3609
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
3610
                            result.Add(connector.ModelItemID);
3611
                    }
3612
                }
3613
            }
3614

    
3615
            foreach (var connector in connectors)
3616
                ReleaseCOMObjects(connector);
3617
            
3618
            return result;
3619

    
3620

    
3621
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3622
            {
3623
                LMSymbol findResult = null;
3624
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3625
                    findResult = connector.ConnectItem1SymbolObject;
3626
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3627
                    findResult = connector.ConnectItem2SymbolObject;
3628

    
3629
                return findResult;
3630
            }
3631
        }
3632

    
3633
        /// <summary>
3634
        /// PipeRun의 좌표를 가져오는 메서드
3635
        /// </summary>
3636
        /// <param name="modelId"></param>
3637
        /// <returns></returns>
3638
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
3639
        {
3640
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
3641
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
3642

    
3643
            if (modelItem != null)
3644
            {
3645
                foreach (LMRepresentation rep in modelItem.Representations)
3646
                {
3647
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3648
                    {
3649
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3650
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
3651
                        {
3652
                            ReleaseCOMObjects(_LMConnector);
3653
                            _LMConnector = null;
3654
                            continue;
3655
                        }
3656
                        connectorVertices.Add(_LMConnector, new List<double[]>());
3657
                        dynamic OID = rep.get_GraphicOID().ToString();
3658
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3659
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3660
                        int verticesCount = lineStringGeometry.VertexCount;
3661
                        double[] vertices = null;
3662
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3663
                        for (int i = 0; i < verticesCount; i++)
3664
                        {
3665
                            double x = 0;
3666
                            double y = 0;
3667
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3668
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
3669
                        }
3670
                    }
3671
                }
3672

    
3673
                ReleaseCOMObjects(modelItem);
3674
            }
3675

    
3676
            return connectorVertices;
3677
        }
3678

    
3679
        private List<double[]> GetConnectorVertices(LMConnector connector)
3680
        {
3681
            List<double[]> vertices = new List<double[]>();
3682
            if (connector != null)
3683
            {
3684
                dynamic OID = connector.get_GraphicOID().ToString();
3685
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3686
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3687
                int verticesCount = lineStringGeometry.VertexCount;
3688
                double[] value = null;
3689
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3690
                for (int i = 0; i < verticesCount; i++)
3691
                {
3692
                    double x = 0;
3693
                    double y = 0;
3694
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3695
                    vertices.Add(new double[] { x, y });
3696
                }
3697
            }
3698
            return vertices;
3699
        }
3700

    
3701
        private double GetConnectorDistance(LMConnector connector)
3702
        {
3703
            double result = 0;
3704
            List<double[]> vertices = new List<double[]>();
3705
            if (connector != null)
3706
            {
3707
                dynamic OID = connector.get_GraphicOID().ToString();
3708
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3709
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3710
                int verticesCount = lineStringGeometry.VertexCount;
3711
                double[] value = null;
3712
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3713
                for (int i = 0; i < verticesCount; i++)
3714
                {
3715
                    double x = 0;
3716
                    double y = 0;
3717
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3718
                    vertices.Add(new double[] { x, y });
3719
                    if (vertices.Count > 1)
3720
                    {
3721
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
3722
                    }
3723
                }
3724
            }
3725
            return result;
3726
        }
3727
        private double[] GetConnectorRange(LMConnector connector)
3728
        {
3729
            double[] result = null;
3730
            List<double[]> vertices = new List<double[]>();
3731
            if (connector != null)
3732
            {
3733
                dynamic OID = connector.get_GraphicOID().ToString();
3734
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3735
                double minX = 0;
3736
                double minY = 0;
3737
                double maxX = 0;
3738
                double maxY = 0;
3739

    
3740
                drawingObject.Range(out minX, out minY, out maxX, out maxY);
3741
                result = new double[] { minX, minY, maxX, maxY };
3742
            }
3743
            return result;
3744
        }
3745
        private List<double[]> GetConnectorVertices(dynamic graphicOID)
3746
        {
3747
            List<double[]> vertices = null;
3748
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID];
3749
            if (drawingObject != null)
3750
            {
3751
                vertices = new List<double[]>();
3752
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3753
                int verticesCount = lineStringGeometry.VertexCount;
3754
                double[] value = null;
3755
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3756
                for (int i = 0; i < verticesCount; i++)
3757
                {
3758
                    double x = 0;
3759
                    double y = 0;
3760
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3761
                    vertices.Add(new double[] { x, y });
3762
                }
3763
            }
3764
            return vertices;
3765
        }
3766
        /// <summary>
3767
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
3768
        /// </summary>
3769
        /// <param name="connectorVertices"></param>
3770
        /// <param name="connX"></param>
3771
        /// <param name="connY"></param>
3772
        /// <returns></returns>
3773
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
3774
        {
3775
            double length = double.MaxValue;
3776
            LMConnector targetConnector = null;
3777
            foreach (var item in connectorVertices)
3778
            {
3779
                List<double[]> points = item.Value;
3780
                for (int i = 0; i < points.Count - 1; i++)
3781
                {
3782
                    double[] point1 = points[i];
3783
                    double[] point2 = points[i + 1];
3784
                    double x1 = Math.Min(point1[0], point2[0]);
3785
                    double y1 = Math.Min(point1[1], point2[1]);
3786
                    double x2 = Math.Max(point1[0], point2[0]);
3787
                    double y2 = Math.Max(point1[1], point2[1]);
3788

    
3789
                    if ((x1 <= connX && x2 >= connX) ||
3790
                        (y1 <= connY && y2 >= connY))
3791
                    {
3792
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3793
                        if (length >= distance)
3794
                        {
3795
                            targetConnector = item.Key;
3796
                            length = distance;
3797
                        }
3798

    
3799
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3800
                        if (length >= distance)
3801
                        {
3802
                            targetConnector = item.Key;
3803
                            length = distance;
3804
                        }
3805
                    }
3806
                }
3807
            }
3808

    
3809
            // 못찾았을때.
3810
            length = double.MaxValue;
3811
            if (targetConnector == null)
3812
            {
3813
                foreach (var item in connectorVertices)
3814
                {
3815
                    List<double[]> points = item.Value;
3816

    
3817
                    foreach (double[] point in points)
3818
                    {
3819
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3820
                        if (length >= distance)
3821
                        {
3822
                            targetConnector = item.Key;
3823
                            length = distance;
3824
                        }
3825
                    }
3826
                }
3827
            }
3828

    
3829
            return targetConnector;
3830
        }
3831

    
3832
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3833
        {
3834
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3835
            if (vertices.Count == 0)
3836
                return null;
3837

    
3838
            double length = double.MaxValue;
3839
            LMConnector targetConnector = null;
3840
            double[] resultPoint = null;
3841
            List<double[]> targetVertices = null;
3842

    
3843
            // Vertices 포인트에 제일 가까운곳
3844
            foreach (var item in vertices)
3845
            {
3846
                List<double[]> points = item.Value;
3847
                for (int i = 0; i < points.Count; i++)
3848
                {
3849
                    double[] point = points[i];
3850
                    double tempX = point[0];
3851
                    double tempY = point[1];
3852

    
3853
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3854
                    if (length >= distance)
3855
                    {
3856
                        targetConnector = item.Key;
3857
                        length = distance;
3858
                        resultPoint = point;
3859
                        targetVertices = item.Value;
3860
                    }
3861
                }
3862
            }
3863

    
3864
            // Vertices Cross에 제일 가까운곳
3865
            foreach (var item in vertices)
3866
            {
3867
                List<double[]> points = item.Value;
3868
                for (int i = 0; i < points.Count - 1; i++)
3869
                {
3870
                    double[] point1 = points[i];
3871
                    double[] point2 = points[i + 1];
3872

    
3873
                    double maxLineX = Math.Max(point1[0], point2[0]);
3874
                    double minLineX = Math.Min(point1[0], point2[0]);
3875
                    double maxLineY = Math.Max(point1[1], point2[1]);
3876
                    double minLineY = Math.Min(point1[1], point2[1]);
3877

    
3878
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3879

    
3880
                    double[] crossingPoint = SPPIDUtil.CalcLineCrossingPoint(line.SPPID.START_X, line.SPPID.START_Y, line.SPPID.END_X, line.SPPID.END_Y, point1[0], point1[1], point2[0], point2[1]);
3881
                    if (crossingPoint != null)
3882
                    {
3883
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3884
                        if (length >= distance)
3885
                        {
3886
                            if (slope == SlopeType.Slope &&
3887
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3888
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3889
                            {
3890
                                targetConnector = item.Key;
3891
                                length = distance;
3892
                                resultPoint = crossingPoint;
3893
                                targetVertices = item.Value;
3894
                            }
3895
                            else if (slope == SlopeType.HORIZONTAL &&
3896
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
3897
                            {
3898
                                targetConnector = item.Key;
3899
                                length = distance;
3900
                                resultPoint = crossingPoint;
3901
                                targetVertices = item.Value;
3902
                            }
3903
                            else if (slope == SlopeType.VERTICAL &&
3904
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3905
                            {
3906
                                targetConnector = item.Key;
3907
                                length = distance;
3908
                                resultPoint = crossingPoint;
3909
                                targetVertices = item.Value;
3910
                            }
3911
                        }
3912
                    }
3913
                }
3914
            }
3915

    
3916
            foreach (var item in vertices)
3917
                if (item.Key != null && item.Key != targetConnector)
3918
                    ReleaseCOMObjects(item.Key);
3919

    
3920
            if (SPPIDUtil.IsBranchLine(line, targetLine))
3921
            {
3922
                double tempResultX = resultPoint[0];
3923
                double tempResultY = resultPoint[1];
3924
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
3925

    
3926
                GridSetting gridSetting = GridSetting.GetInstance();
3927

    
3928
                for (int i = 0; i < targetVertices.Count; i++)
3929
                {
3930
                    double[] point = targetVertices[i];
3931
                    double tempX = targetVertices[i][0];
3932
                    double tempY = targetVertices[i][1];
3933
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
3934
                    if (tempX == tempResultX && tempY == tempResultY)
3935
                    {
3936
                        if (i == 0)
3937
                        {
3938
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
3939
                            bool containZeroLength = false;
3940
                            if (connSymbol != null)
3941
                            {
3942
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
3943
                                {
3944
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3945
                                        containZeroLength = true;
3946
                                }
3947
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
3948
                                {
3949
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
3950
                                        containZeroLength = true;
3951
                                }
3952
                            }
3953

    
3954
                            if (connSymbol == null ||
3955
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
3956
                                containZeroLength)
3957
                            {
3958
                                bool bCalcX = false;
3959
                                bool bCalcY = false;
3960
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3961
                                    bCalcX = true;
3962
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
3963
                                    bCalcY = true;
3964
                                else
3965
                                {
3966
                                    bCalcX = true;
3967
                                    bCalcY = true;
3968
                                }
3969

    
3970
                                if (bCalcX)
3971
                                {
3972
                                    double nextX = targetVertices[i + 1][0];
3973
                                    double newX = 0;
3974
                                    if (nextX > tempX)
3975
                                    {
3976
                                        newX = tempX + gridSetting.Length;
3977
                                        if (newX > nextX)
3978
                                            newX = (point[0] + nextX) / 2;
3979
                                    }
3980
                                    else
3981
                                    {
3982
                                        newX = tempX - gridSetting.Length;
3983
                                        if (newX < nextX)
3984
                                            newX = (point[0] + nextX) / 2;
3985
                                    }
3986
                                    resultPoint = new double[] { newX, resultPoint[1] };
3987
                                }
3988

    
3989
                                if (bCalcY)
3990
                                {
3991
                                    double nextY = targetVertices[i + 1][1];
3992
                                    double newY = 0;
3993
                                    if (nextY > tempY)
3994
                                    {
3995
                                        newY = tempY + gridSetting.Length;
3996
                                        if (newY > nextY)
3997
                                            newY = (point[1] + nextY) / 2;
3998
                                    }
3999
                                    else
4000
                                    {
4001
                                        newY = tempY - gridSetting.Length;
4002
                                        if (newY < nextY)
4003
                                            newY = (point[1] + nextY) / 2;
4004
                                    }
4005
                                    resultPoint = new double[] { resultPoint[0], newY };
4006
                                }
4007
                            }
4008
                        }
4009
                        else if (i == targetVertices.Count - 1)
4010
                        {
4011
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4012
                            bool containZeroLength = false;
4013
                            if (connSymbol != null)
4014
                            {
4015
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4016
                                {
4017
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4018
                                        containZeroLength = true;
4019
                                }
4020
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4021
                                {
4022
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4023
                                        containZeroLength = true;
4024
                                }
4025
                            }
4026

    
4027
                            if (connSymbol == null ||
4028
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4029
                                containZeroLength)
4030
                            {
4031
                                bool bCalcX = false;
4032
                                bool bCalcY = false;
4033
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4034
                                    bCalcX = true;
4035
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4036
                                    bCalcY = true;
4037
                                else
4038
                                {
4039
                                    bCalcX = true;
4040
                                    bCalcY = true;
4041
                                }
4042

    
4043
                                if (bCalcX)
4044
                                {
4045
                                    double nextX = targetVertices[i - 1][0];
4046
                                    double newX = 0;
4047
                                    if (nextX > tempX)
4048
                                    {
4049
                                        newX = tempX + gridSetting.Length;
4050
                                        if (newX > nextX)
4051
                                            newX = (point[0] + nextX) / 2;
4052
                                    }
4053
                                    else
4054
                                    {
4055
                                        newX = tempX - gridSetting.Length;
4056
                                        if (newX < nextX)
4057
                                            newX = (point[0] + nextX) / 2;
4058
                                    }
4059
                                    resultPoint = new double[] { newX, resultPoint[1] };
4060
                                }
4061

    
4062
                                if (bCalcY)
4063
                                {
4064
                                    double nextY = targetVertices[i - 1][1];
4065
                                    double newY = 0;
4066
                                    if (nextY > tempY)
4067
                                    {
4068
                                        newY = tempY + gridSetting.Length;
4069
                                        if (newY > nextY)
4070
                                            newY = (point[1] + nextY) / 2;
4071
                                    }
4072
                                    else
4073
                                    {
4074
                                        newY = tempY - gridSetting.Length;
4075
                                        if (newY < nextY)
4076
                                            newY = (point[1] + nextY) / 2;
4077
                                    }
4078
                                    resultPoint = new double[] { resultPoint[0], newY };
4079
                                }
4080
                            }
4081
                        }
4082
                        break;
4083
                    }
4084
                }
4085
            }
4086

    
4087
            x = resultPoint[0];
4088
            y = resultPoint[1];
4089

    
4090
            return targetConnector;
4091
        }
4092

    
4093
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
4094
        {
4095
            LMConnector result = null;
4096
            List<LMConnector> connectors = new List<LMConnector>();
4097
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4098

    
4099
            if (modelItem != null)
4100
            {
4101
                foreach (LMRepresentation rep in modelItem.Representations)
4102
                {
4103
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4104
                        connectors.Add(dataSource.GetConnector(rep.Id));
4105
                }
4106

    
4107
                ReleaseCOMObjects(modelItem);
4108
            }
4109

    
4110
            if (connectors.Count == 1)
4111
                result = connectors[0];
4112
            else
4113
                foreach (var item in connectors)
4114
                    ReleaseCOMObjects(item);
4115

    
4116
            return result;
4117
        }
4118

    
4119
        private LMConnector GetLMConnectorFirst(string modelItemID)
4120
        {
4121
            LMConnector result = null;
4122
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4123

    
4124
            if (modelItem != null)
4125
            {
4126
                foreach (LMRepresentation rep in modelItem.Representations)
4127
                {
4128
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && 
4129
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
4130
                    {
4131
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4132
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
4133
                        {
4134
                            result = connector;
4135
                            break;
4136
                        }
4137
                        else
4138
                        {
4139
                            ReleaseCOMObjects(connector);
4140
                            connector = null;
4141
                        }
4142
                    }
4143
                }
4144
                ReleaseCOMObjects(modelItem);
4145
                modelItem = null;
4146
            }
4147

    
4148
            return result;
4149
        }
4150

    
4151
        private int GetConnectorCount(string modelItemID)
4152
        {
4153
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4154
            int result = 0;
4155
            if (modelItem != null)
4156
            {
4157
                foreach (LMRepresentation rep in modelItem.Representations)
4158
                {
4159
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4160
                        result++;
4161
                    ReleaseCOMObjects(rep);
4162
                }
4163
                ReleaseCOMObjects(modelItem);
4164
            }
4165

    
4166
            return result;
4167
        }
4168

    
4169
        public List<string> GetRepresentations(string modelItemID)
4170
        {
4171
            List<string> result = new List<string>(); ;
4172
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4173
            if (modelItem != null)
4174
            {
4175
                foreach (LMRepresentation rep in modelItem.Representations)
4176
                {
4177
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4178
                        result.Add(rep.Id);
4179
                }
4180
                ReleaseCOMObjects(modelItem);
4181
            }
4182

    
4183
            return result;
4184
        }
4185

    
4186
        /// <summary>
4187
        /// Line Number Symbol을 실제로 Modeling하는 메서드
4188
        /// </summary>
4189
        /// <param name="lineNumber"></param>
4190
        private void LineNumberModelingOnlyOne(Line line)
4191
        {
4192
            LineNumber lineNumber = document.LINENUMBERS.Find(x => x.CONNLINE == line.UID);
4193
            if (lineNumber != null)
4194
            {
4195
                LMConnector connectedLMConnector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
4196
                if (connectedLMConnector != null)
4197
                {
4198
                    double x = 0;
4199
                    double y = 0;
4200
                    CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4201

    
4202
                    Array points = new double[] { 0, x, y };
4203
                    lineNumber.SPPID.SPPID_X = x;
4204
                    lineNumber.SPPID.SPPID_Y = y;
4205
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4206

    
4207
                    if (_LmLabelPresist != null)
4208
                    {
4209
                        _LmLabelPresist.Commit();
4210
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4211
                        ReleaseCOMObjects(_LmLabelPresist);
4212
                    }
4213
                }
4214
            }
4215
        }
4216

    
4217
        private void LineNumberModeling(LineNumber lineNumber)
4218
        {
4219
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4220
            if (line != null)
4221
            {
4222
                double x = 0;
4223
                double y = 0;
4224
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4225

    
4226
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4227
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
4228
                if (connectedLMConnector != null)
4229
                {
4230
                    Array points = new double[] { 0, x, y };
4231
                    lineNumber.SPPID.SPPID_X = x;
4232
                    lineNumber.SPPID.SPPID_Y = y;
4233
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4234

    
4235
                    if (_LmLabelPresist != null)
4236
                    {
4237
                        _LmLabelPresist.Commit();
4238
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4239
                        ReleaseCOMObjects(_LmLabelPresist);
4240
                    }
4241
                }
4242

    
4243
                foreach (var item in connectorVertices)
4244
                    ReleaseCOMObjects(item.Key);
4245
            }
4246
        }
4247
        private void LineNumberCorrectModeling(LineNumber lineNumber)
4248
        {
4249
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4250
            if (line == null || line.SPPID.Vertices == null)
4251
                return;
4252

    
4253
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
4254
            {
4255
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
4256
                if (removeLabel != null)
4257
                {
4258
                    GridSetting gridSetting = GridSetting.GetInstance();
4259
                    double[] labelRange = null;
4260
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
4261
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4262
                    List<double[]> vertices = GetConnectorVertices(connector);
4263

    
4264
                    double[] resultStart = null;
4265
                    double[] resultEnd = null;
4266
                    double distance = double.MaxValue;
4267
                    for (int i = 0; i < vertices.Count - 1; i++)
4268
                    {
4269
                        double[] startPoint = vertices[i];
4270
                        double[] endPoint = vertices[i + 1];
4271
                        foreach (var item in line.SPPID.Vertices)
4272
                        {
4273
                            double[] lineStartPoint = item[0];
4274
                            double[] lineEndPoint = item[item.Count - 1];
4275

    
4276
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
4277
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
4278
                            if (tempDistance < distance)
4279
                            {
4280
                                distance = tempDistance;
4281
                                resultStart = startPoint;
4282
                                resultEnd = endPoint;
4283
                            }
4284
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
4285
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
4286
                            if (tempDistance < distance)
4287
                            {
4288
                                distance = tempDistance;
4289
                                resultStart = startPoint;
4290
                                resultEnd = endPoint;
4291
                            }
4292
                        }
4293
                    }
4294

    
4295
                    if (resultStart != null && resultEnd != null)
4296
                    {
4297
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
4298
                        double lineStartX = 0;
4299
                        double lineStartY = 0;
4300
                        double lineEndX = 0;
4301
                        double lineEndY = 0;
4302
                        double lineNumberX = 0;
4303
                        double lineNumberY = 0;
4304
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
4305
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
4306

    
4307
                        double lineX = (lineStartX + lineEndX) / 2;
4308
                        double lineY = (lineStartY + lineEndY) / 2;
4309
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
4310
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
4311

    
4312
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4313
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4314
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4315
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4316

    
4317
                        double offsetX = 0;
4318
                        double offsetY = 0;
4319
                        if (slope == SlopeType.HORIZONTAL)
4320
                        {
4321
                            // Line Number 아래
4322
                            if (lineY < lineNumberY)
4323
                            {
4324
                                offsetX = labelCenterX - SPPIDCenterX;
4325
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
4326
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4327
                            }
4328
                            // Line Number 위
4329
                            else
4330
                            {
4331
                                offsetX = labelCenterX - SPPIDCenterX;
4332
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
4333
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4334
                            }
4335
                        }
4336
                        else if (slope == SlopeType.VERTICAL)
4337
                        {
4338
                            // Line Number 오르쪽
4339
                            if (lineX < lineNumberX)
4340
                            {
4341
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
4342
                                offsetY = labelCenterY - SPPIDCenterY;
4343
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4344
                            }
4345
                            // Line Number 왼쪽
4346
                            else
4347
                            {
4348
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
4349
                                offsetY = labelCenterY - SPPIDCenterY;
4350
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4351
                            }
4352
                        }
4353

    
4354
                        if (offsetY != 0 && offsetY != 0)
4355
                        {
4356
                            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
4357
                            Array points = new double[] { 0, lineNumber.SPPID.SPPID_X, lineNumber.SPPID.SPPID_Y };
4358
                            LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connector.AsLMRepresentation(), IsLeaderVisible: false);
4359

    
4360
                            if (_LmLabelPresist != null)
4361
                            {
4362
                                _LmLabelPresist.Commit();
4363
                                lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4364
                            }
4365
                            ReleaseCOMObjects(_LmLabelPresist);
4366
                            _LmLabelPresist = null; 
4367
                        }
4368

    
4369
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4370
                        {
4371
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4372
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4373
                        }
4374
                    }
4375

    
4376

    
4377
                    ReleaseCOMObjects(connector);
4378
                    connector = null;
4379
                }
4380

    
4381
                ReleaseCOMObjects(removeLabel);
4382
                removeLabel = null;
4383
            }
4384
        }
4385
        /// <summary>
4386
        /// Flow Mark Modeling
4387
        /// </summary>
4388
        /// <param name="line"></param>
4389
        private void FlowMarkModeling(Line line)
4390
        {
4391
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
4392
            {
4393
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
4394
                if (connector != null)
4395
                {
4396
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
4397
                    List<double[]> vertices = GetConnectorVertices(connector);
4398
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
4399
                    double[] point = vertices[vertices.Count - 1];
4400
                    Array array = new double[] { 0, point[0], point[1] };
4401
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
4402
                    if (_LMLabelPersist != null)
4403
                    {
4404
                        _LMLabelPersist.Commit();
4405
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
4406
                        ReleaseCOMObjects(_LMLabelPersist);
4407
                    }
4408
                }
4409
            }
4410
        }
4411

    
4412
        /// <summary>
4413
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
4414
        /// </summary>
4415
        /// <param name="lineNumber"></param>
4416
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
4417
        {
4418
            foreach (LineRun run in lineNumber.RUNS)
4419
            {
4420
                foreach (var item in run.RUNITEMS)
4421
                {
4422
                    if (item.GetType() == typeof(Symbol))
4423
                    {
4424
                        Symbol symbol = item as Symbol;
4425
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4426
                        if (_LMSymbol != null)
4427
                        {
4428
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4429

    
4430
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4431
                            {
4432
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4433
                                {
4434
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4435
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4436
                                    {
4437
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4438
                                        if (_LMAAttribute != null)
4439
                                        {
4440
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4441
                                                _LMAAttribute.set_Value(attribute.VALUE);
4442
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4443
                                                _LMAAttribute.set_Value(attribute.VALUE);
4444
                                        }
4445
                                    }
4446
                                }
4447
                                _LMModelItem.Commit();
4448
                            }
4449
                            if (_LMModelItem != null)
4450
                                ReleaseCOMObjects(_LMModelItem);
4451
                        }
4452
                        if (_LMSymbol != null)
4453
                            ReleaseCOMObjects(_LMSymbol);
4454
                    }
4455
                    else if (item.GetType() == typeof(Line))
4456
                    {
4457
                        Line line = item as Line;
4458
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
4459
                        {
4460
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4461
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4462
                            {
4463
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4464
                                {
4465
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4466
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4467
                                    {
4468
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4469
                                        if (_LMAAttribute != null)
4470
                                        {
4471
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4472
                                                _LMAAttribute.set_Value(attribute.VALUE);
4473
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4474
                                                _LMAAttribute.set_Value(attribute.VALUE);
4475

    
4476
                                        }
4477
                                    }
4478
                                }
4479
                                _LMModelItem.Commit();
4480
                            }
4481
                            if (_LMModelItem != null)
4482
                                ReleaseCOMObjects(_LMModelItem);
4483
                            endLine.Add(line.SPPID.ModelItemId);
4484
                        }
4485
                    }
4486
                }
4487
            }
4488
        }
4489

    
4490
        /// <summary>
4491
        /// Symbol Attribute 입력 메서드
4492
        /// </summary>
4493
        /// <param name="item"></param>
4494
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
4495
        {
4496
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
4497
            string sRep = null;
4498
            if (targetItem.GetType() == typeof(Symbol))
4499
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
4500
            else if (targetItem.GetType() == typeof(Equipment))
4501
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
4502

    
4503
            if (!string.IsNullOrEmpty(sRep))
4504
            {
4505
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
4506
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4507
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4508
                
4509
                foreach (var item in targetAttributes)
4510
                {
4511
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4512
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4513
                    {
4514
                        LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4515
                        if (_Attribute != null)
4516
                        {
4517
                            //object associItem = SPPIDUtil.FindObjectByUID(document, item.ASSOCITEM);
4518
                            //if (associItem != null)
4519
                            //{
4520
                            //    if (associItem.GetType() == typeof(Text))
4521
                            //    {
4522
                            //        Text text = associItem as Text;
4523
                            //        text.SPPID.RepresentationId = "Attribute";
4524
                            //    }
4525
                            //    else if (associItem.GetType() == typeof(Note))
4526
                            //    {
4527
                            //        Note note = associItem as Note;
4528
                            //        note.SPPID.RepresentationId = "Attribute";
4529
                            //    }
4530
                            //}
4531
                            _Attribute.set_Value(item.VALUE);
4532
                            // OPC 일경우 Attribute 저장
4533
                            if (targetItem.GetType() == typeof(Symbol))
4534
                            {
4535
                                Symbol symbol = targetItem as Symbol;
4536
                                if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
4537
                                    symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
4538
                            }
4539
                        }
4540
                    }
4541
                }
4542
                _LMModelItem.Commit();
4543

    
4544
                ReleaseCOMObjects(_Attributes);
4545
                ReleaseCOMObjects(_LMModelItem);
4546
                ReleaseCOMObjects(_LMSymbol);
4547
            }
4548
        }
4549

    
4550
        /// <summary>
4551
        /// Input SpecBreak Attribute
4552
        /// </summary>
4553
        /// <param name="specBreak"></param>
4554
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4555
        {
4556
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4557
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4558

    
4559
            if (upStreamObj != null &&
4560
                downStreamObj != null)
4561
            {
4562
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4563

    
4564
                if (targetLMConnector != null)
4565
                {
4566
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4567
                    {
4568
                        string symbolPath = _LMLabelPersist.get_FileName();
4569
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4570
                        if (mapping != null)
4571
                        {
4572
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4573
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4574
                            {
4575
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4576
                                if (values.Length == 2)
4577
                                {
4578
                                    string upStreamValue = values[0];
4579
                                    string downStreamValue = values[1];
4580

    
4581
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4582
                                }
4583
                            }
4584
                        }
4585
                    }
4586

    
4587
                    ReleaseCOMObjects(targetLMConnector);
4588
                }
4589
            }
4590

    
4591

    
4592
            #region 내부에서만 쓰는 메서드
4593
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4594
            {
4595
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4596
                Line upStreamLine = _upStreamObj as Line;
4597
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4598
                Line downStreamLine = _downStreamObj as Line;
4599
                // 둘다 Line일 경우
4600
                if (upStreamLine != null && downStreamLine != null)
4601
                {
4602
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4603
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4604
                }
4605
                // 둘다 Symbol일 경우
4606
                else if (upStreamSymbol != null && downStreamSymbol != null)
4607
                {
4608
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4609
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4610
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4611

    
4612
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4613
                    {
4614
                        if (connector.get_ItemStatus() != "Active")
4615
                            continue;
4616

    
4617
                        if (connector.Id != zeroLenthConnector.Id)
4618
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4619
                    }
4620

    
4621
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4622
                    {
4623
                        if (connector.get_ItemStatus() != "Active")
4624
                            continue;
4625

    
4626
                        if (connector.Id != zeroLenthConnector.Id)
4627
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4628
                    }
4629

    
4630
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4631
                    {
4632
                        if (connector.get_ItemStatus() != "Active")
4633
                            continue;
4634

    
4635
                        if (connector.Id != zeroLenthConnector.Id)
4636
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4637
                    }
4638

    
4639
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4640
                    {
4641
                        if (connector.get_ItemStatus() != "Active")
4642
                            continue;
4643

    
4644
                        if (connector.Id != zeroLenthConnector.Id)
4645
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4646
                    }
4647

    
4648
                    ReleaseCOMObjects(zeroLenthConnector);
4649
                    ReleaseCOMObjects(upStreamLMSymbol);
4650
                    ReleaseCOMObjects(downStreamLMSymbol);
4651
                }
4652
                else if (upStreamSymbol != null && downStreamLine != null)
4653
                {
4654
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4655
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4656
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4657

    
4658
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4659
                    {
4660
                        if (connector.get_ItemStatus() != "Active")
4661
                            continue;
4662

    
4663
                        if (connector.Id == zeroLenthConnector.Id)
4664
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4665
                    }
4666

    
4667
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4668
                    {
4669
                        if (connector.get_ItemStatus() != "Active")
4670
                            continue;
4671

    
4672
                        if (connector.Id == zeroLenthConnector.Id)
4673
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4674
                    }
4675

    
4676
                    ReleaseCOMObjects(zeroLenthConnector);
4677
                    ReleaseCOMObjects(upStreamLMSymbol);
4678
                }
4679
                else if (upStreamLine != null && downStreamSymbol != null)
4680
                {
4681
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4682
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4683
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4684

    
4685
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4686
                    {
4687
                        if (connector.get_ItemStatus() != "Active")
4688
                            continue;
4689

    
4690
                        if (connector.Id == zeroLenthConnector.Id)
4691
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4692
                    }
4693

    
4694
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4695
                    {
4696
                        if (connector.get_ItemStatus() != "Active")
4697
                            continue;
4698

    
4699
                        if (connector.Id == zeroLenthConnector.Id)
4700
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4701
                    }
4702

    
4703
                    ReleaseCOMObjects(zeroLenthConnector);
4704
                    ReleaseCOMObjects(downStreamLMSymbol);
4705
                }
4706
            }
4707

    
4708
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4709
            {
4710
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4711
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4712
                {
4713
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4714
                    if (_LMAAttribute != null)
4715
                    {
4716
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4717
                            _LMAAttribute.set_Value(value);
4718
                        else if (_LMAAttribute.get_Value() != value)
4719
                            _LMAAttribute.set_Value(value);
4720
                    }
4721

    
4722
                    _LMModelItem.Commit();
4723
                }
4724
                if (_LMModelItem != null)
4725
                    ReleaseCOMObjects(_LMModelItem);
4726
            }
4727

    
4728
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4729
            {
4730
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4731
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4732
                {
4733
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4734
                    if (_LMAAttribute != null)
4735
                    {
4736
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4737
                            _LMAAttribute.set_Value(value);
4738
                        else if (_LMAAttribute.get_Value() != value)
4739
                            _LMAAttribute.set_Value(value);
4740
                    }
4741

    
4742
                    _LMModelItem.Commit();
4743
                }
4744
                if (_LMModelItem != null)
4745
                    ReleaseCOMObjects(_LMModelItem);
4746
            }
4747
            #endregion
4748
        }
4749

    
4750
        private void InputEndBreakAttribute(EndBreak endBreak)
4751
        {
4752
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
4753
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
4754

    
4755
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
4756
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
4757
            {
4758
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
4759
                if (labelPersist != null)
4760
                {
4761
                    LMRepresentation representation = labelPersist.RepresentationObject;
4762
                    if (representation != null)
4763
                    {
4764
                        LMConnector connector = dataSource.GetConnector(representation.Id);
4765
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
4766
                        string modelItemID = connector.ModelItemID;
4767
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
4768
                        {
4769
                            List<string> modelItemIDs = new List<string>();
4770
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4771
                            {
4772
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
4773
                                foreach (LMConnector item in symbol.Connect1Connectors)
4774
                                {
4775
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4776
                                        modelItemIDs.Add(item.ModelItemID);
4777
                                    ReleaseCOMObjects(item);
4778
                                }
4779
                                foreach (LMConnector item in symbol.Connect2Connectors)
4780
                                {
4781
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4782
                                        modelItemIDs.Add(item.ModelItemID);
4783
                                    ReleaseCOMObjects(item);
4784
                                }
4785
                                ReleaseCOMObjects(symbol);
4786
                                symbol = null;
4787
                            }
4788
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4789
                            {
4790
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
4791
                                foreach (LMConnector item in symbol.Connect1Connectors)
4792
                                {
4793
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4794
                                        modelItemIDs.Add(item.ModelItemID);
4795
                                    ReleaseCOMObjects(item);
4796
                                }
4797
                                foreach (LMConnector item in symbol.Connect2Connectors)
4798
                                {
4799
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4800
                                        modelItemIDs.Add(item.ModelItemID);
4801
                                    ReleaseCOMObjects(item);
4802
                                }
4803
                                ReleaseCOMObjects(symbol);
4804
                                symbol = null;
4805
                            }
4806

    
4807
                            modelItemIDs = modelItemIDs.Distinct().ToList();
4808
                            if (modelItemIDs.Count == 1)
4809
                            {
4810
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
4811
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
4812
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
4813
                                {
4814
                                    bool result = false;
4815
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
4816
                                    {
4817
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
4818
                                            result = true;
4819
                                        ReleaseCOMObjects(loop);
4820
                                    }
4821

    
4822
                                    if (result)
4823
                                    {
4824
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4825
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4826
                                        ZeroLengthModelItem.Commit();
4827
                                    }
4828
                                    else
4829
                                    {
4830
                                        List<string> loopModelItems = new List<string>();
4831
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
4832
                                        {
4833
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
4834
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4835
                                            {
4836
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4837
                                                    loopModelItems.Add(loop.ModelItemID);
4838
                                                ReleaseCOMObjects(loop);
4839
                                            }
4840
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4841
                                            {
4842
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4843
                                                    loopModelItems.Add(loop.ModelItemID);
4844
                                                ReleaseCOMObjects(loop);
4845
                                            }
4846
                                            ReleaseCOMObjects(_symbol);
4847
                                            _symbol = null;
4848
                                        }
4849
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
4850
                                        {
4851
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
4852
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4853
                                            {
4854
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4855
                                                    loopModelItems.Add(loop.ModelItemID);
4856
                                                ReleaseCOMObjects(loop);
4857
                                            }
4858
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4859
                                            {
4860
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4861
                                                    loopModelItems.Add(loop.ModelItemID);
4862
                                                ReleaseCOMObjects(loop);
4863
                                            }
4864
                                            ReleaseCOMObjects(_symbol);
4865
                                            _symbol = null;
4866
                                        }
4867

    
4868
                                        loopModelItems = loopModelItems.Distinct().ToList();
4869
                                        if (loopModelItems.Count == 1)
4870
                                        {
4871
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
4872
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
4873
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
4874
                                            modelItem.Commit();
4875
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4876
                                            ZeroLengthModelItem.Commit();
4877

    
4878
                                            ReleaseCOMObjects(loopModelItem);
4879
                                            loopModelItem = null;
4880
                                        }
4881
                                    }
4882
                                }
4883
                                else
4884
                                {
4885
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4886
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4887
                                    ZeroLengthModelItem.Commit();
4888
                                }
4889
                                ReleaseCOMObjects(modelItem);
4890
                                modelItem = null;
4891
                                ReleaseCOMObjects(onlyOne);
4892
                                onlyOne = null;
4893
                            }
4894
                        }
4895
                        ReleaseCOMObjects(connector);
4896
                        connector = null;
4897
                        ReleaseCOMObjects(ZeroLengthModelItem);
4898
                        ZeroLengthModelItem = null;
4899
                    }
4900
                    ReleaseCOMObjects(representation);
4901
                    representation = null;
4902
                }
4903
                ReleaseCOMObjects(labelPersist);
4904
                labelPersist = null;
4905
            }
4906
        }
4907

    
4908
        /// <summary>
4909
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
4910
        /// </summary>
4911
        /// <param name="text"></param>
4912
        private void NormalTextModeling(Text text)
4913
        {
4914
            LMSymbol _LMSymbol = null;
4915

    
4916
            LMItemNote _LMItemNote = null;
4917
            LMAAttribute _LMAAttribute = null;
4918

    
4919
            double x = 0;
4920
            double y = 0;
4921
            double angle = text.ANGLE;
4922
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
4923

    
4924
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
4925
            text.SPPID.SPPID_X = x;
4926
            text.SPPID.SPPID_Y = y;
4927

    
4928
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
4929
            if (_LMSymbol != null)
4930
            {
4931
                _LMSymbol.Commit();
4932
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
4933
                if (_LMItemNote != null)
4934
                {
4935
                    _LMItemNote.Commit();
4936
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
4937
                    if (_LMAAttribute != null)
4938
                    {
4939
                        _LMAAttribute.set_Value(text.VALUE);
4940
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
4941
                        _LMItemNote.Commit();
4942

    
4943

    
4944
                        double[] range = null;
4945
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
4946
                        {
4947
                            double[] temp = null;
4948
                            GetSPPIDSymbolRange(labelPersist, ref temp);
4949
                            if (temp != null)
4950
                            {
4951
                                if (range == null)
4952
                                    range = temp;
4953
                                else
4954
                                {
4955
                                    range = new double[] {
4956
                                            Math.Min(range[0], temp[0]),
4957
                                            Math.Min(range[1], temp[1]),
4958
                                            Math.Max(range[2], temp[2]),
4959
                                            Math.Max(range[3], temp[3])
4960
                                        };
4961
                                }
4962
                            }
4963
                        }
4964
                        text.SPPID.Range = range;
4965

    
4966
                        if (_LMAAttribute != null)
4967
                            ReleaseCOMObjects(_LMAAttribute);
4968
                        if (_LMItemNote != null)
4969
                            ReleaseCOMObjects(_LMItemNote);
4970
                    }
4971

    
4972
                    TextCorrectModeling(text);
4973
                }
4974
            }
4975
            if (_LMSymbol != null)
4976
                ReleaseCOMObjects(_LMSymbol);
4977
        }
4978

    
4979
        private void AssociationTextModeling(Text text)
4980
        {
4981
            LMSymbol _LMSymbol = null;
4982
            LMConnector connectedLMConnector = null;
4983
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
4984
            if (owner != null && owner.GetType() == typeof(Symbol))
4985
            {
4986
                Symbol symbol = owner as Symbol;
4987
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4988
                if (_LMSymbol != null)
4989
                {
4990
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
4991
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4992
                    {
4993
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
4994

    
4995
                        if (mapping != null)
4996
                        {
4997
                            double x = 0;
4998
                            double y = 0;
4999

    
5000
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5001
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5002
                            Array array = new double[] { 0, x, y };
5003
                            text.SPPID.SPPID_X = x;
5004
                            text.SPPID.SPPID_Y = y;
5005
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5006
                            if (_LMLabelPersist != null)
5007
                            {
5008
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5009
                                _LMLabelPersist.Commit();
5010
                                ReleaseCOMObjects(_LMLabelPersist);
5011
                            }
5012
                        }
5013
                    }
5014
                }
5015
            }
5016
            else if (owner != null && owner.GetType() == typeof(Line))
5017
            {
5018
                Line line = owner as Line;
5019
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5020
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
5021

    
5022
                if (connectedLMConnector != null)
5023
                {
5024
                    BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5025
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5026
                    {
5027
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5028

    
5029
                        if (mapping != null)
5030
                        {
5031
                            double x = 0;
5032
                            double y = 0;
5033
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5034
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5035
                            Array array = new double[] { 0, x, y };
5036

    
5037
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5038
                            if (_LMLabelPersist != null)
5039
                            {
5040
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5041
                                _LMLabelPersist.Commit();
5042
                                ReleaseCOMObjects(_LMLabelPersist);
5043
                            }
5044
                        }
5045
                    }
5046
                }
5047
            }
5048
            if (_LMSymbol != null)
5049
                ReleaseCOMObjects(_LMSymbol);
5050
        }
5051

    
5052
        private void TextCorrectModeling(Text text)
5053
        {
5054
            if (text.SPPID.Range == null)
5055
                return;
5056

    
5057
            bool needRemodeling = false;
5058
            bool loop = true;
5059
            GridSetting gridSetting = GridSetting.GetInstance();
5060
            while (loop)
5061
            {
5062
                loop = false;
5063
                foreach (var overlapText in document.TEXTINFOS)
5064
                {
5065
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5066
                        continue;
5067

    
5068
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5069
                    {
5070
                        double percentX = 0;
5071
                        double percentY = 0;
5072
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
5073
                        {
5074
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
5075
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
5076
                        }
5077
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
5078
                        {
5079
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
5080
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
5081
                        }
5082

    
5083
                        double tempX = 0;
5084
                        double tempY = 0;
5085
                        bool overlapX = false;
5086
                        bool overlapY = false;
5087
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5088
                        if (percentX >= percentY)
5089
                        {
5090
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5091
                            double move = gridSetting.Length * count;
5092
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
5093
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
5094
                            needRemodeling = true;
5095
                            loop = true;
5096
                        }
5097
                        else
5098
                        {
5099
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5100
                            double move = gridSetting.Length * count;
5101
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
5102
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
5103
                            needRemodeling = true;
5104
                            loop = true;
5105
                        }
5106
                    }
5107
                }
5108
            }
5109
            
5110

    
5111
            if (needRemodeling)
5112
            {
5113
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
5114
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5115
                text.SPPID.RepresentationId = null;
5116

    
5117
                LMItemNote _LMItemNote = null;
5118
                LMAAttribute _LMAAttribute = null;
5119
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
5120
                if (_LMSymbol != null)
5121
                {
5122
                    _LMSymbol.Commit();
5123
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5124
                    if (_LMItemNote != null)
5125
                    {
5126
                        _LMItemNote.Commit();
5127
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5128
                        if (_LMAAttribute != null)
5129
                        {
5130
                            _LMAAttribute.set_Value(text.VALUE);
5131
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5132
                            _LMItemNote.Commit();
5133

    
5134
                            ReleaseCOMObjects(_LMAAttribute);
5135
                            ReleaseCOMObjects(_LMItemNote);
5136
                        }
5137
                    }
5138
                }
5139

    
5140
                ReleaseCOMObjects(symbol);
5141
                symbol = null;
5142
                ReleaseCOMObjects(_LMItemNote);
5143
                _LMItemNote = null;
5144
                ReleaseCOMObjects(_LMAAttribute);
5145
                _LMAAttribute = null;
5146
                ReleaseCOMObjects(_LMSymbol);
5147
                _LMSymbol = null;
5148
            }
5149
        }
5150

    
5151
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
5152
        {
5153
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
5154
            {
5155
                List<Text> texts = new List<Text>();
5156
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5157
                LMRepresentation representation = targetLabel.RepresentationObject;
5158
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
5159
                if (targetLabel.RepresentationObject != null && symbol != null)
5160
                {
5161
                    double[] symbolRange = null;
5162
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
5163
                    if (symbolRange != null)
5164
                    {
5165
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
5166
                        {
5167
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
5168
                            if (findText != null)
5169
                            {
5170
                                double[] range = null;
5171
                                GetSPPIDSymbolRange(labelPersist, ref range);
5172
                                findText.SPPID.Range = range;
5173
                                texts.Add(findText);
5174
                            }
5175

    
5176
                            ReleaseCOMObjects(labelPersist);
5177
                        }
5178

    
5179
                        if (texts.Count > 0)
5180
                        {
5181
                            #region Sort Text By Y
5182
                            texts.Sort(SortTextByY);
5183
                            int SortTextByY(Text a, Text b)
5184
                            {
5185
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
5186
                            }
5187
                            #endregion
5188

    
5189
                            #region 첫번째 Text로 기준 맞춤
5190
                            for (int i = 0; i < texts.Count; i++)
5191
                            {
5192
                                if (i != 0)
5193
                                {
5194
                                    Text currentText = texts[i];
5195
                                    Text prevText = texts[i - 1];
5196
                                    double minY = prevText.SPPID.Range[1];
5197
                                    double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
5198
                                    double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
5199
                                    double _gapX = centerX - centerPrevX;
5200
                                    double _gapY = currentText.SPPID.Range[3] - minY;
5201
                                    MoveText(currentText, _gapX, _gapY);
5202
                                }
5203
                            }
5204
                            List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
5205
                            List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
5206
                            List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
5207
                            List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
5208
                            rangeMinX.Sort();
5209
                            rangeMinY.Sort();
5210
                            rangeMaxX.Sort();
5211
                            rangeMaxY.Sort();
5212
                            double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
5213
                            double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
5214
                            #endregion
5215

    
5216
                            Text correctBySymbol = texts[0];
5217
                            double textCenterX = (text.X1 + text.X2) / 2;
5218
                            double textCenterY = (text.Y1 + text.Y2) / 2;
5219
                            double originX = 0;
5220
                            double originY = 0;
5221
                            SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5222
                            double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5223
                            double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
5224
                            double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
5225

    
5226
                            double gapX = 0;
5227
                            double gapY = 0;
5228
                            if (angle < 45)
5229
                            {
5230
                                // Text 오른쪽
5231
                                if (textCenterX > originX)
5232
                                {
5233
                                    gapX = rangeMinX[0] - symbolRange[2];
5234
                                    gapY = allTextCenterY - symbolCenterY;
5235
                                }
5236
                                // Text 왼쪽
5237
                                else
5238
                                {
5239
                                    gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
5240
                                    gapY = allTextCenterY - symbolCenterY;
5241
                                }
5242
                            }
5243
                            else
5244
                            {
5245
                                // Text 아래쪽
5246
                                if (textCenterY > originY)
5247
                                {
5248
                                    gapX = allTextCenterX - symbolCenterX;
5249
                                    gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
5250
                                }
5251
                                // Text 위쪽
5252
                                else
5253
                                {
5254
                                    gapX = allTextCenterX - symbolCenterX;
5255
                                    gapY = rangeMinY[0] - symbolRange[3];
5256
                                }
5257
                            }
5258

    
5259
                            foreach (var item in texts)
5260
                            {
5261
                                MoveText(item, gapX, gapY);
5262
                                RemodelingAssociationText(item);
5263
                            }
5264
                        }
5265
                    }
5266
                }
5267

    
5268
                void MoveText(Text moveText, double x, double y)
5269
                {
5270
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
5271
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
5272
                    moveText.SPPID.Range = new double[] {
5273
                        moveText.SPPID.Range[0] - x,
5274
                        moveText.SPPID.Range[1]- y,
5275
                        moveText.SPPID.Range[2]- x,
5276
                        moveText.SPPID.Range[3]- y
5277
                    };
5278
                }
5279

    
5280
                endTexts.AddRange(texts);
5281

    
5282
                ReleaseCOMObjects(targetLabel);
5283
                targetLabel = null;
5284
                ReleaseCOMObjects(representation);
5285
                representation = null;
5286
            }
5287
        }
5288

    
5289
        private void RemodelingAssociationText(Text text)
5290
        {
5291
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5292
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5293
            removeLabel.Commit();
5294
            ReleaseCOMObjects(removeLabel);
5295
            removeLabel = null;
5296

    
5297
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5298
            if (owner != null && owner.GetType() == typeof(Symbol))
5299
            {
5300
                Symbol symbol = owner as Symbol;
5301
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5302
                if (_LMSymbol != null)
5303
                {
5304
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5305
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5306
                    {
5307
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5308

    
5309
                        if (mapping != null)
5310
                        {
5311
                            double x = 0;
5312
                            double y = 0;
5313

    
5314
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5315
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5316
                            if (_LMLabelPersist != null)
5317
                            {
5318
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5319
                                _LMLabelPersist.Commit();
5320
                            }
5321
                            ReleaseCOMObjects(_LMLabelPersist);
5322
                            _LMLabelPersist = null;
5323
                        }
5324
                    }
5325
                }
5326
                ReleaseCOMObjects(_LMSymbol);
5327
                _LMSymbol = null;
5328
            }
5329
        }
5330

    
5331
        /// <summary>
5332
        /// Note Modeling
5333
        /// </summary>
5334
        /// <param name="note"></param>
5335
        private void NoteModeling(Note note, List<Note> correctList)
5336
        {
5337
            LMSymbol _LMSymbol = null;
5338
            LMItemNote _LMItemNote = null;
5339
            LMAAttribute _LMAAttribute = null;
5340

    
5341
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5342
            {
5343
                double x = 0;
5344
                double y = 0;
5345

    
5346
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5347
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5348
                note.SPPID.SPPID_X = x;
5349
                note.SPPID.SPPID_Y = y;
5350

    
5351
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5352
                if (_LMSymbol != null)
5353
                {
5354
                    _LMSymbol.Commit();
5355
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5356
                    if (_LMItemNote != null)
5357
                    {
5358
                        _LMItemNote.Commit();
5359
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5360
                        if (_LMAAttribute != null)
5361
                        {
5362
                            _LMAAttribute.set_Value(note.VALUE);
5363
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5364

    
5365
                            double[] range = null;
5366
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5367
                            {
5368
                                double[] temp = null;
5369
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5370
                                if (temp != null)
5371
                                {
5372
                                    if (range == null)
5373
                                        range = temp;
5374
                                    else
5375
                                    {
5376
                                        range = new double[] {
5377
                                            Math.Min(range[0], temp[0]),
5378
                                            Math.Min(range[1], temp[1]),
5379
                                            Math.Max(range[2], temp[2]),
5380
                                            Math.Max(range[3], temp[3])
5381
                                        };
5382
                                    }
5383
                                }
5384
                            }
5385
                            if (range != null)
5386
                                correctList.Add(note);
5387
                            note.SPPID.Range = range;
5388

    
5389

    
5390
                            _LMItemNote.Commit();
5391
                        }
5392
                    }
5393
                }
5394
            }
5395

    
5396
            if (_LMAAttribute != null)
5397
                ReleaseCOMObjects(_LMAAttribute);
5398
            if (_LMItemNote != null)
5399
                ReleaseCOMObjects(_LMItemNote);
5400
            if (_LMSymbol != null)
5401
                ReleaseCOMObjects(_LMSymbol);
5402
        }
5403

    
5404
        private void NoteCorrectModeling(Note note, List<Note> endList)
5405
        {
5406
            bool needRemodeling = false;
5407
            bool loop = true;
5408
            GridSetting gridSetting = GridSetting.GetInstance();
5409
            while (loop)
5410
            {
5411
                loop = false;
5412
                foreach (var overlap in endList)
5413
                {
5414
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5415
                    {
5416
                        double tempX = 0;
5417
                        double tempY = 0;
5418
                        bool overlapX = false;
5419
                        bool overlapY = false;
5420
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5421
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5422
                        if (overlapY && angle >= 45)
5423
                        {
5424
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5425
                            double move = gridSetting.Length * count;
5426
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5427
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5428
                            needRemodeling = true;
5429
                            loop = true;
5430
                        }
5431
                        if (overlapX && angle <= 45)
5432
                        {
5433
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5434
                            double move = gridSetting.Length * count;
5435
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5436
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5437
                            needRemodeling = true;
5438
                            loop = true;
5439
                        }
5440
                    }
5441
                }
5442
            }
5443

    
5444

    
5445
            if (needRemodeling)
5446
            {
5447
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5448
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5449
                note.SPPID.RepresentationId = null;
5450

    
5451
                LMItemNote _LMItemNote = null;
5452
                LMAAttribute _LMAAttribute = null;
5453
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5454
                if (_LMSymbol != null)
5455
                {
5456
                    _LMSymbol.Commit();
5457
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5458
                    if (_LMItemNote != null)
5459
                    {
5460
                        _LMItemNote.Commit();
5461
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5462
                        if (_LMAAttribute != null)
5463
                        {
5464
                            _LMAAttribute.set_Value(note.VALUE);
5465
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5466
                            _LMItemNote.Commit();
5467

    
5468
                            ReleaseCOMObjects(_LMAAttribute);
5469
                            ReleaseCOMObjects(_LMItemNote);
5470
                        }
5471
                    }
5472
                }
5473

    
5474
                ReleaseCOMObjects(symbol);
5475
                symbol = null;
5476
                ReleaseCOMObjects(_LMItemNote);
5477
                _LMItemNote = null;
5478
                ReleaseCOMObjects(_LMAAttribute);
5479
                _LMAAttribute = null;
5480
                ReleaseCOMObjects(_LMSymbol);
5481
                _LMSymbol = null;
5482
            }
5483

    
5484
            endList.Add(note);
5485
        }
5486

    
5487
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5488
        {
5489
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5490
            if (modelItem != null)
5491
            {
5492
                foreach (LMRepresentation rep in modelItem.Representations)
5493
                {
5494
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5495
                    {
5496
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5497
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5498
                        {
5499
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5500
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5501
                            if (modelItemIds.Count == 1)
5502
                            {
5503
                                string joinModelItemId = modelItemIds[0];
5504
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5505
                                if (survivorId != null)
5506
                                    break;
5507
                            }
5508
                        }
5509
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5510
                        {
5511
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5512
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5513
                            if (modelItemIds.Count == 1)
5514
                            {
5515
                                string joinModelItemId = modelItemIds[0];
5516
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5517
                                if (survivorId != null)
5518
                                    break;
5519
                            }
5520
                        }
5521
                    }
5522
                }
5523
            }
5524
        }
5525

    
5526
        /// <summary>
5527
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5528
        /// </summary>
5529
        /// <param name="x"></param>
5530
        /// <param name="y"></param>
5531
        /// <param name="originX"></param>
5532
        /// <param name="originY"></param>
5533
        /// <param name="SPPIDLabelLocation"></param>
5534
        /// <param name="location"></param>
5535
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5536
        {
5537
            if (location == Location.None)
5538
            {
5539
                x = originX;
5540
                y = originY;
5541
            }
5542
            else
5543
            {
5544
                if (location.HasFlag(Location.Center))
5545
                {
5546
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5547
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5548
                }
5549

    
5550
                if (location.HasFlag(Location.Left))
5551
                    x = SPPIDLabelLocation.X1;
5552
                else if (location.HasFlag(Location.Right))
5553
                    x = SPPIDLabelLocation.X2;
5554

    
5555
                if (location.HasFlag(Location.Down))
5556
                    y = SPPIDLabelLocation.Y1;
5557
                else if (location.HasFlag(Location.Up))
5558
                    y = SPPIDLabelLocation.Y2;
5559
            }
5560
        }
5561

    
5562
        /// <summary>
5563
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5564
        /// 1. Angle Valve
5565
        /// 2. 3개로 이루어진 Symbol Group
5566
        /// </summary>
5567
        /// <returns></returns>
5568
        private List<Symbol> GetPrioritySymbol()
5569
        {
5570
            DataTable symbolTable = document.SymbolTable;
5571
            // List에 순서대로 쌓는다.
5572
            List<Symbol> symbols = new List<Symbol>();
5573

    
5574
            // Angle Valve 부터
5575
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5576
            {
5577
                if (!symbols.Contains(symbol))
5578
                {
5579
                    double originX = 0;
5580
                    double originY = 0;
5581

    
5582
                    // ID2 Table에서 Original Point 가져옴.
5583
                    string OriginalPoint = symbolTable.Select(string.Format("UID = {0}", symbol.DBUID))[0]["OriginalPoint"].ToString();
5584
                    SPPIDUtil.ConvertPointBystring(OriginalPoint, ref originX, ref originY);
5585

    
5586
                    SlopeType slopeType1 = SlopeType.None;
5587
                    SlopeType slopeType2 = SlopeType.None;
5588
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5589
                    {
5590
                        double connectorX = 0;
5591
                        double connectorY = 0;
5592
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5593
                        if (slopeType1 == SlopeType.None)
5594
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5595
                        else
5596
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5597
                    }
5598

    
5599
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5600
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5601
                        symbols.Add(symbol);
5602
                }
5603
            }
5604

    
5605
            List<Symbol> tempSymbols = new List<Symbol>();
5606
            // Conn 갯수 기준
5607
            foreach (var item in document.SYMBOLS)
5608
            {
5609
                if (!symbols.Contains(item))
5610
                    tempSymbols.Add(item);
5611
            }
5612
            tempSymbols.Sort(SortSymbolPriority);
5613
            symbols.AddRange(tempSymbols);
5614

    
5615
            return symbols;
5616
        }
5617

    
5618
        private void SetPriorityLine(List<Line> lines)
5619
        {
5620
            lines.Sort(SortLinePriority);
5621

    
5622
            int SortLinePriority(Line a, Line b)
5623
            {
5624
                // Branch 없는것부터
5625
                int branchRetval = CompareBranchLine(a, b);
5626
                if (branchRetval != 0)
5627
                {
5628
                    return branchRetval;
5629
                }
5630
                else
5631
                {
5632
                    // Symbol 연결 갯수
5633
                    int connSymbolRetval = CompareConnSymbol(a, b);
5634
                    if (connSymbolRetval != 0)
5635
                    {
5636
                        return connSymbolRetval;
5637
                    }
5638
                    else
5639
                    {
5640
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5641
                        int connItemRetval = CompareConnItem(a, b);
5642
                        if (connItemRetval != 0)
5643
                        {
5644
                            return connItemRetval;
5645
                        }
5646
                        else
5647
                        {
5648
                            // ConnectedItem이 없는것
5649
                            int noneConnRetval = CompareNoneConn(a, b);
5650
                            if (noneConnRetval != 0)
5651
                            {
5652
                                return noneConnRetval;
5653
                            }
5654
                            else
5655
                            {
5656

    
5657
                            }
5658
                        }
5659
                    }
5660
                }
5661

    
5662
                return 0;
5663
            }
5664

    
5665
            int CompareNotSegmentLine(Line a, Line b)
5666
            {
5667
                List<Connector> connectorsA = a.CONNECTORS
5668
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5669
                    .ToList();
5670

    
5671
                List<Connector> connectorsB = b.CONNECTORS
5672
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5673
                    .ToList();
5674

    
5675
                // 오름차순
5676
                return connectorsB.Count.CompareTo(connectorsA.Count);
5677
            }
5678

    
5679
            int CompareConnSymbol(Line a, Line b)
5680
            {
5681
                List<Connector> connectorsA = a.CONNECTORS
5682
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5683
                    .ToList();
5684

    
5685
                List<Connector> connectorsB = b.CONNECTORS
5686
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5687
                    .ToList();
5688

    
5689
                // 오름차순
5690
                return connectorsB.Count.CompareTo(connectorsA.Count);
5691
            }
5692

    
5693
            int CompareConnItem(Line a, Line b)
5694
            {
5695
                List<Connector> connectorsA = a.CONNECTORS
5696
                    .Where(conn => conn.ConnectedObject != null && 
5697
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5698
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5699
                    .ToList();
5700

    
5701
                List<Connector> connectorsB = b.CONNECTORS
5702
                    .Where(conn => conn.ConnectedObject != null &&
5703
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5704
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5705
                    .ToList();
5706

    
5707
                // 오름차순
5708
                return connectorsB.Count.CompareTo(connectorsA.Count);
5709
            }
5710

    
5711
            int CompareBranchLine(Line a, Line b)
5712
            {
5713
                List<Connector> connectorsA = a.CONNECTORS
5714
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5715
                    .ToList();
5716
                List<Connector> connectorsB = b.CONNECTORS
5717
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5718
                    .ToList();
5719

    
5720
                // 내림차순
5721
                return connectorsA.Count.CompareTo(connectorsB.Count);
5722
            }
5723

    
5724
            int CompareNoneConn(Line a, Line b)
5725
            {
5726
                List<Connector> connectorsA = a.CONNECTORS
5727
                    .Where(conn => conn.ConnectedObject == null)
5728
                    .ToList();
5729

    
5730
                List<Connector> connectorsB = b.CONNECTORS
5731
                    .Where(conn => conn.ConnectedObject == null)
5732
                    .ToList();
5733

    
5734
                // 오름차순
5735
                return connectorsB.Count.CompareTo(connectorsA.Count);
5736
            }
5737
        }
5738

    
5739
        private void SortText(List<Text> texts)
5740
        {
5741
            texts.Sort(Sort);
5742

    
5743
            int Sort(Text a, Text b)
5744
            {
5745
                int yRetval = CompareY(a, b);
5746
                if (yRetval != 0)
5747
                {
5748
                    return yRetval;
5749
                }
5750
                else
5751
                {
5752
                    return CompareX(a, b);
5753
                }
5754
            }
5755

    
5756
            int CompareY(Text a, Text b)
5757
            {
5758
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5759
            }
5760

    
5761
            int CompareX(Text a, Text b)
5762
            {
5763
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5764
            }
5765
        }
5766
        private void SortNote(List<Note> notes)
5767
        {
5768
            notes.Sort(Sort);
5769

    
5770
            int Sort(Note a, Note b)
5771
            {
5772
                int yRetval = CompareY(a, b);
5773
                if (yRetval != 0)
5774
                {
5775
                    return yRetval;
5776
                }
5777
                else
5778
                {
5779
                    return CompareX(a, b);
5780
                }
5781
            }
5782

    
5783
            int CompareY(Note a, Note b)
5784
            {
5785
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5786
            }
5787

    
5788
            int CompareX(Note a, Note b)
5789
            {
5790
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5791
            }
5792
        }
5793

    
5794
        private void SortBranchLines()
5795
        {
5796
            BranchLines.Sort(SortBranchLine);
5797
            int SortBranchLine(Line a, Line b)
5798
            {
5799
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5800
                 x.ConnectedObject.GetType() == typeof(Line) &&
5801
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
5802
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5803

    
5804
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
5805
                 x.ConnectedObject.GetType() == typeof(Line) &&
5806
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
5807
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
5808

    
5809
                // 내림차순
5810
                return countA.CompareTo(countB);
5811
            }
5812
        }
5813

    
5814
        private static int SortSymbolPriority(Symbol a, Symbol b)
5815
        {
5816
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5817
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
5818
            int retval = countB.CompareTo(countA);
5819
            if (retval != 0)
5820
                return retval;
5821
            else
5822
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
5823
        }
5824

    
5825
        private string GetSPPIDFileName(LMModelItem modelItem)
5826
        {
5827
            string symbolPath = null;
5828
            foreach (LMRepresentation rep in modelItem.Representations)
5829
            {
5830
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5831
                {
5832
                    symbolPath = rep.get_FileName();
5833
                    break;
5834
                }
5835
            }
5836
            return symbolPath;
5837
        }
5838

    
5839
        private string GetSPPIDFileName(string modelItemId)
5840
        {
5841
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5842
            string symbolPath = null;
5843
            foreach (LMRepresentation rep in modelItem.Representations)
5844
            {
5845
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
5846
                {
5847
                    symbolPath = rep.get_FileName();
5848
                    break;
5849
                }
5850
            }
5851
            ReleaseCOMObjects(modelItem);
5852
            return symbolPath;
5853
        }
5854

    
5855
        /// <summary>
5856
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
5857
        /// </summary>
5858
        /// <param name="graphicOID"></param>
5859
        /// <param name="milliseconds"></param>
5860
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
5861
        {
5862
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
5863
            {
5864
                double minX = 0;
5865
                double minY = 0;
5866
                double maxX = 0;
5867
                double maxY = 0;
5868
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
5869
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
5870

    
5871
                Thread.Sleep(milliseconds);
5872
            }
5873
        }
5874

    
5875
        /// <summary>
5876
        /// ComObject를 Release
5877
        /// </summary>
5878
        /// <param name="objVars"></param>
5879
        public void ReleaseCOMObjects(params object[] objVars)
5880
        {
5881
            if (objVars != null)
5882
            {
5883
                int intNewRefCount = 0;
5884
                foreach (object obj in objVars)
5885
                {
5886
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
5887
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
5888
                }
5889
            }
5890
        }
5891

    
5892
        /// IDisposable 구현
5893
        ~AutoModeling()
5894
        {
5895
            this.Dispose(false);
5896
        }
5897

    
5898
        private bool disposed;
5899
        public void Dispose()
5900
        {
5901
            this.Dispose(true);
5902
            GC.SuppressFinalize(this);
5903
        }
5904

    
5905
        protected virtual void Dispose(bool disposing)
5906
        {
5907
            if (this.disposed) return;
5908
            if (disposing)
5909
            {
5910
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
5911
            }
5912
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
5913
            this.disposed = true;
5914
        }
5915
    }
5916
}
클립보드 이미지 추가 (최대 크기: 500 MB)