프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ da1aeb27

이력 | 보기 | 이력해설 | 다운로드 (287 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
                Project_DB.InsertLineNumberInfo(document.PATH, drawingNumber, drawingName, document);
154

    
155
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
156
                {
157
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
158
                    SplashScreenManager.CloseForm(false);
159
                    Log.Write("\r\n");
160
                }
161
                Thread.Sleep(1000);
162

    
163
                Log.Write("End Modeling");
164
                radApp.ActiveWindow.Fit();
165

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

    
183
                ReleaseCOMObjects(dataSource);
184
                dataSource = null;
185
                ReleaseCOMObjects(_placement);
186
                _placement = null;
187

    
188
                Thread.Sleep(1000);
189

    
190

    
191

    
192
            }
193
        }
194

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

    
264
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
265
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
266

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

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

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

    
344
                        GridSetting grid = GridSetting.GetInstance();
345
                        int count = grid.DrainValveCellCount;
346
                        double length = grid.Length;
347

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

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

    
405
                                    // 제거
406
                                    RemoveSymbol(connSymbol);
407
                                    RemoveLine(item);
408

    
409
                                    // 재생성
410
                                    SymbolModelingBySymbol(connSymbol);
411
                                    NewLineModeling(item, true);
412
                                }
413
                            }
414

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

    
429
                void SetCoordinate()
430
                {
431
                    Connector branchConnector = item.CONNECTORS.Find(loop => loop.ConnectedObject != null && loop.ConnectedObject.GetType() == typeof(Line));
432
                    if (branchConnector != null)
433
                    {
434
                        Line connLine = branchConnector.ConnectedObject as Line;
435
                        double x = 0;
436
                        double y = 0;
437
                        GetTargetLineConnectorPoint(branchConnector, item, ref x, ref y);
438
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(item, connLine, ref x, ref y);
439
                        if (targetConnector != null)
440
                        {
441
                            List<Symbol> group = new List<Symbol>();
442
                            SPPIDUtil.FindConnectedSymbolGroup(document, item.CONNECTORS.Find(loop => loop != branchConnector).ConnectedObject as Symbol, group);
443
                            if (item.SlopeType == SlopeType.HORIZONTAL)
444
                            {
445
                                item.SPPID.START_Y = y;
446
                                item.SPPID.END_Y = y;
447
                                foreach (var symbol in group)
448
                                {
449
                                    symbol.SPPID.ORIGINAL_Y = y;
450
                                    symbol.SPPID.SPPID_Y = y;
451
                                }
452
                            }
453
                            else if (item.SlopeType == SlopeType.VERTICAL)
454
                            {
455
                                item.SPPID.START_X = x;
456
                                item.SPPID.END_X = x;
457
                                foreach (var symbol in group)
458
                                {
459
                                    symbol.SPPID.ORIGINAL_X = x;
460
                                    symbol.SPPID.SPPID_X = x;
461
                                }
462
                            }
463
                        }
464
                        ReleaseCOMObjects(targetConnector);
465
                        targetConnector = null;
466
                    }
467
                }
468
            }
469
        }
470
        private void RunClearNominalDiameter()
471
        {
472
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.LINES.Count);
473
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Clear Attribute");
474
            return;
475

    
476
            List<string> endClearModelItemID = new List<string>();
477
            for (int i = 0; i < document.LINES.Count; i++)
478
            {
479
                Line item = document.LINES[i];
480
                string modelItemID = item.SPPID.ModelItemId;
481
                if (!string.IsNullOrEmpty(modelItemID))
482
                {
483
                    LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
484
                    if (modelItem != null)
485
                    {
486
                        LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
487
                        if (attribute != null)
488
                            attribute.set_Value(DBNull.Value);
489

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

    
544
                                    modelItem.Commit();
545
                                    ReleaseCOMObjects(modelItem);
546
                                    modelItem = null;
547
                                }
548
                            }
549
                        }
550
                        foreach (LMConnector connector in symbol.Connect2Connectors)
551
                        {
552
                            if (connector.get_ItemStatus() == "Active" && !endClearModelItemID.Contains(connector.ModelItemID))
553
                            {
554
                                endClearModelItemID.Add(connector.ModelItemID);
555
                                LMModelItem modelItem = connector.ModelItemObject;
556
                                if (modelItem != null)
557
                                {
558
                                    LMAAttribute attribute = modelItem.Attributes["NominalDiameter"];
559
                                    if (attribute != null)
560
                                        attribute.set_Value(DBNull.Value);
561

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

    
590
                LMRelationships relationships = new LMRelationships();
591
                relationships.Collect(dataSource, Filter: filter);
592

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

    
734
            foreach (var line in document.LINES)
735
            {
736
                foreach (var connector in line.CONNECTORS)
737
                {
738
                    if (connector.ConnectedObject != null &&
739
                        connector.ConnectedObject.GetType() == typeof(Line) &&
740
                        !SPPIDUtil.IsBranchLine(line, connector.ConnectedObject as Line))
741
                    {
742
                        Line connLine = connector.ConnectedObject as Line;
743
                        if (line.SPPID.ModelItemId != connLine.SPPID.ModelItemId &&
744
                            !string.IsNullOrEmpty(line.SPPID.ModelItemId) &&
745
                            !string.IsNullOrEmpty(connLine.SPPID.ModelItemId) &&
746
                            !SPPIDUtil.IsSegment(document, line, connLine))
747
                        {
748
                            string survivorId = string.Empty;
749
                            JoinRun(connLine.SPPID.ModelItemId, line.SPPID.ModelItemId, ref survivorId);
750
                        }
751

    
752
                    }
753
                }
754
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
755
            }
756

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

    
817
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, correctList.Count);
818
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Note");
819
            SortNote(correctList);
820
            List<Note> endList = new List<Note>();
821
            if (correctList.Count > 0)
822
                endList.Add(correctList[0]);
823
            foreach (var item in correctList)
824
                try
825
                {
826
                    if (!endList.Contains(item))
827
                        NoteCorrectModeling(item, endList);
828
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
829
                }
830
                catch (Exception ex)
831
                {
832
                    Log.Write("Error in NoteModeling");
833
                    Log.Write("UID : " + item.UID);
834
                    Log.Write(ex.Message);
835
                    Log.Write(ex.StackTrace);
836
                }
837
        }
838
        private void RunTextModeling()
839
        {
840
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count);
841
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Texts Modeling");
842
            SortText(document.TEXTINFOS);
843
            foreach (var item in document.TEXTINFOS)
844
                try
845
                {
846
                    if (item.ASSOCIATION)
847
                        AssociationTextModeling(item);
848
                    else
849
                        NormalTextModeling(item);
850
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
851
                }
852
                catch (Exception ex)
853
                {
854
                    Log.Write("Error in TextModeling");
855
                    Log.Write("UID : " + item.UID);
856
                    Log.Write(ex.Message);
857
                    Log.Write(ex.StackTrace);
858
                }
859
        }
860
        private void RunInputLineNumberAttribute()
861
        {
862
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.LINENUMBERS.Count);
863
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set LineNumbers Attribute");
864
            List<string> endLine = new List<string>();
865
            foreach (var item in document.LINENUMBERS)
866
                try
867
                {
868
                    InputLineNumberAttribute(item, endLine);
869
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
870
                }
871
                catch (Exception ex)
872
                {
873
                    Log.Write("Error in InputLineNumberAttribute");
874
                    Log.Write("UID : " + item.UID);
875
                    Log.Write(ex.Message);
876
                    Log.Write(ex.StackTrace);
877
                }
878
        }
879
        private void RunInputSymbolAttribute()
880
        {
881
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count + document.Equipments.Count);
882
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set Symbols Attribute");
883
            foreach (var item in document.SYMBOLS)
884
                try
885
                {
886
                    InputSymbolAttribute(item, item.ATTRIBUTES);
887
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
888
                }
889
                catch (Exception ex)
890
                {
891
                    Log.Write("Error in InputSymbolAttribute");
892
                    Log.Write("UID : " + item.UID);
893
                    Log.Write(ex.Message);
894
                    Log.Write(ex.StackTrace);
895
                }
896

    
897
            foreach (var item in document.Equipments)
898
                try
899
                {
900
                    InputSymbolAttribute(item, item.ATTRIBUTES);
901
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
902
                }
903
                catch (Exception ex)
904
                {
905
                    Log.Write("Error in InputSymbolAttribute");
906
                    Log.Write("UID : " + item.UID);
907
                    Log.Write(ex.Message);
908
                    Log.Write(ex.StackTrace);
909
                }
910
        }
911
        private void RunInputSpecBreakAttribute()
912
        {
913
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SpecBreaks.Count);
914
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set SpecBreak Attribute");
915
            foreach (var item in document.SpecBreaks)
916
                try
917
                {
918
                    InputSpecBreakAttribute(item);
919
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
920
                }
921
                catch (Exception ex)
922
                {
923
                    Log.Write("Error in InputSpecBreakAttribute");
924
                    Log.Write("UID : " + item.UID);
925
                    Log.Write(ex.Message);
926
                    Log.Write(ex.StackTrace);
927
                }
928
        }
929
        private void RunInputEndBreakAttribute()
930
        {
931
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.EndBreaks.Count);
932
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Set EndBreak Attribute");
933
            foreach (var item in document.EndBreaks)
934
                try
935
                {
936
                    InputEndBreakAttribute(item);
937
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
938
                }
939
                catch (Exception ex)
940
                {
941
                    Log.Write("Error in RunInputEndBreakAttribute");
942
                    Log.Write("UID : " + item.UID);
943
                    Log.Write(ex.Message);
944
                    Log.Write(ex.StackTrace);
945
                }
946
        }
947
        private void RunLabelSymbolModeling()
948
        {
949
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.SYMBOLS.Count);
950
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Labels Modeling");
951
            foreach (var item in document.SYMBOLS)
952
                try
953
                {
954
                    LabelSymbolModeling(item);
955
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
956
                }
957
                catch (Exception ex)
958
                {
959
                    Log.Write("Error in LabelSymbolModeling");
960
                    Log.Write("UID : " + item.UID);
961
                    Log.Write(ex.Message);
962
                    Log.Write(ex.StackTrace);
963
                }
964
        }
965
        private void RunCorrectAssociationText()
966
        {
967
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, document.TEXTINFOS.Count + document.LINENUMBERS.Count);
968
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Correct Labels");
969
            List<Text> endTexts = new List<Text>();
970
            foreach (var item in document.TEXTINFOS)
971
            {
972
                try
973
                {
974
                    if (item.ASSOCIATION && !endTexts.Contains(item))
975
                        AssociationTextCorrectModeling(item, endTexts);
976
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
977
                }
978
                catch (Exception ex)
979
                {
980
                    Log.Write("Error in RunCorrectAssociationText");
981
                    Log.Write("UID : " + item.UID);
982
                    Log.Write(ex.Message);
983
                    Log.Write(ex.StackTrace);
984
                }
985
                
986
            }
987

    
988
            foreach (var item in document.LINENUMBERS)
989
            {
990
                try
991
                {
992
                    LineNumberCorrectModeling(item);
993
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
994
                }
995
                catch (Exception ex)
996
                {
997
                    Log.Write("Error in RunCorrectAssociationText");
998
                    Log.Write("UID : " + item.UID);
999
                    Log.Write(ex.Message);
1000
                    Log.Write(ex.StackTrace);
1001
                }
1002
            }
1003
        }
1004
        private void RunETC()
1005
        {
1006
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, FlowMarkRepIds.Count);
1007
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "ETC");
1008
            foreach (var item in FlowMarkRepIds)
1009
            {
1010
                LMLabelPersist label = dataSource.GetLabelPersist(item);
1011
                if (label != null)
1012
                {
1013
                    label.get_GraphicOID();
1014
                    DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[label.get_GraphicOID().ToString()] as DependencyObject;
1015
                    if (dependency != null)
1016
                        dependency.BringToFront();
1017
                }
1018
                ReleaseCOMObjects(label);
1019
                label = null;
1020
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
1021
            }
1022
        }
1023
        /// <summary>
1024
        /// 도면 생성 메서드
1025
        /// </summary>
1026
        private bool CreateDocument(ref string drawingNumber, ref string drawingName)
1027
        {
1028
            Log.Write("------------------ Start create document ------------------");
1029
            GetDrawingNameAndNumber(ref drawingName, ref drawingNumber);
1030
            Log.Write("Drawing name : " + drawingName);
1031
            Log.Write("Drawing number : " + drawingNumber);
1032
            Thread.Sleep(1000);
1033
            newDrawing = application.Drawings.Add(document.Unit, document.Template, drawingNumber, drawingName);
1034
            if (newDrawing != null)
1035
            {
1036
                document.SPPID_DrawingNumber = drawingNumber;
1037
                document.SPPID_DrawingName = drawingName;
1038
                Thread.Sleep(1000);
1039
                radApp.ActiveWindow.Fit();
1040
                Thread.Sleep(1000);
1041
                radApp.ActiveWindow.Zoom = 2000;
1042
                Thread.Sleep(2000);
1043

    
1044
                //current LMDrawing 가져오기
1045
                LMAFilter filter = new LMAFilter();
1046
                LMACriterion criterion = new LMACriterion();
1047
                filter.ItemType = "Drawing";
1048
                criterion.SourceAttributeName = "Name";
1049
                criterion.Operator = "=";
1050
                criterion.set_ValueAttribute(drawingName);
1051
                filter.get_Criteria().Add(criterion);
1052

    
1053
                LMDrawings drawings = new LMDrawings();
1054
                drawings.Collect(dataSource, Filter: filter);
1055

    
1056
                // Input Drawing Attribute
1057
                LMDrawing drawing = ((dynamic)drawings).Nth(1);
1058
                if (drawing != null)
1059
                {
1060
                    using (DataTable drawingAttributeDT = Project_DB.SelectDrawingProjectAttribute())
1061
                    {
1062
                        foreach (DataRow row in drawingAttributeDT.Rows)
1063
                        {
1064
                            string mappingName = DBNull.Value.Equals(row["SPPID_ATTRIBUTE"]) ? string.Empty : row["SPPID_ATTRIBUTE"].ToString();
1065
                            if (!string.IsNullOrEmpty(mappingName))
1066
                            {
1067
                                string uid = row["UID"].ToString();
1068
                                string name = row["NAME"].ToString();
1069
                                Text text = document.TEXTINFOS.Find(x => x.AREA == uid);
1070
                                if (text != null)
1071
                                {
1072
                                    string value = text.VALUE;
1073
                                    LMAAttribute attribute = drawing.Attributes[mappingName];
1074
                                    if (attribute != null)
1075
                                        attribute.set_Value(value);
1076
                                    ReleaseCOMObjects(attribute);
1077
                                    document.TEXTINFOS.Remove(text);
1078
                                }
1079
                            }
1080
                        }
1081

    
1082
                        drawingAttributeDT.Dispose();
1083
                    }
1084

    
1085
                    ReleaseCOMObjects(drawing);
1086
                }
1087

    
1088
                drawingID = ((dynamic)drawings).Nth(1).Id;
1089
                ReleaseCOMObjects(filter);
1090
                ReleaseCOMObjects(criterion);
1091
                ReleaseCOMObjects(drawings);
1092
                filter = null;
1093
                criterion = null;
1094
                drawings = null;
1095
            }
1096
            else
1097
                Log.Write("Fail Create Drawing");
1098

    
1099
            if (newDrawing != null)
1100
            {
1101
                SetBorderFile();
1102
                return true;
1103
            }
1104
            else
1105
                return false;
1106
        }
1107

    
1108
        private void SetBorderFile()
1109
        {
1110
            ETCSetting setting = ETCSetting.GetInstance();
1111

    
1112
            if (!string.IsNullOrEmpty(setting.BorderFilePath) && System.IO.File.Exists(setting.BorderFilePath))
1113
            {
1114
                foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1115
                {
1116
                    if (!string.IsNullOrEmpty(smartFrame.LinkMoniker) && smartFrame.LinkMoniker != setting.BorderFilePath)
1117
                    {
1118
                        smartFrame.ChangeSource(Ingr.RAD2D.OLEInsertionTypeConstant.igOLELinked, setting.BorderFilePath, true);
1119
                        smartFrame.Update();
1120
                    }
1121
                        
1122
                }
1123
            }
1124
        }
1125

    
1126
        /// <summary>
1127
        /// DrawingName, DrawingNumber를 확인하여 중복이 있으면 _1을 붙이고 +1씩 한다.
1128
        /// </summary>
1129
        /// <param name="drawingName"></param>
1130
        /// <param name="drawingNumber"></param>
1131
        private void GetDrawingNameAndNumber(ref string drawingName, ref string drawingNumber)
1132
        {
1133
            LMDrawings drawings = new LMDrawings();
1134
            drawings.Collect(dataSource);
1135

    
1136
            List<string> drawingNameList = new List<string>();
1137
            List<string> drawingNumberList = new List<string>();
1138

    
1139
            foreach (LMDrawing item in drawings)
1140
            {
1141
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
1142
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
1143
            }
1144

    
1145
            int nameLength = drawingName.Length;
1146
            while (drawingNameList.Contains(drawingName))
1147
            {
1148
                if (nameLength == drawingName.Length)
1149
                    drawingName += "-1";
1150
                else
1151
                {
1152
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1153
                    drawingName = drawingName.Substring(0, nameLength + 1);
1154
                    drawingName += ++index;
1155
                }
1156
            }
1157

    
1158
            int numberLength = drawingNumber.Length;
1159
            while (drawingNameList.Contains(drawingNumber))
1160
            {
1161
                if (numberLength == drawingNumber.Length)
1162
                    drawingNumber += "-1";
1163
                else
1164
                {
1165
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1166
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1167
                    drawingNumber += ++index;
1168
                }
1169
            }
1170
            ReleaseCOMObjects(drawings);
1171
            drawings = null;
1172
        }
1173

    
1174
        /// <summary>
1175
        /// 도면 크기 구하는 메서드
1176
        /// </summary>
1177
        /// <returns></returns>
1178
        private bool DocumentCoordinateCorrection()
1179
        {
1180
            if (radApp.ActiveDocument.ActiveSheet.SmartFrames2d.Count > 0)
1181
            {
1182
                double x = 0;
1183
                double y = 0;
1184
                foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1185
                {
1186
                    x = Math.Max(smartFrame.CropRight, x);
1187
                    y = Math.Max(smartFrame.CropTop, y);
1188
                }
1189
                document.SetSPPIDLocation(x, y);
1190
                document.CoordinateCorrection();
1191
                return true;
1192
            }
1193
            else
1194
            {
1195
                Log.Write("Need Border!");
1196
                return false;
1197
            }
1198
        }
1199

    
1200
        /// <summary>
1201
        /// 심볼을 실제로 Modeling 메서드
1202
        /// </summary>
1203
        /// <param name="symbol">생성할 심볼</param>
1204
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1205
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1206
        {
1207
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1208
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1209
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1210
                return;
1211
            // 이미 모델링 됐을 경우
1212
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1213
                return;
1214

    
1215
            LMSymbol _LMSymbol = null;
1216

    
1217
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1218
            double x = symbol.SPPID.ORIGINAL_X;
1219
            double y = symbol.SPPID.ORIGINAL_Y;
1220
            int mirror = 0;
1221
            double angle = symbol.ANGLE;
1222

    
1223
            // OPC 일경우 180도 일때 Mirror
1224
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1225
                mirror = 1;
1226

    
1227
            // Mirror 계산
1228
            if (symbol.FLIP == 1)
1229
            {
1230
                mirror = 1;
1231
                angle += Math.PI;
1232
            }
1233

    
1234
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1235
            {
1236
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1237
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1238
                if (connector != null)
1239
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1240

    
1241
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1242
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1243
                if (temp != null)
1244
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1245
                ReleaseCOMObjects(temp);
1246
                temp = null;
1247

    
1248
                if (_LMSymbol != null && _TargetItem != null)
1249
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1250

    
1251
                ReleaseCOMObjects(_TargetItem);
1252
            }
1253
            else
1254
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1255

    
1256
            if (_LMSymbol != null)
1257
            {
1258
                _LMSymbol.Commit();
1259

    
1260
                // ConnCheck
1261
                List<string> ids = new List<string>();
1262
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1263
                {
1264
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1265
                        ids.Add(item.Id);
1266
                    ReleaseCOMObjects(item);
1267
                }
1268
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1269
                {
1270
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1271
                        ids.Add(item.Id);
1272
                    ReleaseCOMObjects(item);
1273
                }
1274

    
1275
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1276
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1277
                {
1278
                    double currentX = _LMSymbol.get_XCoordinate();
1279
                    double currentY = _LMSymbol.get_YCoordinate();
1280

    
1281

    
1282
                }
1283

    
1284
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1285
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1286
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1287

    
1288
                foreach (var item in symbol.ChildSymbols)
1289
                    CreateChildSymbol(item, _LMSymbol, symbol);
1290

    
1291
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1292
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1293

    
1294
                double[] range = null;
1295
                GetSPPIDSymbolRange(symbol, ref range);
1296
                symbol.SPPID.SPPID_Min_X = range[0];
1297
                symbol.SPPID.SPPID_Min_Y = range[1];
1298
                symbol.SPPID.SPPID_Max_X = range[2];
1299
                symbol.SPPID.SPPID_Max_Y = range[3];
1300

    
1301
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1302
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1303
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1304
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1305

    
1306
                ReleaseCOMObjects(_LMSymbol);
1307
            }
1308
        }
1309
        /// <summary>
1310
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1311
        /// Signal Point는 고려하지 않음
1312
        /// </summary>
1313
        /// <param name="symbol"></param>
1314
        /// <param name="_TargetItem"></param>
1315
        /// <param name="targetX"></param>
1316
        /// <param name="targetY"></param>
1317
        /// <returns></returns>
1318
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1319
        {
1320
            LMConnector tempConnector = null;
1321

    
1322
            List<Symbol> group = new List<Symbol>();
1323
            SPPIDUtil.FindConnectedSymbolGroup(document, symbol, group);
1324
            if (group.FindAll(loopX => !string.IsNullOrEmpty(loopX.SPPID.RepresentationId)).Count == 1)
1325
            {
1326
                List<Connector> connectors = new List<Connector>();
1327
                foreach (var item in group)
1328
                    connectors.AddRange(item.CONNECTORS.FindAll(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line)));
1329
                /// Primary or Secondary Type Line만 고려
1330
                Connector _connector = connectors.Find(loopX => loopX.ConnectedObject != null && loopX.ConnectedObject.GetType() == typeof(Line) &&
1331
                (((Line)loopX.ConnectedObject).TYPE == "Primary" || ((Line)loopX.ConnectedObject).TYPE == "Secondary"));
1332
                if (_connector != null)
1333
                {
1334
                    string sppidLine = ((Line)_connector.ConnectedObject).SPPID.MAPPINGNAME;
1335
                    List<double[]> pointInfos = getPipingPoints(_TargetItem);
1336
                    /// PipingPoint가 2개 이상만
1337
                    if (pointInfos.Count >= 2)
1338
                    {
1339
                        double lineX = 0;
1340
                        double lineY = 0;
1341
                        double length = 0;
1342
                        foreach (var item in pointInfos)
1343
                        {
1344
                            double tempX = item[1];
1345
                            double tempY = item[2];
1346

    
1347
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1348
                            if (calcDistance > length)
1349
                            {
1350
                                lineX = tempX;
1351
                                lineY = tempY;
1352
                            }
1353
                        }
1354

    
1355
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1356
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1357
                        placeRunInputs.AddPoint(-1, -1);
1358
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1359
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1360
                        if (tempConnector != null)
1361
                            tempConnector.Commit();
1362
                        ReleaseCOMObjects(_LMAItem);
1363
                        _LMAItem = null;
1364
                        ReleaseCOMObjects(placeRunInputs);
1365
                        placeRunInputs = null;
1366
                    }
1367
                }
1368
            }
1369

    
1370
            return tempConnector;
1371
        }
1372
        /// <summary>
1373
        /// Symbol의 PipingPoints를 구함
1374
        /// SignalPoint는 고려하지 않음
1375
        /// </summary>
1376
        /// <param name="symbol"></param>
1377
        /// <returns></returns>
1378
        private List<double[]> getPipingPoints(LMSymbol symbol)
1379
        {
1380
            LMModelItem modelItem = symbol.ModelItemObject;
1381
            LMPipingPoints pipingPoints = null;
1382
            if (modelItem.get_ItemTypeName() == "PipingComp")
1383
            {
1384
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1385
                pipingPoints = pipingComp.PipingPoints;
1386
                ReleaseCOMObjects(pipingComp);
1387
                pipingComp = null;
1388
            }
1389
            else if (modelItem.get_ItemTypeName() == "Instrument")
1390
            {
1391
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1392
                pipingPoints = instrument.PipingPoints;
1393
                ReleaseCOMObjects(instrument);
1394
                instrument = null;
1395
            }
1396
            else
1397
                Log.Write("다른 Type");
1398

    
1399
            List<double[]> info = new List<double[]>();
1400
            if (pipingPoints != null)
1401
            {
1402
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1403
                {
1404
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1405
                    {
1406
                        if (attribute.Name == "PipingPointNumber")
1407
                        {
1408
                            int index = Convert.ToInt32(attribute.get_Value());
1409
                            if (info.Find(loopX => loopX[0] == index) == null)
1410
                            {
1411
                                double x = 0;
1412
                                double y = 0;
1413
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1414
                                    info.Add(new double[] { index, x, y });
1415
                            }
1416
                        }
1417
                    }
1418
                }
1419
            }
1420
            ReleaseCOMObjects(modelItem);
1421
            modelItem = null;
1422
            ReleaseCOMObjects(pipingPoints);
1423
            pipingPoints = null;
1424

    
1425
            return info;
1426
        }
1427

    
1428
        private void RemoveSymbol(Symbol symbol)
1429
        {
1430
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1431
            {
1432
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1433
                if (_LMSymbol != null)
1434
                {
1435
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1436
                    ReleaseCOMObjects(_LMSymbol);
1437
                }
1438
            }
1439

    
1440
            symbol.SPPID.RepresentationId = string.Empty;
1441
            symbol.SPPID.ModelItemID = string.Empty;
1442
            symbol.SPPID.SPPID_X = double.NaN;
1443
            symbol.SPPID.SPPID_Y = double.NaN;
1444
            symbol.SPPID.SPPID_Min_X = double.NaN;
1445
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1446
            symbol.SPPID.SPPID_Max_X = double.NaN;
1447
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1448
        }
1449

    
1450
        private void RemoveSymbol(List<Symbol> symbols)
1451
        {
1452
            foreach (var symbol in symbols)
1453
            {
1454
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1455
                {
1456
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1457
                    if (_LMSymbol != null)
1458
                    {
1459
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1460
                        ReleaseCOMObjects(_LMSymbol);
1461
                    }
1462
                }
1463

    
1464
                symbol.SPPID.RepresentationId = string.Empty;
1465
                symbol.SPPID.ModelItemID = string.Empty;
1466
                symbol.SPPID.SPPID_X = double.NaN;
1467
                symbol.SPPID.SPPID_Y = double.NaN;
1468
                symbol.SPPID.SPPID_Min_X = double.NaN;
1469
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1470
                symbol.SPPID.SPPID_Max_X = double.NaN;
1471
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1472
            }
1473
        }
1474

    
1475
        /// <summary>
1476
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1477
        /// </summary>
1478
        /// <param name="targetConnector"></param>
1479
        /// <param name="targetSymbol"></param>
1480
        /// <param name="x"></param>
1481
        /// <param name="y"></param>
1482
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1483
        {
1484
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1485

    
1486
            double[] range = null;
1487
            List<double[]> points = new List<double[]>();
1488
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1489
            double x1 = range[0];
1490
            double y1 = range[1];
1491
            double x2 = range[2];
1492
            double y2 = range[3];
1493

    
1494
            // Origin 기준 Connector의 위치차이
1495
            double sceneX = 0;
1496
            double sceneY = 0;
1497
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1498
            double originX = 0;
1499
            double originY = 0;
1500
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1501
            double gapX = originX - sceneX;
1502
            double gapY = originY - sceneY;
1503

    
1504
            // SPPID Symbol과 ID2 심볼의 크기 차이
1505
            double sizeWidth = 0;
1506
            double sizeHeight = 0;
1507
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1508
            if (sizeWidth == 0 || sizeHeight == 0)
1509
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1510

    
1511
            double percentX = (x2 - x1) / sizeWidth;
1512
            double percentY = (y2 - y1) / sizeHeight;
1513

    
1514
            double SPPIDgapX = gapX * percentX;
1515
            double SPPIDgapY = gapY * percentY;
1516

    
1517
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1518
            double distance = double.MaxValue;
1519
            double[] resultPoint;
1520
            foreach (var point in points)
1521
            {
1522
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1523
                if (distance > result)
1524
                {
1525
                    distance = result;
1526
                    resultPoint = point;
1527
                    x = point[0];
1528
                    y = point[1];
1529
                }
1530
            }
1531

    
1532
            ReleaseCOMObjects(_TargetItem);
1533
        }
1534

    
1535
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1536
        {
1537
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1538
            if (index == 0)
1539
            {
1540
                x = targetLine.SPPID.START_X;
1541
                y = targetLine.SPPID.START_Y;
1542
            }
1543
            else
1544
            {
1545
                x = targetLine.SPPID.END_X;
1546
                y = targetLine.SPPID.END_Y;
1547
            }
1548
        }
1549

    
1550
        /// <summary>
1551
        /// SPPID Symbol의 Range를 구한다.
1552
        /// </summary>
1553
        /// <param name="symbol"></param>
1554
        /// <param name="range"></param>
1555
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1556
        {
1557
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1558
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1559
            double x1 = 0;
1560
            double y1 = 0;
1561
            double x2 = 0;
1562
            double y2 = 0;
1563
            symbol2d.Range(out x1, out y1, out x2, out y2);
1564
            range = new double[] { x1, y1, x2, y2 };
1565

    
1566
            for (int i = 1; i < int.MaxValue; i++)
1567
            {
1568
                double connX = 0;
1569
                double connY = 0;
1570
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1571
                    points.Add(new double[] { connX, connY });
1572
                else
1573
                    break;
1574
            }
1575

    
1576
            foreach (var childSymbol in symbol.ChildSymbols)
1577
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1578

    
1579
            ReleaseCOMObjects(_TargetItem);
1580
        }
1581

    
1582
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1583
        {
1584
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1585
            if (_TargetItem != null)
1586
            {
1587
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1588
                double x1 = 0;
1589
                double y1 = 0;
1590
                double x2 = 0;
1591
                double y2 = 0;
1592
                if (!bForGraphic)
1593
                {
1594
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1595
                    range = new double[] { x1, y1, x2, y2 };
1596
                }
1597
                else
1598
                {
1599
                    x1 = double.MaxValue;
1600
                    y1 = double.MaxValue;
1601
                    x2 = double.MinValue;
1602
                    y2 = double.MinValue;
1603
                    range = new double[] { x1, y1, x2, y2 };
1604

    
1605
                    foreach (var item in symbol2d.DrawingObjects)
1606
                    {
1607
                        if (item.GetType() == typeof(Ingr.RAD2D.Line2d))
1608
                        {
1609
                            Ingr.RAD2D.Line2d rangeObject = item as Ingr.RAD2D.Line2d;
1610
                            if (rangeObject.Layer == "Default")
1611
                            {
1612
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1613
                                range = new double[] {
1614
                                Math.Min(x1, range[0]),
1615
                                Math.Min(y1, range[1]),
1616
                                Math.Max(x2, range[2]),
1617
                                Math.Max(y2, range[3])
1618
                            };
1619
                            }
1620
                        }
1621
                        else if (item.GetType() == typeof(Ingr.RAD2D.Circle2d))
1622
                        {
1623
                            Ingr.RAD2D.Circle2d rangeObject = item as Ingr.RAD2D.Circle2d;
1624
                            if (rangeObject.Layer == "Default")
1625
                            {
1626
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1627
                                range = new double[] {
1628
                                Math.Min(x1, range[0]),
1629
                                Math.Min(y1, range[1]),
1630
                                Math.Max(x2, range[2]),
1631
                                Math.Max(y2, range[3])
1632
                            };
1633
                            }
1634
                        }
1635
                        else if (item.GetType() == typeof(Ingr.RAD2D.Rectangle2d))
1636
                        {
1637
                            Ingr.RAD2D.Rectangle2d rangeObject = item as Ingr.RAD2D.Rectangle2d;
1638
                            if (rangeObject.Layer == "Default")
1639
                            {
1640
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1641
                                range = new double[] {
1642
                                Math.Min(x1, range[0]),
1643
                                Math.Min(y1, range[1]),
1644
                                Math.Max(x2, range[2]),
1645
                                Math.Max(y2, range[3])
1646
                            };
1647
                            }
1648
                        }
1649
                        else if (item.GetType() == typeof(Ingr.RAD2D.Arc2d))
1650
                        {
1651
                            Ingr.RAD2D.Arc2d rangeObject = item as Ingr.RAD2D.Arc2d;
1652
                            if (rangeObject.Layer == "Default")
1653
                            {
1654
                                rangeObject.Range(out x1, out y1, out x2, out y2);
1655
                                range = new double[] {
1656
                                Math.Min(x1, range[0]),
1657
                                Math.Min(y1, range[1]),
1658
                                Math.Max(x2, range[2]),
1659
                                Math.Max(y2, range[3])
1660
                            };
1661
                            }
1662
                        }
1663
                    }
1664
                }
1665

    
1666
                if (!bOnlySymbol)
1667
                {
1668
                    foreach (var childSymbol in symbol.ChildSymbols)
1669
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1670
                }
1671
                ReleaseCOMObjects(_TargetItem);
1672
            }
1673
        }
1674

    
1675
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1676
        {
1677
            if (labelPersist != null)
1678
            {
1679
                double x1 = double.MaxValue;
1680
                double y1 = double.MaxValue;
1681
                double x2 = double.MinValue;
1682
                double y2 = double.MinValue;
1683
                range = new double[] { x1, y1, x2, y2 };
1684

    
1685
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1686
                foreach (var item in dependency.DrawingObjects)
1687
                {
1688
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1689
                    if (textBox != null)
1690
                    {
1691
                        if (dependency != null)
1692
                        {
1693
                            double tempX1;
1694
                            double tempY1;
1695
                            double tempX2;
1696
                            double tempY2;
1697
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1698
                            x1 = Math.Min(x1, tempX1);
1699
                            y1 = Math.Min(y1, tempY1);
1700
                            x2 = Math.Max(x2, tempX2);
1701
                            y2 = Math.Max(y2, tempY2);
1702

    
1703
                            range = new double[] { x1, y1, x2, y2 };
1704
                        }
1705
                    }
1706
                }
1707
                
1708
            }
1709
        }
1710

    
1711
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1712
        {
1713
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1714
            foreach (var symbol in symbols)
1715
            {
1716
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1717
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1718
                double x1 = 0;
1719
                double y1 = 0;
1720
                double x2 = 0;
1721
                double y2 = 0;
1722
                symbol2d.Range(out x1, out y1, out x2, out y2);
1723

    
1724
                tempRange[0] = Math.Min(tempRange[0], x1);
1725
                tempRange[1] = Math.Min(tempRange[1], y1);
1726
                tempRange[2] = Math.Max(tempRange[2], x2);
1727
                tempRange[3] = Math.Max(tempRange[3], y2);
1728

    
1729
                foreach (var childSymbol in symbol.ChildSymbols)
1730
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1731

    
1732
                ReleaseCOMObjects(_TargetItem);
1733
            }
1734

    
1735
            range = tempRange;
1736
        }
1737

    
1738
        /// <summary>
1739
        /// Child Modeling 된 Symbol의 Range를 구한다.
1740
        /// </summary>
1741
        /// <param name="childSymbol"></param>
1742
        /// <param name="range"></param>
1743
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range, List<double[]> points)
1744
        {
1745
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1746
            if (_ChildSymbol != null)
1747
            {
1748
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1749
                double x1 = 0;
1750
                double y1 = 0;
1751
                double x2 = 0;
1752
                double y2 = 0;
1753
                symbol2d.Range(out x1, out y1, out x2, out y2);
1754
                range[0] = Math.Min(range[0], x1);
1755
                range[1] = Math.Min(range[1], y1);
1756
                range[2] = Math.Max(range[2], x2);
1757
                range[3] = Math.Max(range[3], y2);
1758

    
1759
                for (int i = 1; i < int.MaxValue; i++)
1760
                {
1761
                    double connX = 0;
1762
                    double connY = 0;
1763
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1764
                        points.Add(new double[] { connX, connY });
1765
                    else
1766
                        break;
1767
                }
1768

    
1769
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1770
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1771

    
1772
                ReleaseCOMObjects(_ChildSymbol);
1773
            }
1774
        }
1775

    
1776
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1777
        {
1778
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1779
            if (_ChildSymbol != null)
1780
            {
1781
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1782
                double x1 = 0;
1783
                double y1 = 0;
1784
                double x2 = 0;
1785
                double y2 = 0;
1786
                symbol2d.Range(out x1, out y1, out x2, out y2);
1787
                range[0] = Math.Min(range[0], x1);
1788
                range[1] = Math.Min(range[1], y1);
1789
                range[2] = Math.Max(range[2], x2);
1790
                range[3] = Math.Max(range[3], y2);
1791

    
1792
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1793
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1794
                ReleaseCOMObjects(_ChildSymbol);
1795
            }
1796
        }
1797

    
1798
        /// <summary>
1799
        /// Label Symbol Modeling
1800
        /// </summary>
1801
        /// <param name="symbol"></param>
1802
        private void LabelSymbolModeling(Symbol symbol)
1803
        {
1804
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1805
            {
1806
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1807
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1808
                    return;
1809
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1810

    
1811
                string symbolUID = itemAttribute.VALUE;
1812
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1813
                if (targetItem != null &&
1814
                    (targetItem.GetType() == typeof(Symbol) ||
1815
                    targetItem.GetType() == typeof(Equipment)))
1816
                {
1817
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1818
                    string sRep = null;
1819
                    if (targetItem.GetType() == typeof(Symbol))
1820
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1821
                    else if (targetItem.GetType() == typeof(Equipment))
1822
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1823
                    if (!string.IsNullOrEmpty(sRep))
1824
                    {
1825
                        // LEADER Line 검사
1826
                        bool leaderLine = false;
1827
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1828
                        if (symbolMapping != null)
1829
                            leaderLine = symbolMapping.LEADERLINE;
1830

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

    
1835
                        //Leader 선 센터로
1836
                        if (_LMLabelPresist != null)
1837
                        {
1838
                            // Target Item에 Label의 Attribute Input
1839
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1840

    
1841
                            string OID = _LMLabelPresist.get_GraphicOID().ToString();
1842
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID] as DependencyObject;
1843
                            if (dependency != null)
1844
                            {
1845
                                bool result = false;
1846
                                foreach (var attributes in dependency.AttributeSets)
1847
                                {
1848
                                    foreach (var attribute in attributes)
1849
                                    {
1850
                                        string name = attribute.Name;
1851
                                        string value = attribute.GetValue().ToString();
1852
                                        if (name == "DrawingItemType" && value == "LabelPersist")
1853
                                        {
1854
                                            foreach (DrawingObjectBase drawingObject in dependency.DrawingObjects)
1855
                                            {
1856
                                                if (drawingObject.Type == Ingr.RAD2D.ObjectType.igLineString2d)
1857
                                                {
1858
                                                    Ingr.RAD2D.LineString2d lineString2D = drawingObject as Ingr.RAD2D.LineString2d;
1859
                                                    double prevX = _TargetItem.get_XCoordinate();
1860
                                                    double prevY = _TargetItem.get_YCoordinate();
1861
                                                    lineString2D.InsertVertex(lineString2D.VertexCount, prevX, prevY);
1862
                                                    lineString2D.RemoveVertex(lineString2D.VertexCount);
1863
                                                    result = true;
1864
                                                    break;
1865
                                                }
1866
                                            }
1867
                                        }
1868

    
1869
                                        if (result)
1870
                                            break;
1871
                                    }
1872

    
1873
                                    if (result)
1874
                                        break;
1875
                                }
1876
                            }
1877

    
1878
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1879
                            _LMLabelPresist.Commit();
1880
                            ReleaseCOMObjects(_LMLabelPresist);
1881
                        }
1882

    
1883
                        ReleaseCOMObjects(_TargetItem);
1884
                    }
1885
                }
1886
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1887
                {
1888
                    Line targetLine = targetItem as Line;
1889
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1890
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1891
                    if (connectedLMConnector != null)
1892
                    {
1893
                        // LEADER Line 검사
1894
                        bool leaderLine = false;
1895
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1896
                        if (symbolMapping != null)
1897
                            leaderLine = symbolMapping.LEADERLINE;
1898

    
1899
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1900
                        if (_LMLabelPresist != null)
1901
                        {
1902
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1903
                            _LMLabelPresist.Commit();
1904
                            ReleaseCOMObjects(_LMLabelPresist);
1905
                        }
1906
                        ReleaseCOMObjects(connectedLMConnector);
1907
                    }
1908

    
1909
                    foreach (var item in connectorVertices)
1910
                        if (item.Key != null)
1911
                            ReleaseCOMObjects(item.Key);
1912
                }
1913
            }
1914
        }
1915

    
1916
        /// <summary>
1917
        /// Equipment를 실제로 Modeling 메서드
1918
        /// </summary>
1919
        /// <param name="equipment"></param>
1920
        private void EquipmentModeling(Equipment equipment)
1921
        {
1922
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1923
                return;
1924

    
1925
            LMSymbol _LMSymbol = null;
1926
            LMSymbol targetItem = null;
1927
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1928
            double x = equipment.SPPID.ORIGINAL_X;
1929
            double y = equipment.SPPID.ORIGINAL_Y;
1930
            int mirror = 0;
1931
            double angle = equipment.ANGLE;
1932

    
1933
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1934

    
1935
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1936
            if (connector != null)
1937
            {
1938
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1939
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
1940
                if (connEquipment != null)
1941
                {
1942
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1943
                        EquipmentModeling(connEquipment);
1944

    
1945
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1946
                    {
1947
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1948
                        if (targetItem != null)
1949
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1950
                        else
1951
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1952
                    }
1953
                    else
1954
                    {
1955
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1956
                    }
1957
                }
1958
                else if (connVendorPackage != null)
1959
                {
1960
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
1961
                    {
1962
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
1963
                        if (targetItem != null)
1964
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1965
                        else
1966
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1967
                    }
1968
                }
1969
                else
1970
                {
1971
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1972
                }
1973
            }
1974
            else
1975
            {
1976
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1977
            }
1978

    
1979
            if (_LMSymbol != null)
1980
            {
1981
                _LMSymbol.Commit();
1982
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1983
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1984
                ReleaseCOMObjects(_LMSymbol);
1985
            }
1986

    
1987
            if (targetItem != null)
1988
            {
1989
                ReleaseCOMObjects(targetItem);
1990
            }
1991

    
1992
            ReleaseCOMObjects(_LMSymbol);
1993
        }
1994

    
1995
        private void VendorPackageModeling(VendorPackage vendorPackage)
1996
        {
1997
            ETCSetting setting = ETCSetting.GetInstance();
1998
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
1999
            {
2000
                string symbolPath = setting.VendorPackageSymbolPath;
2001
                double x = vendorPackage.SPPID.ORIGINAL_X;
2002
                double y = vendorPackage.SPPID.ORIGINAL_Y;
2003

    
2004
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
2005
                if (symbol != null)
2006
                {
2007
                    symbol.Commit();
2008
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
2009
                }
2010

    
2011
                ReleaseCOMObjects(symbol);
2012
                symbol = null;
2013
            }
2014
        }
2015

    
2016
        /// <summary>
2017
        /// 첫 진입점
2018
        /// </summary>
2019
        /// <param name="symbol"></param>
2020
        private void SymbolModelingBySymbol(Symbol symbol)
2021
        {
2022
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
2023
            List<object> endObjects = new List<object>();
2024
            endObjects.Add(symbol);
2025

    
2026
            /// 심볼에 연결되어 있는 항목들을 모델링한다
2027
            foreach (var connector in symbol.CONNECTORS)
2028
            {
2029
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2030
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2031
                {
2032
                    endObjects.Add(connItem);
2033
                    if (connItem.GetType() == typeof(Symbol))
2034
                    {
2035
                        Symbol connSymbol = connItem as Symbol;
2036
                        if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2037
                        {
2038
                            SymbolModeling(connSymbol, symbol);
2039
                        }
2040
                        SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2041
                        SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2042
                    }
2043
                    else if (connItem.GetType() == typeof(Line))
2044
                    {
2045
                        Line connLine = connItem as Line;
2046
                        SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2047
                    }
2048
                }
2049
            }
2050
        }
2051

    
2052
        private void SymbolModelingByNeerSymbolLoop(Symbol symbol, List<object> endObjects)
2053
        {
2054
            foreach (var connector in symbol.CONNECTORS)
2055
            {
2056
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2057
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2058
                {
2059
                    if (!endObjects.Contains(connItem))
2060
                    {
2061
                        endObjects.Add(connItem);
2062
                        if (connItem.GetType() == typeof(Symbol))
2063
                        {
2064
                            Symbol connSymbol = connItem as Symbol;
2065
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2066
                            {
2067
                                SymbolModeling(connSymbol, symbol);
2068
                            }
2069
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2070
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2071
                        }
2072
                        else if (connItem.GetType() == typeof(Line))
2073
                        {
2074
                            Line connLine = connItem as Line;
2075
                            SymbolModelingByNeerLineLoop(connLine, endObjects, symbol);
2076
                        }
2077
                    }
2078
                }
2079
            }
2080
        }
2081

    
2082
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
2083
        {
2084
            foreach (var connector in line.CONNECTORS)
2085
            {
2086
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2087
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2088
                {
2089
                    if (!endObjects.Contains(connItem))
2090
                    {
2091
                        endObjects.Add(connItem);
2092
                        if (connItem.GetType() == typeof(Symbol))
2093
                        {
2094
                            Symbol connSymbol = connItem as Symbol;
2095
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2096
                            {
2097
                                Line connLine = SPPIDUtil.GetConnectedLine(prevSymbol, connSymbol);
2098
                                int branchCount = 0;
2099
                                if (connLine != null)
2100
                                    branchCount = SPPIDUtil.GetBranchLineCount(document, connLine);
2101

    
2102
                                List<Symbol> group = new List<Symbol>();
2103
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2104
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2105
                                List<Symbol> endModelingGroup = new List<Symbol>();
2106
                                if (priority != null)
2107
                                {
2108
                                    SymbolGroupModeling(priority, group);
2109

    
2110
                                    // Range 겹치는지 확인해야함
2111
                                    double[] prevRange = null;
2112
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2113
                                    double[] groupRange = null;
2114
                                    GetSPPIDSymbolRange(group, ref groupRange);
2115

    
2116
                                    double distanceX = 0;
2117
                                    double distanceY = 0;
2118
                                    bool overlapX = false;
2119
                                    bool overlapY = false;
2120
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2121
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2122
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2123
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2124
                                    {
2125
                                        RemoveSymbol(group);
2126
                                        foreach (var _temp in group)
2127
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
2128

    
2129
                                        SymbolGroupModeling(priority, group);
2130
                                    }
2131
                                    else if (branchCount > 0)
2132
                                    {
2133
                                        LMConnector _connector = JustLineModeling(connLine);
2134
                                        if (_connector != null)
2135
                                        {
2136
                                            double distance = GetConnectorDistance(_connector);
2137
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2138
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2139
                                            _connector.Commit();
2140
                                            ReleaseCOMObjects(_connector);
2141
                                            _connector = null;
2142
                                            if (cellCount < branchCount + 1)
2143
                                            {
2144
                                                int moveCount = branchCount - cellCount;
2145
                                                RemoveSymbol(group);
2146
                                                foreach (var _temp in group)
2147
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2148

    
2149
                                                SymbolGroupModeling(priority, group);
2150
                                            }
2151
                                        }
2152
                                    }
2153
                                }
2154
                                else
2155
                                {
2156
                                    SymbolModeling(connSymbol, null);
2157
                                    // Range 겹치는지 확인해야함
2158
                                    double[] prevRange = null;
2159
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2160
                                    double[] connRange = null;
2161
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
2162

    
2163
                                    double distanceX = 0;
2164
                                    double distanceY = 0;
2165
                                    bool overlapX = false;
2166
                                    bool overlapY = false;
2167
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2168
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2169
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2170
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2171
                                    {
2172
                                        RemoveSymbol(connSymbol);
2173
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
2174

    
2175
                                        SymbolModeling(connSymbol, null);
2176
                                    }
2177
                                    else if (branchCount > 0)
2178
                                    {
2179
                                        LMConnector _connector = JustLineModeling(connLine);
2180
                                        if (_connector != null)
2181
                                        {
2182
                                            double distance = GetConnectorDistance(_connector);
2183
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2184
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2185
                                            _connector.Commit();
2186
                                            ReleaseCOMObjects(_connector);
2187
                                            _connector = null;
2188
                                            if (cellCount < branchCount + 1)
2189
                                            {
2190
                                                int moveCount = branchCount - cellCount;
2191
                                                RemoveSymbol(group);
2192
                                                foreach (var _temp in group)
2193
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2194

    
2195
                                                SymbolGroupModeling(priority, group);
2196
                                            }
2197
                                        }
2198
                                    }
2199
                                }
2200
                            }
2201
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2202
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2203
                        }
2204
                        else if (connItem.GetType() == typeof(Line))
2205
                        {
2206
                            Line connLine = connItem as Line;
2207
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
2208
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
2209
                        }
2210
                    }
2211
                }
2212
            }
2213
        }
2214

    
2215
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
2216
        {
2217
            List<Symbol> endModelingGroup = new List<Symbol>();
2218
            SymbolModeling(firstSymbol, null);
2219
            endModelingGroup.Add(firstSymbol);
2220
            while (endModelingGroup.Count != group.Count)
2221
            {
2222
                foreach (var _symbol in group)
2223
                {
2224
                    if (!endModelingGroup.Contains(_symbol))
2225
                    {
2226
                        foreach (var _connector in _symbol.CONNECTORS)
2227
                        {
2228
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2229
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2230
                            {
2231
                                SymbolModeling(_symbol, _connSymbol);
2232
                                endModelingGroup.Add(_symbol);
2233
                                break;
2234
                            }
2235
                        }
2236
                    }
2237
                }
2238
            }
2239
        }
2240

    
2241
        /// <summary>
2242
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2243
        /// </summary>
2244
        /// <param name="childSymbol"></param>
2245
        /// <param name="parentSymbol"></param>
2246
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2247
        {
2248
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2249
            double x1 = 0;
2250
            double x2 = 0;
2251
            double y1 = 0;
2252
            double y2 = 0;
2253
            symbol2d.Range(out x1, out y1, out x2, out y2);
2254

    
2255
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2256
            if (_LMSymbol != null)
2257
            {
2258
                _LMSymbol.Commit();
2259
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2260
                foreach (var item in childSymbol.ChildSymbols)
2261
                    CreateChildSymbol(item, _LMSymbol, parent);
2262
            }
2263

    
2264

    
2265
            ReleaseCOMObjects(_LMSymbol);
2266
        }
2267
        double index = 0;
2268
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2269
        {
2270
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2271
                return;
2272

    
2273
            List<Line> group = new List<Line>();
2274
            GetConnectedLineGroup(line, group);
2275
            LineCoordinateCorrection(group);
2276

    
2277
            foreach (var groupLine in group)
2278
            {
2279
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2280
                {
2281
                    BranchLines.Add(groupLine);
2282
                    continue;
2283
                }
2284

    
2285
                bool diagonal = false;
2286
                if (groupLine.SlopeType != SlopeType.HORIZONTAL && groupLine.SlopeType != SlopeType.VERTICAL)
2287
                    diagonal = true;
2288
                _LMAItem _LMAItem = _placement.PIDCreateItem(groupLine.SPPID.MAPPINGNAME);
2289
                LMSymbol _LMSymbolStart = null;
2290
                LMSymbol _LMSymbolEnd = null;
2291
                PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2292
                foreach (var connector in groupLine.CONNECTORS)
2293
                {
2294
                    double x = 0;
2295
                    double y = 0;
2296
                    GetTargetLineConnectorPoint(connector, groupLine, ref x, ref y);
2297
                    if (connector.ConnectedObject == null)
2298
                    {
2299
                        placeRunInputs.AddPoint(x, y);
2300
                    }
2301
                    else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2302
                    {
2303
                        Symbol targetSymbol = connector.ConnectedObject as Symbol;
2304
                        GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == groupLine), targetSymbol, ref x, ref y);
2305
                        if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2306
                        {
2307
                            _LMSymbolStart = GetTargetSymbol(targetSymbol, groupLine);
2308
                            if (_LMSymbolStart != null)
2309
                                placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2310
                            else
2311
                                placeRunInputs.AddPoint(x, y);
2312
                        }
2313
                        else
2314
                        {
2315
                            _LMSymbolEnd = GetTargetSymbol(targetSymbol, groupLine);
2316
                            if (_LMSymbolEnd != null)
2317
                                placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2318
                            else
2319
                                placeRunInputs.AddPoint(x, y);
2320
                        }
2321
                    }
2322
                    else if (connector.ConnectedObject.GetType() == typeof(Line))
2323
                    {
2324
                        Line targetLine = connector.ConnectedObject as Line;
2325
                        if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2326
                        {
2327
                            LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2328
                            if (targetConnector != null)
2329
                            {
2330
                                placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2331
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2332
                            }
2333
                            else
2334
                            {
2335
                                placeRunInputs.AddPoint( x, y);
2336
                                ChangeLineSPPIDCoordinateByConnector(groupLine, targetLine, x, y, false);
2337
                            }
2338
                        }
2339
                        else
2340
                        {
2341
                            if (groupLine.CONNECTORS.IndexOf(connector) == 0)
2342
                            {
2343
                                index += 0.01;
2344
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2345
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2346
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2347
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2348
                                else
2349
                                {
2350
                                    Line nextLine = groupLine.CONNECTORS[0].ConnectedObject as Line;
2351
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2352
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2353
                                    else
2354
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2355
                                }
2356
                            }
2357

    
2358
                            placeRunInputs.AddPoint(x, y);
2359

    
2360
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2361
                            {
2362
                                index += 0.01;
2363
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2364
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2365
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2366
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2367
                                else
2368
                                {
2369
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2370
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2371
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2372
                                    else
2373
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2374
                                }
2375
                            }
2376
                        }
2377
                    }
2378
                }
2379

    
2380
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2381
                if (_lMConnector != null)
2382
                {
2383
                    _lMConnector.Commit();
2384
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2385

    
2386
                    bool bRemodelingStart = false;
2387
                    if (_LMSymbolStart != null)
2388
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2389
                    bool bRemodelingEnd = false;
2390
                    if (_LMSymbolEnd != null)
2391
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2392

    
2393
                    if (bRemodelingStart || bRemodelingEnd)
2394
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2395

    
2396
                    FlowMarkModeling(groupLine);
2397

    
2398
                    ReleaseCOMObjects(_lMConnector);
2399

    
2400
                    LMModelItem modelItem = dataSource.GetModelItem(groupLine.SPPID.ModelItemId);
2401
                    if (modelItem != null)
2402
                    {
2403
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2404
                        if (attribute != null)
2405
                            attribute.set_Value("End 1 is upstream (Inlet)");
2406
                        modelItem.Commit();
2407
                    }
2408
                    ReleaseCOMObjects(modelItem);
2409
                    modelItem = null;
2410
                }
2411
                else if (!isBranchModeling)
2412
                {
2413
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2414
                }
2415

    
2416
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2417
                x.ConnectedObject != null &&
2418
                x.ConnectedObject.GetType() == typeof(Line) &&
2419
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2420
                .Select(x => x.ConnectedObject)
2421
                .ToList();
2422

    
2423
                foreach (var item in removeLines)
2424
                    RemoveLineForModeling(item as Line);
2425

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

    
2435
                if (isBranchModeling && BranchLines.Contains(groupLine))
2436
                    BranchLines.Remove(groupLine);
2437
            }
2438
        }
2439

    
2440
        private LMConnector JustLineModeling(Line line)
2441
        {
2442
            bool diagonal = false;
2443
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2444
                diagonal = true;
2445
            _LMAItem _LMAItem = _placement.PIDCreateItem(line.SPPID.MAPPINGNAME);
2446
            LMSymbol _LMSymbolStart = null;
2447
            LMSymbol _LMSymbolEnd = null;
2448
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2449
            foreach (var connector in line.CONNECTORS)
2450
            {
2451
                double x = 0;
2452
                double y = 0;
2453
                GetTargetLineConnectorPoint(connector, line, ref x, ref y);
2454
                if (connector.ConnectedObject == null)
2455
                {
2456
                    placeRunInputs.AddPoint(x, y);
2457
                }
2458
                else if (connector.ConnectedObject.GetType() == typeof(Symbol))
2459
                {
2460
                    Symbol targetSymbol = connector.ConnectedObject as Symbol;
2461
                    GetTargetSymbolConnectorPoint(targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line), targetSymbol, ref x, ref y);
2462
                    if (line.CONNECTORS.IndexOf(connector) == 0)
2463
                    {
2464
                        _LMSymbolStart = GetTargetSymbol(targetSymbol, line);
2465
                        if (_LMSymbolStart != null)
2466
                            placeRunInputs.AddSymbolTarget(_LMSymbolStart, x, y, diagonal);
2467
                        else
2468
                            placeRunInputs.AddPoint(x, y);
2469
                    }
2470
                    else
2471
                    {
2472
                        _LMSymbolEnd = GetTargetSymbol(targetSymbol, line);
2473
                        if (_LMSymbolEnd != null)
2474
                            placeRunInputs.AddSymbolTarget(_LMSymbolEnd, x, y, diagonal);
2475
                        else
2476
                            placeRunInputs.AddPoint(x, y);
2477
                    }
2478
                }
2479
                else if (connector.ConnectedObject.GetType() == typeof(Line))
2480
                {
2481
                    Line targetLine = connector.ConnectedObject as Line;
2482
                    if (!string.IsNullOrEmpty(targetLine.SPPID.ModelItemId))
2483
                    {
2484
                        LMConnector targetConnector = FindTargetLMConnectorForBranch(line, targetLine, ref x, ref y);
2485
                        if (targetConnector != null)
2486
                        {
2487
                            placeRunInputs.AddConnectorTarget(targetConnector, x, y, diagonal);
2488
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2489
                        }
2490
                        else
2491
                        {
2492
                            placeRunInputs.AddPoint(x, y);
2493
                            ChangeLineSPPIDCoordinateByConnector(line, targetLine, x, y, false);
2494
                        }
2495
                    }
2496
                    else
2497
                        placeRunInputs.AddPoint(x, y);
2498
                }
2499
            }
2500

    
2501
            LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2502
            if (_lMConnector != null)
2503
                _lMConnector.Commit();
2504

    
2505
            ReleaseCOMObjects(_LMAItem);
2506
            _LMAItem = null;
2507
            ReleaseCOMObjects(placeRunInputs);
2508
            placeRunInputs = null;
2509
            ReleaseCOMObjects(_LMSymbolStart);
2510
            _LMSymbolStart = null;
2511
            ReleaseCOMObjects(_LMSymbolEnd);
2512
            _LMSymbolEnd = null;
2513

    
2514
            return _lMConnector;
2515
        }
2516

    
2517
        private void RemoveLineForModeling(Line line)
2518
        {
2519
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2520
            if (modelItem != null)
2521
            {
2522
                foreach (LMRepresentation rep in modelItem.Representations)
2523
                {
2524
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2525
                    {
2526
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
2527
                        dynamic OID = rep.get_GraphicOID().ToString();
2528
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2529
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2530
                        int verticesCount = lineStringGeometry.VertexCount;
2531
                        double[] vertices = null;
2532
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
2533
                        for (int i = 0; i < verticesCount; i++)
2534
                        {
2535
                            double x = 0;
2536
                            double y = 0;
2537
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
2538
                            if (verticesCount == 2 && (x < 0 || y < 0))
2539
                                _placement.PIDRemovePlacement(rep);
2540
                        }
2541
                        ReleaseCOMObjects(_LMConnector);
2542
                    }
2543
                }
2544

    
2545
                ReleaseCOMObjects(modelItem);
2546
            }
2547
        }
2548

    
2549
        private void RemoveLine(Line line)
2550
        {
2551
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2552
            if (modelItem != null)
2553
            {
2554
                foreach (LMRepresentation rep in modelItem.Representations)
2555
                {
2556
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2557
                        _placement.PIDRemovePlacement(rep);
2558
                }
2559
                ReleaseCOMObjects(modelItem);
2560
            }
2561
            line.SPPID.ModelItemId = null;
2562
        }
2563

    
2564
        private void GetConnectedLineGroup(Line line, List<Line> group)
2565
        {
2566
            if (!group.Contains(line))
2567
                group.Add(line);
2568
            foreach (var connector in line.CONNECTORS)
2569
            {
2570
                if (connector.ConnectedObject != null &&
2571
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2572
                    !group.Contains(connector.ConnectedObject) &&
2573
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2574
                {
2575
                    Line connLine = connector.ConnectedObject as Line;
2576
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2577
                    {
2578
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2579
                            group.Insert(0, connLine);
2580
                        else
2581
                            group.Add(connLine);
2582
                        GetConnectedLineGroup(connLine, group);
2583
                    }
2584
                }
2585
            }
2586
        }
2587

    
2588
        private void LineCoordinateCorrection(List<Line> group)
2589
        {
2590
            // 순서대로 전 Item 기준 정렬
2591
            LineCoordinateCorrectionByStart(group);
2592

    
2593
            // 역으로 심볼이 있을 경우 좌표 보정
2594
            LineCoordinateCorrectionForLastLine(group);
2595
        }
2596

    
2597
        private void LineCoordinateCorrectionByStart(List<Line> group)
2598
        {
2599
            for (int i = 0; i < group.Count; i++)
2600
            {
2601
                Line line = group[i];
2602
                if (i == 0)
2603
                {
2604
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2605
                    if (symbolConnector != null)
2606
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2607
                }
2608
                else if (i != 0)
2609
                {
2610
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2611
                }
2612
            }
2613
        }
2614

    
2615
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2616
        {
2617
            Line checkLine = group[group.Count - 1];
2618
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2619
            if (lastSymbolConnector != null)
2620
            {
2621
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2622
                for (int i = group.Count - 2; i >= 0; i--)
2623
                {
2624
                    Line line = group[i + 1];
2625
                    Line prevLine = group[i];
2626

    
2627
                    // 같으면 보정
2628
                    if (line.SlopeType == prevLine.SlopeType)
2629
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2630
                    else
2631
                    {
2632
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2633
                        {
2634
                            double prevX = 0;
2635
                            double prevY = 0;
2636
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2637
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2638

    
2639
                            double x = 0;
2640
                            double y = 0;
2641
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2642
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2643
                        }
2644
                        else if (line.SlopeType == SlopeType.VERTICAL)
2645
                        {
2646
                            double prevX = 0;
2647
                            double prevY = 0;
2648
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2649
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2650

    
2651
                            double x = 0;
2652
                            double y = 0;
2653
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2654
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2655
                        }
2656
                        break;
2657
                    }
2658
                }
2659
            }
2660
        }
2661

    
2662
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2663
        {
2664
            double x = 0;
2665
            double y = 0;
2666
            if (connItem.GetType() == typeof(Symbol))
2667
            {
2668
                Symbol targetSymbol = connItem as Symbol;
2669
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2670
                if (targetConnector != null)
2671
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2672
                else
2673
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2674
            }
2675
            else if (connItem.GetType() == typeof(Line))
2676
            {
2677
                Line targetLine = connItem as Line;
2678
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2679
            }
2680

    
2681
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2682
        }
2683

    
2684
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2685
        {
2686
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2687
            int index = line.CONNECTORS.IndexOf(connector);
2688
            if (index == 0)
2689
            {
2690
                line.SPPID.START_X = x;
2691
                line.SPPID.START_Y = y;
2692
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2693
                    line.SPPID.END_Y = y;
2694
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2695
                    line.SPPID.END_X = x;
2696
            }
2697
            else
2698
            {
2699
                line.SPPID.END_X = x;
2700
                line.SPPID.END_Y = y;
2701
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2702
                    line.SPPID.START_Y = y;
2703
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2704
                    line.SPPID.START_X = x;
2705
            }
2706
        }
2707

    
2708
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2709
        {
2710
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2711
            int index = line.CONNECTORS.IndexOf(connector);
2712
            if (index == 0)
2713
            {
2714
                line.SPPID.START_X = x;
2715
                if (line.SlopeType == SlopeType.VERTICAL)
2716
                    line.SPPID.END_X = x;
2717
            }
2718
            else
2719
            {
2720
                line.SPPID.END_X = x;
2721
                if (line.SlopeType == SlopeType.VERTICAL)
2722
                    line.SPPID.START_X = x;
2723
            }
2724
        }
2725

    
2726
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2727
        {
2728
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2729
            int index = line.CONNECTORS.IndexOf(connector);
2730
            if (index == 0)
2731
            {
2732
                line.SPPID.START_Y = y;
2733
                if (line.SlopeType == SlopeType.HORIZONTAL)
2734
                    line.SPPID.END_Y = y;
2735
            }
2736
            else
2737
            {
2738
                line.SPPID.END_Y = y;
2739
                if (line.SlopeType == SlopeType.HORIZONTAL)
2740
                    line.SPPID.START_Y = y;
2741
            }
2742
        }
2743

    
2744
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2745
        {
2746
            if (symbol != null)
2747
            {
2748
                string repID = symbol.AsLMRepresentation().Id;
2749
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2750
                string lineUID = line.UID;
2751

    
2752
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2753
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2754
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2755

    
2756
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2757
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2758
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2759

    
2760
                if (startSpecBreak != null || startEndBreak != null)
2761
                    result = true;
2762
            }
2763
        }
2764

    
2765
        /// <summary>
2766
        /// Symbol에 붙을 경우 Line을 Remodeling 한다.
2767
        /// </summary>
2768
        /// <param name="lines"></param>
2769
        /// <param name="prevLMConnector"></param>
2770
        /// <param name="startSymbol"></param>
2771
        /// <param name="endSymbol"></param>
2772
        private void ReModelingLine(Line line, LMConnector prevLMConnector, LMSymbol startSymbol, LMSymbol endSymbol, bool bStart, bool bEnd)
2773
        {
2774
            string symbolPath = string.Empty;
2775
            #region get symbol path
2776
            LMModelItem modelItem = dataSource.GetModelItem(prevLMConnector.ModelItemID);
2777
            symbolPath = GetSPPIDFileName(modelItem);
2778
            ReleaseCOMObjects(modelItem);
2779
            #endregion
2780
            bool diagonal = false;
2781
            if (line.SlopeType != SlopeType.HORIZONTAL && line.SlopeType != SlopeType.VERTICAL)
2782
                diagonal = true;
2783
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
2784
            LMConnector newConnector = null;
2785
            dynamic OID = prevLMConnector.get_GraphicOID().ToString();
2786
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
2787
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
2788
            int verticesCount = lineStringGeometry.VertexCount;
2789
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
2790

    
2791
            List<double[]> vertices = new List<double[]>();
2792
            for (int i = 1; i <= verticesCount; i++)
2793
            {
2794
                double x = 0;
2795
                double y = 0;
2796
                lineStringGeometry.GetVertex(i, ref x, ref y);
2797
                vertices.Add(new double[] { x, y });
2798
            }
2799

    
2800
            for (int i = 0; i < vertices.Count; i++)
2801
            {
2802
                double[] points = vertices[i];
2803
                // 시작 심볼이 있고 첫번째 좌표일 때
2804
                if (startSymbol != null && i == 0)
2805
                {
2806
                    if (bStart)
2807
                    {
2808
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2809
                        if (slopeType == SlopeType.HORIZONTAL)
2810
                            placeRunInputs.AddPoint(points[0], -0.1);
2811
                        else if (slopeType == SlopeType.VERTICAL)
2812
                            placeRunInputs.AddPoint(-0.1, points[1]);
2813
                        else
2814
                            placeRunInputs.AddPoint(points[0], -0.1);
2815

    
2816
                        placeRunInputs.AddPoint(points[0], points[1]);
2817
                    }
2818
                    else
2819
                    {
2820
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2821
                    }
2822
                }
2823
                // 마지막 심볼이 있고 마지막 좌표일 때
2824
                else if (endSymbol != null && i == vertices.Count - 1)
2825
                {
2826
                    if (bEnd)
2827
                    {
2828
                        placeRunInputs.AddPoint(points[0], points[1]);
2829

    
2830
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2831
                        if (slopeType == SlopeType.HORIZONTAL)
2832
                            placeRunInputs.AddPoint(points[0], -0.1);
2833
                        else if (slopeType == SlopeType.VERTICAL)
2834
                            placeRunInputs.AddPoint(-0.1, points[1]);
2835
                        else
2836
                            placeRunInputs.AddPoint(points[0], -0.1);
2837
                    }
2838
                    else
2839
                    {
2840
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2841
                    }
2842
                }
2843
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2844
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2845
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2846
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2847
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2848
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2849
                else
2850
                    placeRunInputs.AddPoint(points[0], points[1]);
2851
            }
2852

    
2853
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2854
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2855

    
2856
            ReleaseCOMObjects(placeRunInputs);
2857
            ReleaseCOMObjects(_LMAItem);
2858
            ReleaseCOMObjects(modelItem);
2859

    
2860
            if (newConnector != null)
2861
            {
2862
                newConnector.Commit();
2863
                if (startSymbol != null && bStart)
2864
                {
2865
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2866
                    placeRunInputs = new PlaceRunInputs();
2867
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2868
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2869
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2870
                    if (_LMConnector != null)
2871
                    {
2872
                        _LMConnector.Commit();
2873
                        RemoveConnectorForReModelingLine(newConnector);
2874
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2875
                        ReleaseCOMObjects(_LMConnector);
2876
                    }
2877
                    ReleaseCOMObjects(placeRunInputs);
2878
                    ReleaseCOMObjects(_LMAItem);
2879
                }
2880

    
2881
                if (endSymbol != null && bEnd)
2882
                {
2883
                    if (startSymbol != null)
2884
                    {
2885
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2886
                        newConnector = dicVertices.First().Key;
2887
                    }
2888

    
2889
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2890
                    placeRunInputs = new PlaceRunInputs();
2891
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2892
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2893
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2894
                    if (_LMConnector != null)
2895
                    {
2896
                        _LMConnector.Commit();
2897
                        RemoveConnectorForReModelingLine(newConnector);
2898
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2899
                        ReleaseCOMObjects(_LMConnector);
2900
                    }
2901
                    ReleaseCOMObjects(placeRunInputs);
2902
                    ReleaseCOMObjects(_LMAItem);
2903
                }
2904

    
2905
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2906
                ReleaseCOMObjects(newConnector);
2907
            }
2908

    
2909
            ReleaseCOMObjects(modelItem);
2910
        }
2911

    
2912
        /// <summary>
2913
        /// Remodeling 과정에서 생긴 불필요한 Connector 제거
2914
        /// </summary>
2915
        /// <param name="connector"></param>
2916
        private void RemoveConnectorForReModelingLine(LMConnector connector)
2917
        {
2918
            Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(connector.ModelItemID);
2919
            foreach (var item in dicVertices)
2920
            {
2921
                if (item.Value.Count == 2)
2922
                {
2923
                    bool result = false;
2924
                    foreach (var point in item.Value)
2925
                    {
2926
                        if (point[0] < 0 || point[1] < 0)
2927
                        {
2928
                            result = true;
2929
                            _placement.PIDRemovePlacement(item.Key.AsLMRepresentation());
2930
                            break;
2931
                        }
2932
                    }
2933

    
2934
                    if (result)
2935
                        break;
2936
                }
2937
            }
2938
            foreach (var item in dicVertices)
2939
                ReleaseCOMObjects(item.Key);
2940
        }
2941

    
2942
        /// <summary>
2943
        /// Symbol이 모델링된 SPPPID Symbol Object를 반환 - 연결된 Symbol이 ChildSymbol일 수도 있기때문에 메서드 개발
2944
        /// </summary>
2945
        /// <param name="symbol"></param>
2946
        /// <param name="line"></param>
2947
        /// <returns></returns>
2948
        private LMSymbol GetTargetSymbol(Symbol symbol, Line line)
2949
        {
2950
            LMSymbol _LMSymbol = null;
2951
            foreach (var connector in symbol.CONNECTORS)
2952
            {
2953
                if (connector.CONNECTEDITEM == line.UID)
2954
                {
2955
                    if (connector.Index == 0)
2956
                        _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
2957
                    else
2958
                    {
2959
                        ChildSymbol child = null;
2960
                        foreach (var childSymbol in symbol.ChildSymbols)
2961
                        {
2962
                            if (childSymbol.Connectors.Contains(connector))
2963
                                child = childSymbol;
2964
                            else
2965
                                child = GetChildSymbolByConnector(childSymbol, connector);
2966

    
2967
                            if (child != null)
2968
                                break;
2969
                        }
2970

    
2971
                        if (child != null)
2972
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2973
                    }
2974

    
2975
                    break;
2976
                }
2977
            }
2978

    
2979
            return _LMSymbol;
2980
        }
2981

    
2982
        /// <summary>
2983
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2984
        /// </summary>
2985
        /// <param name="item"></param>
2986
        /// <param name="connector"></param>
2987
        /// <returns></returns>
2988
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
2989
        {
2990
            foreach (var childSymbol in item.ChildSymbols)
2991
            {
2992
                if (childSymbol.Connectors.Contains(connector))
2993
                    return childSymbol;
2994
                else
2995
                    return GetChildSymbolByConnector(childSymbol, connector);
2996
            }
2997

    
2998
            return null;
2999
        }
3000

    
3001
        /// <summary>
3002
        /// EndBreak 모델링 메서드
3003
        /// </summary>
3004
        /// <param name="endBreak"></param>
3005
        private void EndBreakModeling(EndBreak endBreak)
3006
        {
3007
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
3008
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
3009

    
3010
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3011
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3012
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3013

    
3014
            if (targetLMConnector != null)
3015
            {
3016
                // LEADER Line 검사
3017
                bool leaderLine = false;
3018
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
3019
                if (symbolMapping != null)
3020
                    leaderLine = symbolMapping.LEADERLINE;
3021

    
3022
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector);
3023
                Array array = null;
3024
                if (point != null)
3025
                    array = new double[] { 0, point[0], point[1] };
3026
                else
3027
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
3028
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3029
                if (_LmLabelPersist != null)
3030
                {
3031
                    _LmLabelPersist.Commit();
3032
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3033
                    if (_LmLabelPersist.ModelItemObject != null)
3034
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3035
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3036
                    ReleaseCOMObjects(_LmLabelPersist);
3037
                }
3038
                ReleaseCOMObjects(targetLMConnector);
3039
            }
3040
            else
3041
            {
3042
                Log.Write("End Break UID : " + endBreak.UID);
3043
                Log.Write("Can't find targetLMConnector");
3044
            }
3045
        }
3046

    
3047
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
3048
        {
3049
            string symbolPath = string.Empty;
3050
            #region get symbol path
3051
            if (string.IsNullOrEmpty(changeSymbolPath))
3052
            {
3053
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
3054
                symbolPath = GetSPPIDFileName(modelItem);
3055
                ReleaseCOMObjects(modelItem);
3056
            }
3057
            else
3058
                symbolPath = changeSymbolPath;
3059
            
3060
            #endregion
3061

    
3062
            LMConnector newConnector = null;
3063
            dynamic OID = connector.get_GraphicOID().ToString();
3064
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3065
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3066
            int verticesCount = lineStringGeometry.VertexCount;
3067
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3068
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
3069

    
3070
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3071
            {
3072
                double[] vertices = null;
3073
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3074
                double x = 0;
3075
                double y = 0;
3076
                lineStringGeometry.GetVertex(1, ref x, ref y);
3077

    
3078
                string flowDirection = string.Empty;
3079
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3080
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3081
                    flowDirection = flowAttribute.get_Value().ToString();
3082

    
3083
                if (flowDirection == "End 1 is downstream (Outlet)")
3084
                {
3085
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3086
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3087
                    flowDirection = "End 1 is upstream (Inlet)";
3088
                }
3089
                else
3090
                {
3091
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3092
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3093
                }
3094
                string oldModelItemId = connector.ModelItemID;
3095
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3096
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3097
                newConnector.Commit();
3098
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3099
                if (!string.IsNullOrEmpty(flowDirection))
3100
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3101
                ReleaseCOMObjects(connector);
3102

    
3103
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3104
                {
3105
                    foreach (var repId in line.SPPID.Representations)
3106
                    {
3107
                        LMConnector _connector = dataSource.GetConnector(repId);
3108
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3109
                        {
3110
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3111
                            {
3112
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3113
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3114
                            }
3115
                        }
3116
                        ReleaseCOMObjects(_connector);
3117
                        _connector = null;
3118
                    }
3119
                }
3120
            }
3121

    
3122
            return newConnector;
3123
        }
3124

    
3125
        /// <summary>
3126
        /// SpecBreak Modeling 메서드
3127
        /// </summary>
3128
        /// <param name="specBreak"></param>
3129
        private void SpecBreakModeling(SpecBreak specBreak)
3130
        {
3131
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3132
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3133

    
3134
            if (upStreamObj != null &&
3135
                downStreamObj != null)
3136
            {
3137
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3138
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && 
3139
                    targetLMConnector != null && 
3140
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3141
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3142

    
3143
                if (targetLMConnector != null)
3144
                {
3145
                    foreach (var attribute in specBreak.ATTRIBUTES)
3146
                    {
3147
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3148
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3149
                        {
3150
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3151
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
3152
                            Array array = null;
3153
                            if (point != null)
3154
                                array = new double[] { 0, point[0], point[1] };
3155
                            else
3156
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3157
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3158

    
3159
                            if (_LmLabelPersist != null)
3160
                            {
3161
                                _LmLabelPersist.Commit();
3162
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3163
                                if (_LmLabelPersist.ModelItemObject != null)
3164
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3165
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3166
                                ReleaseCOMObjects(_LmLabelPersist);
3167
                            }
3168

    
3169
                            // temp
3170
                            ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3171
                        }
3172
                    }
3173
                    ReleaseCOMObjects(targetLMConnector);
3174
                }
3175
                else
3176
                {
3177
                    Log.Write("Spec Break UID : " + specBreak.UID);
3178
                    Log.Write("Can't find targetLMConnector");
3179
                }
3180
            }
3181
        }
3182

    
3183
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3184
        {
3185
            LMConnector targetConnector = null;
3186
            Symbol targetSymbol = targetObj as Symbol;
3187
            Symbol connectedSymbol = connectedObj as Symbol;
3188
            Line targetLine = targetObj as Line;
3189
            Line connectedLine = connectedObj as Line;
3190
            if (targetSymbol != null && connectedSymbol != null)
3191
            {
3192
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3193
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3194

    
3195
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3196
                {
3197
                    if (connector.get_ItemStatus() != "Active")
3198
                        continue;
3199

    
3200
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3201
                    {
3202
                        targetConnector = connector;
3203
                        break;
3204
                    }
3205
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3206
                    {
3207
                        targetConnector = connector;
3208
                        break;
3209
                    }
3210
                }
3211

    
3212
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3213
                {
3214
                    if (connector.get_ItemStatus() != "Active")
3215
                        continue;
3216

    
3217
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3218
                    {
3219
                        targetConnector = connector;
3220
                        break;
3221
                    }
3222
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3223
                    {
3224
                        targetConnector = connector;
3225
                        break;
3226
                    }
3227
                }
3228

    
3229
                ReleaseCOMObjects(targetLMSymbol);
3230
                ReleaseCOMObjects(connectedLMSymbol);
3231
            }
3232
            else if (targetLine != null && connectedLine != null)
3233
            {
3234
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3235
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3236

    
3237
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
3238
                {
3239
                    foreach (LMRepresentation rep in targetModelItem.Representations)
3240
                    {
3241
                        if (targetConnector != null)
3242
                            break;
3243

    
3244
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3245
                        {
3246
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3247

    
3248
                            if (IsConnected(_LMConnector, connectedModelItem))
3249
                                targetConnector = _LMConnector;
3250
                            else
3251
                                ReleaseCOMObjects(_LMConnector);
3252
                        }
3253
                    }
3254

    
3255
                    ReleaseCOMObjects(targetModelItem);
3256
                }
3257
            }
3258
            else
3259
            {
3260
                LMSymbol connectedLMSymbol = null;
3261
                if (connectedSymbol != null)
3262
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3263
                else if (targetSymbol != null)
3264
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3265
                else
3266
                {
3267

    
3268
                }
3269
                LMModelItem targetModelItem = null;
3270
                if (targetLine != null)
3271
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3272
                else if (connectedLine != null)
3273
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3274
                else
3275
                {
3276

    
3277
                }
3278
                if (connectedLMSymbol != null && targetModelItem != null)
3279
                {
3280
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
3281
                    {
3282
                        if (connector.get_ItemStatus() != "Active")
3283
                            continue;
3284

    
3285
                        if (IsConnected(connector, targetModelItem))
3286
                        {
3287
                            targetConnector = connector;
3288
                            break;
3289
                        }
3290
                    }
3291

    
3292
                    if (targetConnector == null)
3293
                    {
3294
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
3295
                        {
3296
                            if (connector.get_ItemStatus() != "Active")
3297
                                continue;
3298

    
3299
                            if (IsConnected(connector, targetModelItem))
3300
                            {
3301
                                targetConnector = connector;
3302
                                break;
3303
                            }
3304
                        }
3305
                    }
3306
                }
3307

    
3308
            }
3309

    
3310
            return targetConnector;
3311
        }
3312

    
3313
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
3314
        {
3315
            double[] result = null;
3316
            Line targetLine = targetObj as Line;
3317
            Symbol targetSymbol = targetObj as Symbol;
3318
            Line connLine = connObj as Line;
3319
            Symbol connSymbol = connObj as Symbol;
3320

    
3321
            double zeroLengthMove = GridSetting.GetInstance().Length * 3;
3322
            double lineMove = GridSetting.GetInstance().Length * 3;
3323
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
3324
            {
3325
                result = GetConnectorVertices(targetConnector)[0];
3326
                if (targetSymbol != null && connSymbol != null)
3327
                {
3328
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
3329
                    if (slopeType == SlopeType.HORIZONTAL)
3330
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3331
                    else if (slopeType == SlopeType.VERTICAL)
3332
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3333
                }
3334
                else if (targetLine != null)
3335
                {
3336
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3337
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3338
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
3339
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3340
                }
3341
                else if (connLine != null)
3342
                {
3343
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
3344
                        result = new double[] { result[0], result[1] - zeroLengthMove };
3345
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3346
                        result = new double[] { result[0] + zeroLengthMove, result[1] };
3347
                }
3348
            }
3349
            else
3350
            {
3351
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3352
                {
3353
                    Line line = connObj as Line;
3354
                    LMConnector connectedConnector = null;
3355
                    int connIndex = 0;
3356
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3357
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3358

    
3359
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3360

    
3361
                    ReleaseCOMObjects(modelItem);
3362
                    ReleaseCOMObjects(connectedConnector);
3363

    
3364
                    if (vertices.Count > 0)
3365
                    {
3366
                        if (connIndex == 1)
3367
                            result = vertices[0];
3368
                        else if (connIndex == 2)
3369
                            result = vertices[vertices.Count - 1];
3370

    
3371
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3372
                        {
3373
                            result = new double[] { result[0], result[1] - lineMove };
3374
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3375
                            {
3376
                                result = new double[] { result[0] - lineMove, result[1] };
3377
                            }
3378
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3379
                            {
3380
                                result = new double[] { result[0] + lineMove, result[1] };
3381
                            }
3382
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3383
                            {
3384
                                result = new double[] { result[0] + lineMove, result[1] };
3385
                            }
3386
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3387
                            {
3388
                                result = new double[] { result[0] - lineMove, result[1] };
3389
                            }
3390
                        }
3391
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3392
                        {
3393
                            result = new double[] { result[0] - lineMove, result[1] };
3394
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3395
                            {
3396
                                result = new double[] { result[0], result[1] - lineMove };
3397
                            }
3398
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3399
                            {
3400
                                result = new double[] { result[0], result[1] + lineMove };
3401
                            }
3402
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3403
                            {
3404
                                result = new double[] { result[0], result[1] + lineMove };
3405
                            }
3406
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3407
                            {
3408
                                result = new double[] { result[0], result[1] - lineMove };
3409
                            }
3410
                        }
3411
                            
3412
                    }
3413
                }
3414
                else
3415
                {
3416
                    Log.Write("error in GetSegemtPoint");
3417
                }
3418
            }
3419

    
3420
            return result;
3421
        }
3422

    
3423
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3424
        {
3425
            bool result = false;
3426

    
3427
            foreach (LMRepresentation rep in modelItem.Representations)
3428
            {
3429
                if (result)
3430
                    break;
3431

    
3432
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3433
                {
3434
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3435

    
3436
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3437
                        connector.ConnectItem1SymbolObject != null &&
3438
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3439
                    {
3440
                        result = true;
3441
                        ReleaseCOMObjects(_LMConnector);
3442
                        break;
3443
                    }
3444
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3445
                        connector.ConnectItem2SymbolObject != null &&
3446
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3447
                    {
3448
                        result = true;
3449
                        ReleaseCOMObjects(_LMConnector);
3450
                        break;
3451
                    }
3452
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3453
                        connector.ConnectItem1SymbolObject != null &&
3454
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3455
                    {
3456
                        result = true;
3457
                        ReleaseCOMObjects(_LMConnector);
3458
                        break;
3459
                    }
3460
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3461
                        connector.ConnectItem2SymbolObject != null &&
3462
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3463
                    {
3464
                        result = true;
3465
                        ReleaseCOMObjects(_LMConnector);
3466
                        break;
3467
                    }
3468

    
3469
                    ReleaseCOMObjects(_LMConnector);
3470
                }
3471
            }
3472

    
3473

    
3474
            return result;
3475
        }
3476

    
3477
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3478
        {
3479
            foreach (LMRepresentation rep in modelItem.Representations)
3480
            {
3481
                if (connectedConnector != null)
3482
                    break;
3483

    
3484
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3485
                {
3486
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3487

    
3488
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3489
                        connector.ConnectItem1SymbolObject != null &&
3490
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3491
                    {
3492
                        connectedConnector = _LMConnector;
3493
                        connectorIndex = 1;
3494
                        break;
3495
                    }
3496
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3497
                        connector.ConnectItem2SymbolObject != null &&
3498
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3499
                    {
3500
                        connectedConnector = _LMConnector;
3501
                        connectorIndex = 2;
3502
                        break;
3503
                    }
3504
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3505
                        connector.ConnectItem1SymbolObject != null &&
3506
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3507
                    {
3508
                        connectedConnector = _LMConnector;
3509
                        connectorIndex = 1;
3510
                        break;
3511
                    }
3512
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3513
                        connector.ConnectItem2SymbolObject != null &&
3514
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3515
                    {
3516
                        connectedConnector = _LMConnector;
3517
                        connectorIndex = 2;
3518
                        break;
3519
                    }
3520

    
3521
                    if (connectedConnector == null)
3522
                        ReleaseCOMObjects(_LMConnector);
3523
                }
3524
            }
3525
        }
3526

    
3527
        /// <summary>
3528
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
3529
        /// </summary>
3530
        /// <param name="modelItemID1"></param>
3531
        /// <param name="modelItemID2"></param>
3532
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
3533
        {
3534
            try
3535
            {
3536
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
3537
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
3538
                List<double[]> vertices1 = null;
3539
                string graphicOID1 = string.Empty;
3540
                if (connector1 != null)
3541
                {
3542
                    vertices1 = GetConnectorVertices(connector1);
3543
                    graphicOID1 = connector1.get_GraphicOID();
3544
                }
3545
                _LMAItem item1 = modelItem1.AsLMAItem();
3546
                ReleaseCOMObjects(connector1);
3547
                connector1 = null;
3548

    
3549
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3550
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
3551
                List<double[]> vertices2 = null;
3552
                string graphicOID2 = string.Empty;
3553
                if (connector2 != null)
3554
                {
3555
                    vertices2 = GetConnectorVertices(connector2);
3556
                    graphicOID2 = connector2.get_GraphicOID();
3557
                }
3558
                _LMAItem item2 = modelItem2.AsLMAItem();
3559
                ReleaseCOMObjects(connector2);
3560
                connector2 = null;
3561

    
3562
                // item2가 item1으로 조인
3563
                _placement.PIDJoinRuns(ref item1, ref item2);
3564
                item1.Commit();
3565
                item2.Commit();
3566

    
3567
                string beforeID = string.Empty;
3568
                string afterID = string.Empty;
3569

    
3570
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3571
                {
3572
                    beforeID = modelItem2.Id;
3573
                    afterID = modelItem1.Id;
3574
                    survivorId = afterID;
3575
                }
3576
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3577
                {
3578
                    beforeID = modelItem1.Id;
3579
                    afterID = modelItem2.Id;
3580
                    survivorId = afterID;
3581
                }
3582
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3583
                {
3584
                    int model1Cnt = GetConnectorCount(modelId1);
3585
                    int model2Cnt = GetConnectorCount(modelId2);
3586
                    if (model1Cnt == 0)
3587
                    {
3588
                        beforeID = modelItem1.Id;
3589
                        afterID = modelItem2.Id;
3590
                        survivorId = afterID;
3591
                    }
3592
                    else if (model2Cnt == 0)
3593
                    {
3594
                        beforeID = modelItem2.Id;
3595
                        afterID = modelItem1.Id;
3596
                        survivorId = afterID;
3597
                    }
3598
                    else
3599
                        survivorId = null;
3600
                }
3601
                else
3602
                {
3603
                    Log.Write("잘못된 경우");
3604
                    survivorId = null;
3605
                }
3606

    
3607
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3608
                {
3609
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3610
                    foreach (var line in lines)
3611
                        line.SPPID.ModelItemId = afterID;
3612
                }
3613

    
3614
                ReleaseCOMObjects(modelItem1);
3615
                ReleaseCOMObjects(item1);
3616
                ReleaseCOMObjects(modelItem2);
3617
                ReleaseCOMObjects(item2);
3618
            }
3619
            catch (Exception ex)
3620
            {
3621
                Log.Write("Join Error");
3622
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3623
            }
3624
        }
3625

    
3626
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
3627
        {
3628
            bool result = false;
3629
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
3630
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
3631
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
3632

    
3633
            foreach (var item in endBreaks)
3634
            {
3635
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
3636
                {
3637
                    result = true;
3638
                    break;
3639
                }
3640
            }
3641

    
3642
            return result;
3643
        }
3644
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3645
        {
3646
            List<string> temp = new List<string>();
3647
            List<LMConnector> connectors = new List<LMConnector>();
3648
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3649
            {
3650
                if (connector.get_ItemStatus() != "Active")
3651
                    continue;
3652

    
3653
                LMModelItem modelItem = connector.ModelItemObject;
3654
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3655
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3656
                    temp.Add(modelItem.Id);
3657

    
3658
                if (temp.Contains(modelItem.Id) &&
3659
                    connOtherSymbol != null &&
3660
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3661
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3662
                    temp.Remove(modelItem.Id);
3663

    
3664

    
3665
                if (temp.Contains(modelItem.Id))
3666
                    connectors.Add(connector);
3667
                ReleaseCOMObjects(connOtherSymbol);
3668
                connOtherSymbol = null;
3669
                ReleaseCOMObjects(modelItem);
3670
                modelItem = null;
3671
            }
3672

    
3673
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3674
            {
3675
                if (connector.get_ItemStatus() != "Active")
3676
                    continue;
3677

    
3678
                LMModelItem modelItem = connector.ModelItemObject;
3679
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3680
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3681
                    temp.Add(modelItem.Id);
3682

    
3683
                if (temp.Contains(modelItem.Id) &&
3684
                    connOtherSymbol != null &&
3685
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3686
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3687
                    temp.Remove(modelItem.Id);
3688

    
3689
                if (temp.Contains(modelItem.Id))
3690
                    connectors.Add(connector);
3691
                ReleaseCOMObjects(connOtherSymbol);
3692
                connOtherSymbol = null;
3693
                ReleaseCOMObjects(modelItem);
3694
                modelItem = null;
3695
            }
3696

    
3697

    
3698
            List<string> result = new List<string>();
3699
            string originalName = GetSPPIDFileName(modelId);
3700
            foreach (var connector in connectors)
3701
            {
3702
                string fileName = GetSPPIDFileName(connector.ModelItemID);
3703
                if (originalName == fileName)
3704
                    result.Add(connector.ModelItemID);
3705
                else
3706
                {
3707
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
3708
                        result.Add(connector.ModelItemID);
3709
                    else
3710
                    {
3711
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
3712
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
3713
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
3714
                            result.Add(connector.ModelItemID);
3715
                    }
3716
                }
3717
            }
3718

    
3719
            foreach (var connector in connectors)
3720
                ReleaseCOMObjects(connector);
3721
            
3722
            return result;
3723

    
3724

    
3725
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3726
            {
3727
                LMSymbol findResult = null;
3728
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3729
                    findResult = connector.ConnectItem1SymbolObject;
3730
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3731
                    findResult = connector.ConnectItem2SymbolObject;
3732

    
3733
                return findResult;
3734
            }
3735
        }
3736

    
3737
        /// <summary>
3738
        /// PipeRun의 좌표를 가져오는 메서드
3739
        /// </summary>
3740
        /// <param name="modelId"></param>
3741
        /// <returns></returns>
3742
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
3743
        {
3744
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
3745
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
3746

    
3747
            if (modelItem != null)
3748
            {
3749
                foreach (LMRepresentation rep in modelItem.Representations)
3750
                {
3751
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3752
                    {
3753
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3754
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
3755
                        {
3756
                            ReleaseCOMObjects(_LMConnector);
3757
                            _LMConnector = null;
3758
                            continue;
3759
                        }
3760
                        connectorVertices.Add(_LMConnector, new List<double[]>());
3761
                        dynamic OID = rep.get_GraphicOID().ToString();
3762
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3763
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3764
                        int verticesCount = lineStringGeometry.VertexCount;
3765
                        double[] vertices = null;
3766
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3767
                        for (int i = 0; i < verticesCount; i++)
3768
                        {
3769
                            double x = 0;
3770
                            double y = 0;
3771
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3772
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
3773
                        }
3774
                    }
3775
                }
3776

    
3777
                ReleaseCOMObjects(modelItem);
3778
            }
3779

    
3780
            return connectorVertices;
3781
        }
3782

    
3783
        private List<double[]> GetConnectorVertices(LMConnector connector)
3784
        {
3785
            List<double[]> vertices = new List<double[]>();
3786
            if (connector != null)
3787
            {
3788
                dynamic OID = connector.get_GraphicOID().ToString();
3789
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3790
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3791
                int verticesCount = lineStringGeometry.VertexCount;
3792
                double[] value = null;
3793
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3794
                for (int i = 0; i < verticesCount; i++)
3795
                {
3796
                    double x = 0;
3797
                    double y = 0;
3798
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3799
                    vertices.Add(new double[] { x, y });
3800
                }
3801
            }
3802
            return vertices;
3803
        }
3804

    
3805
        private double GetConnectorDistance(LMConnector connector)
3806
        {
3807
            double result = 0;
3808
            List<double[]> vertices = new List<double[]>();
3809
            if (connector != null)
3810
            {
3811
                dynamic OID = connector.get_GraphicOID().ToString();
3812
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3813
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3814
                int verticesCount = lineStringGeometry.VertexCount;
3815
                double[] value = null;
3816
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3817
                for (int i = 0; i < verticesCount; i++)
3818
                {
3819
                    double x = 0;
3820
                    double y = 0;
3821
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3822
                    vertices.Add(new double[] { x, y });
3823
                    if (vertices.Count > 1)
3824
                    {
3825
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
3826
                    }
3827
                }
3828
            }
3829
            return result;
3830
        }
3831
        private double[] GetConnectorRange(LMConnector connector)
3832
        {
3833
            double[] result = null;
3834
            List<double[]> vertices = new List<double[]>();
3835
            if (connector != null)
3836
            {
3837
                dynamic OID = connector.get_GraphicOID().ToString();
3838
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3839
                double minX = 0;
3840
                double minY = 0;
3841
                double maxX = 0;
3842
                double maxY = 0;
3843

    
3844
                drawingObject.Range(out minX, out minY, out maxX, out maxY);
3845
                result = new double[] { minX, minY, maxX, maxY };
3846
            }
3847
            return result;
3848
        }
3849
        private List<double[]> GetConnectorVertices(dynamic graphicOID)
3850
        {
3851
            List<double[]> vertices = null;
3852
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID];
3853
            if (drawingObject != null)
3854
            {
3855
                vertices = new List<double[]>();
3856
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3857
                int verticesCount = lineStringGeometry.VertexCount;
3858
                double[] value = null;
3859
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3860
                for (int i = 0; i < verticesCount; i++)
3861
                {
3862
                    double x = 0;
3863
                    double y = 0;
3864
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3865
                    vertices.Add(new double[] { x, y });
3866
                }
3867
            }
3868
            return vertices;
3869
        }
3870
        /// <summary>
3871
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
3872
        /// </summary>
3873
        /// <param name="connectorVertices"></param>
3874
        /// <param name="connX"></param>
3875
        /// <param name="connY"></param>
3876
        /// <returns></returns>
3877
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
3878
        {
3879
            double length = double.MaxValue;
3880
            LMConnector targetConnector = null;
3881
            foreach (var item in connectorVertices)
3882
            {
3883
                List<double[]> points = item.Value;
3884
                for (int i = 0; i < points.Count - 1; i++)
3885
                {
3886
                    double[] point1 = points[i];
3887
                    double[] point2 = points[i + 1];
3888
                    double x1 = Math.Min(point1[0], point2[0]);
3889
                    double y1 = Math.Min(point1[1], point2[1]);
3890
                    double x2 = Math.Max(point1[0], point2[0]);
3891
                    double y2 = Math.Max(point1[1], point2[1]);
3892

    
3893
                    if ((x1 <= connX && x2 >= connX) ||
3894
                        (y1 <= connY && y2 >= connY))
3895
                    {
3896
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3897
                        if (length >= distance)
3898
                        {
3899
                            targetConnector = item.Key;
3900
                            length = distance;
3901
                        }
3902

    
3903
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3904
                        if (length >= distance)
3905
                        {
3906
                            targetConnector = item.Key;
3907
                            length = distance;
3908
                        }
3909
                    }
3910
                }
3911
            }
3912

    
3913
            // 못찾았을때.
3914
            length = double.MaxValue;
3915
            if (targetConnector == null)
3916
            {
3917
                foreach (var item in connectorVertices)
3918
                {
3919
                    List<double[]> points = item.Value;
3920

    
3921
                    foreach (double[] point in points)
3922
                    {
3923
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3924
                        if (length >= distance)
3925
                        {
3926
                            targetConnector = item.Key;
3927
                            length = distance;
3928
                        }
3929
                    }
3930
                }
3931
            }
3932

    
3933
            return targetConnector;
3934
        }
3935

    
3936
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3937
        {
3938
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3939
            if (vertices.Count == 0)
3940
                return null;
3941

    
3942
            double length = double.MaxValue;
3943
            LMConnector targetConnector = null;
3944
            double[] resultPoint = null;
3945
            List<double[]> targetVertices = null;
3946

    
3947
            // Vertices 포인트에 제일 가까운곳
3948
            foreach (var item in vertices)
3949
            {
3950
                List<double[]> points = item.Value;
3951
                for (int i = 0; i < points.Count; i++)
3952
                {
3953
                    double[] point = points[i];
3954
                    double tempX = point[0];
3955
                    double tempY = point[1];
3956

    
3957
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3958
                    if (length >= distance)
3959
                    {
3960
                        targetConnector = item.Key;
3961
                        length = distance;
3962
                        resultPoint = point;
3963
                        targetVertices = item.Value;
3964
                    }
3965
                }
3966
            }
3967

    
3968
            // Vertices Cross에 제일 가까운곳
3969
            foreach (var item in vertices)
3970
            {
3971
                List<double[]> points = item.Value;
3972
                for (int i = 0; i < points.Count - 1; i++)
3973
                {
3974
                    double[] point1 = points[i];
3975
                    double[] point2 = points[i + 1];
3976

    
3977
                    double maxLineX = Math.Max(point1[0], point2[0]);
3978
                    double minLineX = Math.Min(point1[0], point2[0]);
3979
                    double maxLineY = Math.Max(point1[1], point2[1]);
3980
                    double minLineY = Math.Min(point1[1], point2[1]);
3981

    
3982
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3983

    
3984
                    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]);
3985
                    if (crossingPoint != null)
3986
                    {
3987
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
3988
                        if (length >= distance)
3989
                        {
3990
                            if (slope == SlopeType.Slope &&
3991
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
3992
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
3993
                            {
3994
                                targetConnector = item.Key;
3995
                                length = distance;
3996
                                resultPoint = crossingPoint;
3997
                                targetVertices = item.Value;
3998
                            }
3999
                            else if (slope == SlopeType.HORIZONTAL &&
4000
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
4001
                            {
4002
                                targetConnector = item.Key;
4003
                                length = distance;
4004
                                resultPoint = crossingPoint;
4005
                                targetVertices = item.Value;
4006
                            }
4007
                            else if (slope == SlopeType.VERTICAL &&
4008
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4009
                            {
4010
                                targetConnector = item.Key;
4011
                                length = distance;
4012
                                resultPoint = crossingPoint;
4013
                                targetVertices = item.Value;
4014
                            }
4015
                        }
4016
                    }
4017
                }
4018
            }
4019

    
4020
            foreach (var item in vertices)
4021
                if (item.Key != null && item.Key != targetConnector)
4022
                    ReleaseCOMObjects(item.Key);
4023

    
4024
            if (SPPIDUtil.IsBranchLine(line, targetLine))
4025
            {
4026
                double tempResultX = resultPoint[0];
4027
                double tempResultY = resultPoint[1];
4028
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4029

    
4030
                GridSetting gridSetting = GridSetting.GetInstance();
4031

    
4032
                for (int i = 0; i < targetVertices.Count; i++)
4033
                {
4034
                    double[] point = targetVertices[i];
4035
                    double tempX = targetVertices[i][0];
4036
                    double tempY = targetVertices[i][1];
4037
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
4038
                    if (tempX == tempResultX && tempY == tempResultY)
4039
                    {
4040
                        if (i == 0)
4041
                        {
4042
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
4043
                            bool containZeroLength = false;
4044
                            if (connSymbol != null)
4045
                            {
4046
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4047
                                {
4048
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4049
                                        containZeroLength = true;
4050
                                }
4051
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4052
                                {
4053
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4054
                                        containZeroLength = true;
4055
                                }
4056
                            }
4057

    
4058
                            if (connSymbol == null ||
4059
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4060
                                containZeroLength)
4061
                            {
4062
                                bool bCalcX = false;
4063
                                bool bCalcY = false;
4064
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4065
                                    bCalcX = true;
4066
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4067
                                    bCalcY = true;
4068
                                else
4069
                                {
4070
                                    bCalcX = true;
4071
                                    bCalcY = true;
4072
                                }
4073

    
4074
                                if (bCalcX)
4075
                                {
4076
                                    double nextX = targetVertices[i + 1][0];
4077
                                    double newX = 0;
4078
                                    if (nextX > tempX)
4079
                                    {
4080
                                        newX = tempX + gridSetting.Length;
4081
                                        if (newX > nextX)
4082
                                            newX = (point[0] + nextX) / 2;
4083
                                    }
4084
                                    else
4085
                                    {
4086
                                        newX = tempX - gridSetting.Length;
4087
                                        if (newX < nextX)
4088
                                            newX = (point[0] + nextX) / 2;
4089
                                    }
4090
                                    resultPoint = new double[] { newX, resultPoint[1] };
4091
                                }
4092

    
4093
                                if (bCalcY)
4094
                                {
4095
                                    double nextY = targetVertices[i + 1][1];
4096
                                    double newY = 0;
4097
                                    if (nextY > tempY)
4098
                                    {
4099
                                        newY = tempY + gridSetting.Length;
4100
                                        if (newY > nextY)
4101
                                            newY = (point[1] + nextY) / 2;
4102
                                    }
4103
                                    else
4104
                                    {
4105
                                        newY = tempY - gridSetting.Length;
4106
                                        if (newY < nextY)
4107
                                            newY = (point[1] + nextY) / 2;
4108
                                    }
4109
                                    resultPoint = new double[] { resultPoint[0], newY };
4110
                                }
4111
                            }
4112
                        }
4113
                        else if (i == targetVertices.Count - 1)
4114
                        {
4115
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4116
                            bool containZeroLength = false;
4117
                            if (connSymbol != null)
4118
                            {
4119
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4120
                                {
4121
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4122
                                        containZeroLength = true;
4123
                                }
4124
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4125
                                {
4126
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4127
                                        containZeroLength = true;
4128
                                }
4129
                            }
4130

    
4131
                            if (connSymbol == null ||
4132
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4133
                                containZeroLength)
4134
                            {
4135
                                bool bCalcX = false;
4136
                                bool bCalcY = false;
4137
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4138
                                    bCalcX = true;
4139
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4140
                                    bCalcY = true;
4141
                                else
4142
                                {
4143
                                    bCalcX = true;
4144
                                    bCalcY = true;
4145
                                }
4146

    
4147
                                if (bCalcX)
4148
                                {
4149
                                    double nextX = targetVertices[i - 1][0];
4150
                                    double newX = 0;
4151
                                    if (nextX > tempX)
4152
                                    {
4153
                                        newX = tempX + gridSetting.Length;
4154
                                        if (newX > nextX)
4155
                                            newX = (point[0] + nextX) / 2;
4156
                                    }
4157
                                    else
4158
                                    {
4159
                                        newX = tempX - gridSetting.Length;
4160
                                        if (newX < nextX)
4161
                                            newX = (point[0] + nextX) / 2;
4162
                                    }
4163
                                    resultPoint = new double[] { newX, resultPoint[1] };
4164
                                }
4165

    
4166
                                if (bCalcY)
4167
                                {
4168
                                    double nextY = targetVertices[i - 1][1];
4169
                                    double newY = 0;
4170
                                    if (nextY > tempY)
4171
                                    {
4172
                                        newY = tempY + gridSetting.Length;
4173
                                        if (newY > nextY)
4174
                                            newY = (point[1] + nextY) / 2;
4175
                                    }
4176
                                    else
4177
                                    {
4178
                                        newY = tempY - gridSetting.Length;
4179
                                        if (newY < nextY)
4180
                                            newY = (point[1] + nextY) / 2;
4181
                                    }
4182
                                    resultPoint = new double[] { resultPoint[0], newY };
4183
                                }
4184
                            }
4185
                        }
4186
                        break;
4187
                    }
4188
                }
4189
            }
4190

    
4191
            x = resultPoint[0];
4192
            y = resultPoint[1];
4193

    
4194
            return targetConnector;
4195
        }
4196

    
4197
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
4198
        {
4199
            LMConnector result = null;
4200
            List<LMConnector> connectors = new List<LMConnector>();
4201
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4202

    
4203
            if (modelItem != null)
4204
            {
4205
                foreach (LMRepresentation rep in modelItem.Representations)
4206
                {
4207
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4208
                        connectors.Add(dataSource.GetConnector(rep.Id));
4209
                }
4210

    
4211
                ReleaseCOMObjects(modelItem);
4212
            }
4213

    
4214
            if (connectors.Count == 1)
4215
                result = connectors[0];
4216
            else
4217
                foreach (var item in connectors)
4218
                    ReleaseCOMObjects(item);
4219

    
4220
            return result;
4221
        }
4222

    
4223
        private LMConnector GetLMConnectorFirst(string modelItemID)
4224
        {
4225
            LMConnector result = null;
4226
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4227

    
4228
            if (modelItem != null)
4229
            {
4230
                foreach (LMRepresentation rep in modelItem.Representations)
4231
                {
4232
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && 
4233
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
4234
                    {
4235
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4236
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
4237
                        {
4238
                            result = connector;
4239
                            break;
4240
                        }
4241
                        else
4242
                        {
4243
                            ReleaseCOMObjects(connector);
4244
                            connector = null;
4245
                        }
4246
                    }
4247
                }
4248
                ReleaseCOMObjects(modelItem);
4249
                modelItem = null;
4250
            }
4251

    
4252
            return result;
4253
        }
4254

    
4255
        private int GetConnectorCount(string modelItemID)
4256
        {
4257
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4258
            int result = 0;
4259
            if (modelItem != null)
4260
            {
4261
                foreach (LMRepresentation rep in modelItem.Representations)
4262
                {
4263
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4264
                        result++;
4265
                    ReleaseCOMObjects(rep);
4266
                }
4267
                ReleaseCOMObjects(modelItem);
4268
            }
4269

    
4270
            return result;
4271
        }
4272

    
4273
        public List<string> GetRepresentations(string modelItemID)
4274
        {
4275
            List<string> result = new List<string>(); ;
4276
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4277
            if (modelItem != null)
4278
            {
4279
                foreach (LMRepresentation rep in modelItem.Representations)
4280
                {
4281
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4282
                        result.Add(rep.Id);
4283
                }
4284
                ReleaseCOMObjects(modelItem);
4285
            }
4286

    
4287
            return result;
4288
        }
4289

    
4290
        private void LineNumberModeling(LineNumber lineNumber)
4291
        {
4292
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4293
            if (line != null)
4294
            {
4295
                double x = 0;
4296
                double y = 0;
4297
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4298

    
4299
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4300
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
4301
                if (connectedLMConnector != null)
4302
                {
4303
                    Array points = new double[] { 0, x, y };
4304
                    lineNumber.SPPID.SPPID_X = x;
4305
                    lineNumber.SPPID.SPPID_Y = y;
4306
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4307

    
4308
                    if (_LmLabelPresist != null)
4309
                    {
4310
                        _LmLabelPresist.Commit();
4311
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4312
                        ReleaseCOMObjects(_LmLabelPresist);
4313
                    }
4314
                }
4315

    
4316
                foreach (var item in connectorVertices)
4317
                    ReleaseCOMObjects(item.Key);
4318
            }
4319
        }
4320
        private void LineNumberCorrectModeling(LineNumber lineNumber)
4321
        {
4322
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4323
            if (line == null || line.SPPID.Vertices == null)
4324
                return;
4325

    
4326
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
4327
            {
4328
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
4329
                if (removeLabel != null)
4330
                {
4331
                    lineNumber.SPPID.SPPID_X = removeLabel.get_XCoordinate();
4332
                    lineNumber.SPPID.SPPID_Y = removeLabel.get_YCoordinate();
4333

    
4334
                    GridSetting gridSetting = GridSetting.GetInstance();
4335
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4336

    
4337
                    double[] labelRange = null;
4338
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
4339
                    List<double[]> vertices = GetConnectorVertices(connector);
4340

    
4341
                    double[] resultStart = null;
4342
                    double[] resultEnd = null;
4343
                    double distance = double.MaxValue;
4344
                    for (int i = 0; i < vertices.Count - 1; i++)
4345
                    {
4346
                        double[] startPoint = vertices[i];
4347
                        double[] endPoint = vertices[i + 1];
4348
                        foreach (var item in line.SPPID.Vertices)
4349
                        {
4350
                            double[] lineStartPoint = item[0];
4351
                            double[] lineEndPoint = item[item.Count - 1];
4352

    
4353
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
4354
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
4355
                            if (tempDistance < distance)
4356
                            {
4357
                                distance = tempDistance;
4358
                                resultStart = startPoint;
4359
                                resultEnd = endPoint;
4360
                            }
4361
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
4362
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
4363
                            if (tempDistance < distance)
4364
                            {
4365
                                distance = tempDistance;
4366
                                resultStart = startPoint;
4367
                                resultEnd = endPoint;
4368
                            }
4369
                        }
4370
                    }
4371

    
4372
                    if (resultStart != null && resultEnd != null)
4373
                    {
4374
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
4375
                        double lineStartX = 0;
4376
                        double lineStartY = 0;
4377
                        double lineEndX = 0;
4378
                        double lineEndY = 0;
4379
                        double lineNumberX = 0;
4380
                        double lineNumberY = 0;
4381
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
4382
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
4383

    
4384
                        double lineX = (lineStartX + lineEndX) / 2;
4385
                        double lineY = (lineStartY + lineEndY) / 2;
4386
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
4387
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
4388

    
4389
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4390
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4391
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4392
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4393

    
4394
                        double offsetX = 0;
4395
                        double offsetY = 0;
4396
                        if (slope == SlopeType.HORIZONTAL)
4397
                        {
4398
                            // Line Number 아래
4399
                            if (lineY < lineNumberY)
4400
                            {
4401
                                offsetX = labelCenterX - SPPIDCenterX;
4402
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
4403
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4404
                            }
4405
                            // Line Number 위
4406
                            else
4407
                            {
4408
                                offsetX = labelCenterX - SPPIDCenterX;
4409
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
4410
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4411
                            }
4412
                        }
4413
                        else if (slope == SlopeType.VERTICAL)
4414
                        {
4415
                            // Line Number 오르쪽
4416
                            if (lineX < lineNumberX)
4417
                            {
4418
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
4419
                                offsetY = labelCenterY - SPPIDCenterY;
4420
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4421
                            }
4422
                            // Line Number 왼쪽
4423
                            else
4424
                            {
4425
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
4426
                                offsetY = labelCenterY - SPPIDCenterY;
4427
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4428
                            }
4429
                        }
4430

    
4431
                        if (offsetY != 0 || offsetY != 0)
4432
                        {
4433
                            if (connector.ConnectItem1SymbolObject != null &&
4434
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
4435
                            {
4436
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
4437

    
4438
                                double x1, y1, x2, y2, originX, originY;
4439
                                symbol.Range(out x1, out y1, out x2, out y2);
4440
                                symbol.GetOrigin(out originX, out originY);
4441
                                if (originX < lineNumber.SPPID.SPPID_X)
4442
                                    lineNumber.SPPID.SPPID_X = originX + gridSetting.Length * 35;
4443
                                else
4444
                                    lineNumber.SPPID.SPPID_X = originX - gridSetting.Length * 35;
4445
                            }
4446
                            else if (connector.ConnectItem2SymbolObject != null &&
4447
                                    connector.ConnectItem2SymbolObject.get_RepresentationType() == "OPC")
4448
                            {
4449
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem2SymbolObject.get_GraphicOID().ToString()];
4450

    
4451
                                double x1, y1, x2, y2, originX, originY;
4452
                                symbol.Range(out x1, out y1, out x2, out y2);
4453
                                symbol.GetOrigin(out originX, out originY);
4454
                                if (originX < lineNumber.SPPID.SPPID_X)
4455
                                    lineNumber.SPPID.SPPID_X = originX + gridSetting.Length * 35;
4456
                                else
4457
                                    lineNumber.SPPID.SPPID_X = originX - gridSetting.Length * 35;
4458
                            }
4459

    
4460
                            radApp.ActiveSelectSet.RemoveAll();
4461
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[removeLabel.get_GraphicOID().ToString()] as DependencyObject;
4462
                            if (dependency != null)
4463
                            {
4464
                                radApp.ActiveSelectSet.Add(dependency);
4465
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
4466
                                transform.DefineByMove2d(-offsetX, -offsetY);
4467
                                radApp.ActiveSelectSet.Transform(transform, true);
4468
                                radApp.ActiveSelectSet.RemoveAll();
4469
                            }
4470
                        }
4471

    
4472
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4473
                        {
4474
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4475
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4476
                        }
4477
                    }
4478

    
4479

    
4480
                    ReleaseCOMObjects(connector);
4481
                    connector = null;
4482
                }
4483

    
4484
                ReleaseCOMObjects(removeLabel);
4485
                removeLabel = null;
4486
            }
4487
        }
4488
        /// <summary>
4489
        /// Flow Mark Modeling
4490
        /// </summary>
4491
        /// <param name="line"></param>
4492
        private void FlowMarkModeling(Line line)
4493
        {
4494
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
4495
            {
4496
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
4497
                if (connector != null)
4498
                {
4499
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
4500
                    List<double[]> vertices = GetConnectorVertices(connector);
4501
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
4502
                    double[] point = vertices[vertices.Count - 1];
4503
                    Array array = new double[] { 0, point[0], point[1] };
4504
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
4505
                    if (_LMLabelPersist != null)
4506
                    {
4507
                        _LMLabelPersist.Commit();
4508
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
4509
                        ReleaseCOMObjects(_LMLabelPersist);
4510
                    }
4511
                }
4512
            }
4513
        }
4514

    
4515
        /// <summary>
4516
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
4517
        /// </summary>
4518
        /// <param name="lineNumber"></param>
4519
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
4520
        {
4521
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
4522
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
4523
            {
4524
                if (a.ATTRIBUTE == "Tag Seq No")
4525
                    return 1;
4526
                else if (b.ATTRIBUTE == "Tag Seq No")
4527
                    return -1;
4528

    
4529
                return 0;
4530
            }
4531

    
4532
            foreach (LineRun run in lineNumber.RUNS)
4533
            {
4534
                foreach (var item in run.RUNITEMS)
4535
                {
4536
                    if (item.GetType() == typeof(Symbol))
4537
                    {
4538
                        Symbol symbol = item as Symbol;
4539
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4540
                        if (_LMSymbol != null)
4541
                        {
4542
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4543

    
4544
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4545
                            {
4546
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4547
                                {
4548
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4549
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4550
                                    {
4551
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4552
                                        if (_LMAAttribute != null)
4553
                                        {
4554
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4555
                                                _LMAAttribute.set_Value(attribute.VALUE);
4556
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4557
                                                _LMAAttribute.set_Value(attribute.VALUE);
4558
                                        }
4559
                                    }
4560
                                }
4561
                                _LMModelItem.Commit();
4562
                            }
4563
                            if (_LMModelItem != null)
4564
                                ReleaseCOMObjects(_LMModelItem);
4565
                        }
4566
                        if (_LMSymbol != null)
4567
                            ReleaseCOMObjects(_LMSymbol);
4568
                    }
4569
                    else if (item.GetType() == typeof(Line))
4570
                    {
4571
                        Line line = item as Line;
4572
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
4573
                        {
4574
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4575
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4576
                            {
4577
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4578
                                {
4579
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4580
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4581
                                    {
4582
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4583
                                        if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(attribute.VALUE))
4584
                                        {
4585
                                            LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
4586
                                            if (_FluidSystemAttribute != null)
4587
                                            {
4588
                                                DataTable dt = SPPID_DB.GetFluidSystemInfo(attribute.VALUE);
4589
                                                if (dt.Rows.Count == 1)
4590
                                                {
4591
                                                    string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
4592
                                                    if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
4593
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
4594
                                                    else if (_FluidSystemAttribute.get_Value() != fluidSystem)
4595
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
4596

    
4597
                                                    if (_LMAAttribute != null)
4598
                                                    {
4599
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4600
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4601
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
4602
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4603
                                                    }
4604
                                                }
4605
                                                if (dt != null)
4606
                                                    dt.Dispose();
4607
                                            }
4608
                                        }
4609
                                        else if (_LMAAttribute != null)
4610
                                        {
4611
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4612
                                                _LMAAttribute.set_Value(attribute.VALUE);
4613
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4614
                                                _LMAAttribute.set_Value(attribute.VALUE);
4615
                                        }
4616
                                    }
4617
                                }
4618
                                _LMModelItem.Commit();
4619
                            }
4620
                            if (_LMModelItem != null)
4621
                                ReleaseCOMObjects(_LMModelItem);
4622
                            endLine.Add(line.SPPID.ModelItemId);
4623
                        }
4624
                    }
4625
                }
4626
            }
4627
        }
4628

    
4629
        /// <summary>
4630
        /// Symbol Attribute 입력 메서드
4631
        /// </summary>
4632
        /// <param name="item"></param>
4633
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
4634
        {
4635
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
4636
            string sRep = null;
4637
            if (targetItem.GetType() == typeof(Symbol))
4638
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
4639
            else if (targetItem.GetType() == typeof(Equipment))
4640
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
4641

    
4642
            if (!string.IsNullOrEmpty(sRep))
4643
            {
4644
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
4645
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4646
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4647
                
4648
                foreach (var item in targetAttributes)
4649
                {
4650
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4651
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4652
                    {
4653
                        if (!mapping.IsText)
4654
                        {
4655
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4656
                            if (_Attribute != null)
4657
                            {
4658
                                _Attribute.set_Value(item.VALUE);
4659
                                // OPC 일경우 Attribute 저장
4660
                                if (targetItem.GetType() == typeof(Symbol))
4661
                                {
4662
                                    Symbol symbol = targetItem as Symbol;
4663
                                    if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
4664
                                        symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
4665
                                }
4666
                            }
4667
                        }
4668
                        else
4669
                            DefaultTextModeling(item.VALUE, _LMSymbol.get_XCoordinate(), _LMSymbol.get_YCoordinate());
4670
                    }
4671
                }
4672
                _LMModelItem.Commit();
4673

    
4674
                ReleaseCOMObjects(_Attributes);
4675
                ReleaseCOMObjects(_LMModelItem);
4676
                ReleaseCOMObjects(_LMSymbol);
4677
            }
4678
        }
4679

    
4680
        /// <summary>
4681
        /// Input SpecBreak Attribute
4682
        /// </summary>
4683
        /// <param name="specBreak"></param>
4684
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4685
        {
4686
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4687
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4688

    
4689
            if (upStreamObj != null &&
4690
                downStreamObj != null)
4691
            {
4692
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4693

    
4694
                if (targetLMConnector != null)
4695
                {
4696
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4697
                    {
4698
                        string symbolPath = _LMLabelPersist.get_FileName();
4699
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4700
                        if (mapping != null)
4701
                        {
4702
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4703
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4704
                            {
4705
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4706
                                if (values.Length == 2)
4707
                                {
4708
                                    string upStreamValue = values[0];
4709
                                    string downStreamValue = values[1];
4710

    
4711
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4712
                                }
4713
                            }
4714
                        }
4715
                    }
4716

    
4717
                    ReleaseCOMObjects(targetLMConnector);
4718
                }
4719
            }
4720

    
4721

    
4722
            #region 내부에서만 쓰는 메서드
4723
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4724
            {
4725
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4726
                Line upStreamLine = _upStreamObj as Line;
4727
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4728
                Line downStreamLine = _downStreamObj as Line;
4729
                // 둘다 Line일 경우
4730
                if (upStreamLine != null && downStreamLine != null)
4731
                {
4732
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4733
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4734
                }
4735
                // 둘다 Symbol일 경우
4736
                else if (upStreamSymbol != null && downStreamSymbol != null)
4737
                {
4738
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4739
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4740
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4741

    
4742
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4743
                    {
4744
                        if (connector.get_ItemStatus() != "Active")
4745
                            continue;
4746

    
4747
                        if (connector.Id != zeroLenthConnector.Id)
4748
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4749
                    }
4750

    
4751
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4752
                    {
4753
                        if (connector.get_ItemStatus() != "Active")
4754
                            continue;
4755

    
4756
                        if (connector.Id != zeroLenthConnector.Id)
4757
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4758
                    }
4759

    
4760
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4761
                    {
4762
                        if (connector.get_ItemStatus() != "Active")
4763
                            continue;
4764

    
4765
                        if (connector.Id != zeroLenthConnector.Id)
4766
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4767
                    }
4768

    
4769
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4770
                    {
4771
                        if (connector.get_ItemStatus() != "Active")
4772
                            continue;
4773

    
4774
                        if (connector.Id != zeroLenthConnector.Id)
4775
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4776
                    }
4777

    
4778
                    ReleaseCOMObjects(zeroLenthConnector);
4779
                    ReleaseCOMObjects(upStreamLMSymbol);
4780
                    ReleaseCOMObjects(downStreamLMSymbol);
4781
                }
4782
                else if (upStreamSymbol != null && downStreamLine != null)
4783
                {
4784
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4785
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4786
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4787

    
4788
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4789
                    {
4790
                        if (connector.get_ItemStatus() != "Active")
4791
                            continue;
4792

    
4793
                        if (connector.Id == zeroLenthConnector.Id)
4794
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4795
                    }
4796

    
4797
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4798
                    {
4799
                        if (connector.get_ItemStatus() != "Active")
4800
                            continue;
4801

    
4802
                        if (connector.Id == zeroLenthConnector.Id)
4803
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4804
                    }
4805

    
4806
                    ReleaseCOMObjects(zeroLenthConnector);
4807
                    ReleaseCOMObjects(upStreamLMSymbol);
4808
                }
4809
                else if (upStreamLine != null && downStreamSymbol != null)
4810
                {
4811
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4812
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4813
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4814

    
4815
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4816
                    {
4817
                        if (connector.get_ItemStatus() != "Active")
4818
                            continue;
4819

    
4820
                        if (connector.Id == zeroLenthConnector.Id)
4821
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4822
                    }
4823

    
4824
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4825
                    {
4826
                        if (connector.get_ItemStatus() != "Active")
4827
                            continue;
4828

    
4829
                        if (connector.Id == zeroLenthConnector.Id)
4830
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4831
                    }
4832

    
4833
                    ReleaseCOMObjects(zeroLenthConnector);
4834
                    ReleaseCOMObjects(downStreamLMSymbol);
4835
                }
4836
            }
4837

    
4838
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4839
            {
4840
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4841
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4842
                {
4843
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4844
                    if (_LMAAttribute != null)
4845
                    {
4846
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4847
                            _LMAAttribute.set_Value(value);
4848
                        else if (_LMAAttribute.get_Value() != value)
4849
                            _LMAAttribute.set_Value(value);
4850
                    }
4851

    
4852
                    _LMModelItem.Commit();
4853
                }
4854
                if (_LMModelItem != null)
4855
                    ReleaseCOMObjects(_LMModelItem);
4856
            }
4857

    
4858
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4859
            {
4860
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4861
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4862
                {
4863
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4864
                    if (_LMAAttribute != null)
4865
                    {
4866
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4867
                            _LMAAttribute.set_Value(value);
4868
                        else if (_LMAAttribute.get_Value() != value)
4869
                            _LMAAttribute.set_Value(value);
4870
                    }
4871

    
4872
                    _LMModelItem.Commit();
4873
                }
4874
                if (_LMModelItem != null)
4875
                    ReleaseCOMObjects(_LMModelItem);
4876
            }
4877
            #endregion
4878
        }
4879

    
4880
        private void InputEndBreakAttribute(EndBreak endBreak)
4881
        {
4882
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
4883
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
4884

    
4885
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
4886
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
4887
            {
4888
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
4889
                if (labelPersist != null)
4890
                {
4891
                    LMRepresentation representation = labelPersist.RepresentationObject;
4892
                    if (representation != null)
4893
                    {
4894
                        LMConnector connector = dataSource.GetConnector(representation.Id);
4895
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
4896
                        string modelItemID = connector.ModelItemID;
4897
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
4898
                        {
4899
                            List<string> modelItemIDs = new List<string>();
4900
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4901
                            {
4902
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
4903
                                foreach (LMConnector item in symbol.Connect1Connectors)
4904
                                {
4905
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4906
                                        modelItemIDs.Add(item.ModelItemID);
4907
                                    ReleaseCOMObjects(item);
4908
                                }
4909
                                foreach (LMConnector item in symbol.Connect2Connectors)
4910
                                {
4911
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4912
                                        modelItemIDs.Add(item.ModelItemID);
4913
                                    ReleaseCOMObjects(item);
4914
                                }
4915
                                ReleaseCOMObjects(symbol);
4916
                                symbol = null;
4917
                            }
4918
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4919
                            {
4920
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
4921
                                foreach (LMConnector item in symbol.Connect1Connectors)
4922
                                {
4923
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4924
                                        modelItemIDs.Add(item.ModelItemID);
4925
                                    ReleaseCOMObjects(item);
4926
                                }
4927
                                foreach (LMConnector item in symbol.Connect2Connectors)
4928
                                {
4929
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4930
                                        modelItemIDs.Add(item.ModelItemID);
4931
                                    ReleaseCOMObjects(item);
4932
                                }
4933
                                ReleaseCOMObjects(symbol);
4934
                                symbol = null;
4935
                            }
4936

    
4937
                            modelItemIDs = modelItemIDs.Distinct().ToList();
4938
                            if (modelItemIDs.Count == 1)
4939
                            {
4940
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
4941
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
4942
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
4943
                                {
4944
                                    bool result = false;
4945
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
4946
                                    {
4947
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
4948
                                            result = true;
4949
                                        ReleaseCOMObjects(loop);
4950
                                    }
4951

    
4952
                                    if (result)
4953
                                    {
4954
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4955
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4956
                                        ZeroLengthModelItem.Commit();
4957
                                    }
4958
                                    else
4959
                                    {
4960
                                        List<string> loopModelItems = new List<string>();
4961
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
4962
                                        {
4963
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
4964
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4965
                                            {
4966
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4967
                                                    loopModelItems.Add(loop.ModelItemID);
4968
                                                ReleaseCOMObjects(loop);
4969
                                            }
4970
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4971
                                            {
4972
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4973
                                                    loopModelItems.Add(loop.ModelItemID);
4974
                                                ReleaseCOMObjects(loop);
4975
                                            }
4976
                                            ReleaseCOMObjects(_symbol);
4977
                                            _symbol = null;
4978
                                        }
4979
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
4980
                                        {
4981
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
4982
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4983
                                            {
4984
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4985
                                                    loopModelItems.Add(loop.ModelItemID);
4986
                                                ReleaseCOMObjects(loop);
4987
                                            }
4988
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
4989
                                            {
4990
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
4991
                                                    loopModelItems.Add(loop.ModelItemID);
4992
                                                ReleaseCOMObjects(loop);
4993
                                            }
4994
                                            ReleaseCOMObjects(_symbol);
4995
                                            _symbol = null;
4996
                                        }
4997

    
4998
                                        loopModelItems = loopModelItems.Distinct().ToList();
4999
                                        if (loopModelItems.Count == 1)
5000
                                        {
5001
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
5002
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5003
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5004
                                            modelItem.Commit();
5005
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5006
                                            ZeroLengthModelItem.Commit();
5007

    
5008
                                            ReleaseCOMObjects(loopModelItem);
5009
                                            loopModelItem = null;
5010
                                        }
5011
                                    }
5012
                                }
5013
                                else
5014
                                {
5015
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5016
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5017
                                    ZeroLengthModelItem.Commit();
5018
                                }
5019
                                ReleaseCOMObjects(modelItem);
5020
                                modelItem = null;
5021
                                ReleaseCOMObjects(onlyOne);
5022
                                onlyOne = null;
5023
                            }
5024
                        }
5025
                        ReleaseCOMObjects(connector);
5026
                        connector = null;
5027
                        ReleaseCOMObjects(ZeroLengthModelItem);
5028
                        ZeroLengthModelItem = null;
5029
                    }
5030
                    ReleaseCOMObjects(representation);
5031
                    representation = null;
5032
                }
5033
                ReleaseCOMObjects(labelPersist);
5034
                labelPersist = null;
5035
            }
5036
        }
5037

    
5038
        /// <summary>
5039
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5040
        /// </summary>
5041
        /// <param name="text"></param>
5042
        private void NormalTextModeling(Text text)
5043
        {
5044
            LMSymbol _LMSymbol = null;
5045

    
5046
            LMItemNote _LMItemNote = null;
5047
            LMAAttribute _LMAAttribute = null;
5048

    
5049
            double x = 0;
5050
            double y = 0;
5051
            double angle = text.ANGLE;
5052
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5053

    
5054
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5055
            text.SPPID.SPPID_X = x;
5056
            text.SPPID.SPPID_Y = y;
5057

    
5058
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
5059
            if (_LMSymbol != null)
5060
            {
5061
                _LMSymbol.Commit();
5062
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5063
                if (_LMItemNote != null)
5064
                {
5065
                    _LMItemNote.Commit();
5066
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5067
                    if (_LMAAttribute != null)
5068
                    {
5069
                        _LMAAttribute.set_Value(text.VALUE);
5070
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5071
                        _LMItemNote.Commit();
5072

    
5073

    
5074
                        double[] range = null;
5075
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5076
                        {
5077
                            double[] temp = null;
5078
                            GetSPPIDSymbolRange(labelPersist, ref temp);
5079
                            if (temp != null)
5080
                            {
5081
                                if (range == null)
5082
                                    range = temp;
5083
                                else
5084
                                {
5085
                                    range = new double[] {
5086
                                            Math.Min(range[0], temp[0]),
5087
                                            Math.Min(range[1], temp[1]),
5088
                                            Math.Max(range[2], temp[2]),
5089
                                            Math.Max(range[3], temp[3])
5090
                                        };
5091
                                }
5092
                            }
5093
                        }
5094
                        text.SPPID.Range = range;
5095

    
5096
                        if (_LMAAttribute != null)
5097
                            ReleaseCOMObjects(_LMAAttribute);
5098
                        if (_LMItemNote != null)
5099
                            ReleaseCOMObjects(_LMItemNote);
5100
                    }
5101

    
5102
                    TextCorrectModeling(text);
5103
                }
5104
            }
5105
            if (_LMSymbol != null)
5106
                ReleaseCOMObjects(_LMSymbol);
5107
        }
5108

    
5109
        private void DefaultTextModeling(string value, double x, double y)
5110
        {
5111
            LMSymbol _LMSymbol = null;
5112

    
5113
            LMItemNote _LMItemNote = null;
5114
            LMAAttribute _LMAAttribute = null;
5115

    
5116
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
5117
            if (_LMSymbol != null)
5118
            {
5119
                _LMSymbol.Commit();
5120
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5121
                if (_LMItemNote != null)
5122
                {
5123
                    _LMItemNote.Commit();
5124
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5125
                    if (_LMAAttribute != null)
5126
                    {
5127
                        _LMAAttribute.set_Value(value);
5128
                        _LMItemNote.Commit();
5129

    
5130
                        if (_LMAAttribute != null)
5131
                            ReleaseCOMObjects(_LMAAttribute);
5132
                        if (_LMItemNote != null)
5133
                            ReleaseCOMObjects(_LMItemNote);
5134
                    }
5135
                }
5136
            }
5137
            if (_LMSymbol != null)
5138
                ReleaseCOMObjects(_LMSymbol);
5139
        }
5140

    
5141
        private void AssociationTextModeling(Text text)
5142
        {
5143
            LMSymbol _LMSymbol = null;
5144
            LMConnector connectedLMConnector = null;
5145
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5146
            if (owner != null && owner.GetType() == typeof(Symbol))
5147
            {
5148
                Symbol symbol = owner as Symbol;
5149
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5150
                if (_LMSymbol != null)
5151
                {
5152
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5153
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5154
                    {
5155
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5156

    
5157
                        if (mapping != null)
5158
                        {
5159
                            double x = 0;
5160
                            double y = 0;
5161

    
5162
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5163
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5164
                            Array array = new double[] { 0, x, y };
5165
                            text.SPPID.SPPID_X = x;
5166
                            text.SPPID.SPPID_Y = y;
5167
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5168
                            if (_LMLabelPersist != null)
5169
                            {
5170
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5171
                                _LMLabelPersist.Commit();
5172
                                ReleaseCOMObjects(_LMLabelPersist);
5173
                            }
5174
                        }
5175
                    }
5176
                }
5177
            }
5178
            else if (owner != null && owner.GetType() == typeof(Line))
5179
            {
5180
                Line line = owner as Line;
5181
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5182
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
5183

    
5184
                if (connectedLMConnector != null)
5185
                {
5186
                    BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5187
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5188
                    {
5189
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5190

    
5191
                        if (mapping != null)
5192
                        {
5193
                            double x = 0;
5194
                            double y = 0;
5195
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5196
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5197
                            Array array = new double[] { 0, x, y };
5198

    
5199
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5200
                            if (_LMLabelPersist != null)
5201
                            {
5202
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5203
                                _LMLabelPersist.Commit();
5204
                                ReleaseCOMObjects(_LMLabelPersist);
5205
                            }
5206
                        }
5207
                    }
5208
                }
5209
            }
5210
            if (_LMSymbol != null)
5211
                ReleaseCOMObjects(_LMSymbol);
5212
        }
5213

    
5214
        private void TextCorrectModeling(Text text)
5215
        {
5216
            if (text.SPPID.Range == null)
5217
                return;
5218

    
5219
            bool needRemodeling = false;
5220
            bool loop = true;
5221
            GridSetting gridSetting = GridSetting.GetInstance();
5222
            while (loop)
5223
            {
5224
                loop = false;
5225
                foreach (var overlapText in document.TEXTINFOS)
5226
                {
5227
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5228
                        continue;
5229

    
5230
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5231
                    {
5232
                        double percentX = 0;
5233
                        double percentY = 0;
5234
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
5235
                        {
5236
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
5237
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
5238
                        }
5239
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
5240
                        {
5241
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
5242
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
5243
                        }
5244

    
5245
                        double tempX = 0;
5246
                        double tempY = 0;
5247
                        bool overlapX = false;
5248
                        bool overlapY = false;
5249
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5250
                        if (percentX >= percentY)
5251
                        {
5252
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5253
                            double move = gridSetting.Length * count;
5254
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
5255
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
5256
                            needRemodeling = true;
5257
                            loop = true;
5258
                        }
5259
                        else
5260
                        {
5261
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5262
                            double move = gridSetting.Length * count;
5263
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
5264
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
5265
                            needRemodeling = true;
5266
                            loop = true;
5267
                        }
5268
                    }
5269
                }
5270
            }
5271
            
5272

    
5273
            if (needRemodeling)
5274
            {
5275
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
5276
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5277
                text.SPPID.RepresentationId = null;
5278

    
5279
                LMItemNote _LMItemNote = null;
5280
                LMAAttribute _LMAAttribute = null;
5281
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
5282
                if (_LMSymbol != null)
5283
                {
5284
                    _LMSymbol.Commit();
5285
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5286
                    if (_LMItemNote != null)
5287
                    {
5288
                        _LMItemNote.Commit();
5289
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5290
                        if (_LMAAttribute != null)
5291
                        {
5292
                            _LMAAttribute.set_Value(text.VALUE);
5293
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5294
                            _LMItemNote.Commit();
5295

    
5296
                            ReleaseCOMObjects(_LMAAttribute);
5297
                            ReleaseCOMObjects(_LMItemNote);
5298
                        }
5299
                    }
5300
                }
5301

    
5302
                ReleaseCOMObjects(symbol);
5303
                symbol = null;
5304
                ReleaseCOMObjects(_LMItemNote);
5305
                _LMItemNote = null;
5306
                ReleaseCOMObjects(_LMAAttribute);
5307
                _LMAAttribute = null;
5308
                ReleaseCOMObjects(_LMSymbol);
5309
                _LMSymbol = null;
5310
            }
5311
        }
5312

    
5313
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
5314
        {
5315
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
5316
            {
5317
                List<Text> allTexts = new List<Text>();
5318
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5319
                LMRepresentation representation = targetLabel.RepresentationObject;
5320
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
5321
                if (targetLabel.RepresentationObject != null && symbol != null)
5322
                {
5323
                    double[] symbolRange = null;
5324
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
5325
                    if (symbolRange != null)
5326
                    {
5327
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
5328
                        {
5329
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
5330
                            if (findText != null)
5331
                            {
5332
                                double[] range = null;
5333
                                GetSPPIDSymbolRange(labelPersist, ref range);
5334
                                findText.SPPID.Range = range;
5335
                                allTexts.Add(findText);
5336
                            }
5337

    
5338
                            ReleaseCOMObjects(labelPersist);
5339
                        }
5340

    
5341
                        if (allTexts.Count > 0)
5342
                        {
5343
                            #region Sort Text By Y
5344
                            allTexts.Sort(SortTextByY);
5345
                            int SortTextByY(Text a, Text b)
5346
                            {
5347
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
5348
                            }
5349
                            #endregion
5350

    
5351
                            #region 정렬하기전 방향
5352
                            List<Text> left = new List<Text>();
5353
                            List<Text> down = new List<Text>();
5354
                            List<Text> right = new List<Text>();
5355
                            List<Text> up = new List<Text>();
5356
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
5357
                            foreach (var loopText in allTexts)
5358
                            {
5359
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
5360
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
5361
                                double originX = 0;
5362
                                double originY = 0;
5363
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5364
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5365

    
5366
                                if (angle < 45)
5367
                                {
5368
                                    // Text 오른쪽
5369
                                    if (textCenterX > originX)
5370
                                        right.Add(loopText);
5371
                                    // Text 왼쪽
5372
                                    else
5373
                                        left.Add(loopText); 
5374
                                }
5375
                                else
5376
                                {
5377
                                    // Text 아래쪽
5378
                                    if (textCenterY > originY)
5379
                                        down.Add(loopText);
5380
                                    // Text 위쪽
5381
                                    else
5382
                                        up.Add(loopText);
5383
                                }
5384
                            }
5385
                            
5386
                            #endregion
5387

    
5388
                            foreach (var texts in sortTexts)
5389
                            {
5390
                                if (texts.Count == 0 )
5391
                                    continue;
5392
                                
5393
                                #region 첫번째 Text로 기준 맞춤
5394
                                for (int i = 0; i < texts.Count; i++)
5395
                                {
5396
                                    if (i != 0)
5397
                                    {
5398
                                        Text currentText = texts[i];
5399
                                        Text prevText = texts[i - 1];
5400
                                        double minY = prevText.SPPID.Range[1];
5401
                                        double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
5402
                                        double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
5403
                                        double _gapX = centerX - centerPrevX;
5404
                                        double _gapY = currentText.SPPID.Range[3] - minY;
5405
                                        MoveText(currentText, _gapX, _gapY);
5406
                                    }
5407
                                }
5408
                                List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
5409
                                List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
5410
                                List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
5411
                                List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
5412
                                rangeMinX.Sort();
5413
                                rangeMinY.Sort();
5414
                                rangeMaxX.Sort();
5415
                                rangeMaxY.Sort();
5416
                                double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
5417
                                double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
5418
                                #endregion
5419
                                #region 정렬
5420
                                Text correctBySymbol = texts[0];
5421
                                double textCenterX = (correctBySymbol.X1 + correctBySymbol.X2) / 2;
5422
                                double textCenterY = (correctBySymbol.Y1 + correctBySymbol.Y2) / 2;
5423
                                double originX = 0;
5424
                                double originY = 0;
5425
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5426
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5427
                                double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
5428
                                double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
5429

    
5430
                                double gapX = 0;
5431
                                double gapY = 0;
5432
                                if (angle < 45)
5433
                                {
5434
                                    // Text 오른쪽
5435
                                    if (textCenterX > originX)
5436
                                    {
5437
                                        gapX = rangeMinX[0] - symbolRange[2];
5438
                                        gapY = allTextCenterY - symbolCenterY;
5439
                                    }
5440
                                    // Text 왼쪽
5441
                                    else
5442
                                    {
5443
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
5444
                                        gapY = allTextCenterY - symbolCenterY;
5445
                                    }
5446
                                }
5447
                                else
5448
                                {
5449
                                    // Text 아래쪽
5450
                                    if (textCenterY > originY)
5451
                                    {
5452
                                        gapX = allTextCenterX - symbolCenterX;
5453
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
5454
                                    }
5455
                                    // Text 위쪽
5456
                                    else
5457
                                    {
5458
                                        gapX = allTextCenterX - symbolCenterX;
5459
                                        gapY = rangeMinY[0] - symbolRange[3];
5460
                                    }
5461
                                }
5462

    
5463
                                foreach (var item in texts)
5464
                                {
5465
                                    MoveText(item, gapX, gapY);
5466
                                    RemodelingAssociationText(item);
5467
                                }
5468
                                #endregion
5469
                            }
5470
                        }
5471
                    }
5472
                }
5473

    
5474
                void MoveText(Text moveText, double x, double y)
5475
                {
5476
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
5477
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
5478
                    moveText.SPPID.Range = new double[] {
5479
                        moveText.SPPID.Range[0] - x,
5480
                        moveText.SPPID.Range[1]- y,
5481
                        moveText.SPPID.Range[2]- x,
5482
                        moveText.SPPID.Range[3]- y
5483
                    };
5484
                }
5485

    
5486
                endTexts.AddRange(allTexts);
5487

    
5488
                ReleaseCOMObjects(targetLabel);
5489
                targetLabel = null;
5490
                ReleaseCOMObjects(representation);
5491
                representation = null;
5492
            }
5493
        }
5494

    
5495
        private void RemodelingAssociationText(Text text)
5496
        {
5497
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5498
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5499
            removeLabel.Commit();
5500
            ReleaseCOMObjects(removeLabel);
5501
            removeLabel = null;
5502

    
5503
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5504
            if (owner != null && owner.GetType() == typeof(Symbol))
5505
            {
5506
                Symbol symbol = owner as Symbol;
5507
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5508
                if (_LMSymbol != null)
5509
                {
5510
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5511
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5512
                    {
5513
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5514

    
5515
                        if (mapping != null)
5516
                        {
5517
                            double x = 0;
5518
                            double y = 0;
5519

    
5520
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5521
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5522
                            if (_LMLabelPersist != null)
5523
                            {
5524
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5525
                                _LMLabelPersist.Commit();
5526
                            }
5527
                            ReleaseCOMObjects(_LMLabelPersist);
5528
                            _LMLabelPersist = null;
5529
                        }
5530
                    }
5531
                }
5532
                ReleaseCOMObjects(_LMSymbol);
5533
                _LMSymbol = null;
5534
            }
5535
        }
5536

    
5537
        /// <summary>
5538
        /// Note Modeling
5539
        /// </summary>
5540
        /// <param name="note"></param>
5541
        private void NoteModeling(Note note, List<Note> correctList)
5542
        {
5543
            LMSymbol _LMSymbol = null;
5544
            LMItemNote _LMItemNote = null;
5545
            LMAAttribute _LMAAttribute = null;
5546

    
5547
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5548
            {
5549
                double x = 0;
5550
                double y = 0;
5551

    
5552
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5553
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5554
                note.SPPID.SPPID_X = x;
5555
                note.SPPID.SPPID_Y = y;
5556

    
5557
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5558
                if (_LMSymbol != null)
5559
                {
5560
                    _LMSymbol.Commit();
5561
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5562
                    if (_LMItemNote != null)
5563
                    {
5564
                        _LMItemNote.Commit();
5565
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5566
                        if (_LMAAttribute != null)
5567
                        {
5568
                            _LMAAttribute.set_Value(note.VALUE);
5569
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5570

    
5571
                            double[] range = null;
5572
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5573
                            {
5574
                                double[] temp = null;
5575
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5576
                                if (temp != null)
5577
                                {
5578
                                    if (range == null)
5579
                                        range = temp;
5580
                                    else
5581
                                    {
5582
                                        range = new double[] {
5583
                                            Math.Min(range[0], temp[0]),
5584
                                            Math.Min(range[1], temp[1]),
5585
                                            Math.Max(range[2], temp[2]),
5586
                                            Math.Max(range[3], temp[3])
5587
                                        };
5588
                                    }
5589
                                }
5590
                            }
5591
                            if (range != null)
5592
                                correctList.Add(note);
5593
                            note.SPPID.Range = range;
5594

    
5595

    
5596
                            _LMItemNote.Commit();
5597
                        }
5598
                    }
5599
                }
5600
            }
5601

    
5602
            if (_LMAAttribute != null)
5603
                ReleaseCOMObjects(_LMAAttribute);
5604
            if (_LMItemNote != null)
5605
                ReleaseCOMObjects(_LMItemNote);
5606
            if (_LMSymbol != null)
5607
                ReleaseCOMObjects(_LMSymbol);
5608
        }
5609

    
5610
        private void NoteCorrectModeling(Note note, List<Note> endList)
5611
        {
5612
            bool needRemodeling = false;
5613
            bool loop = true;
5614
            GridSetting gridSetting = GridSetting.GetInstance();
5615
            while (loop)
5616
            {
5617
                loop = false;
5618
                foreach (var overlap in endList)
5619
                {
5620
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5621
                    {
5622
                        double tempX = 0;
5623
                        double tempY = 0;
5624
                        bool overlapX = false;
5625
                        bool overlapY = false;
5626
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5627
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5628
                        if (overlapY && angle >= 45)
5629
                        {
5630
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5631
                            double move = gridSetting.Length * count;
5632
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5633
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5634
                            needRemodeling = true;
5635
                            loop = true;
5636
                        }
5637
                        if (overlapX && angle <= 45)
5638
                        {
5639
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5640
                            double move = gridSetting.Length * count;
5641
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5642
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5643
                            needRemodeling = true;
5644
                            loop = true;
5645
                        }
5646
                    }
5647
                }
5648
            }
5649

    
5650

    
5651
            if (needRemodeling)
5652
            {
5653
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5654
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5655
                note.SPPID.RepresentationId = null;
5656

    
5657
                LMItemNote _LMItemNote = null;
5658
                LMAAttribute _LMAAttribute = null;
5659
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5660
                if (_LMSymbol != null)
5661
                {
5662
                    _LMSymbol.Commit();
5663
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5664
                    if (_LMItemNote != null)
5665
                    {
5666
                        _LMItemNote.Commit();
5667
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5668
                        if (_LMAAttribute != null)
5669
                        {
5670
                            _LMAAttribute.set_Value(note.VALUE);
5671
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5672
                            _LMItemNote.Commit();
5673

    
5674
                            ReleaseCOMObjects(_LMAAttribute);
5675
                            ReleaseCOMObjects(_LMItemNote);
5676
                        }
5677
                    }
5678
                }
5679

    
5680
                ReleaseCOMObjects(symbol);
5681
                symbol = null;
5682
                ReleaseCOMObjects(_LMItemNote);
5683
                _LMItemNote = null;
5684
                ReleaseCOMObjects(_LMAAttribute);
5685
                _LMAAttribute = null;
5686
                ReleaseCOMObjects(_LMSymbol);
5687
                _LMSymbol = null;
5688
            }
5689

    
5690
            endList.Add(note);
5691
        }
5692

    
5693
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5694
        {
5695
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5696
            if (modelItem != null)
5697
            {
5698
                foreach (LMRepresentation rep in modelItem.Representations)
5699
                {
5700
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5701
                    {
5702
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5703
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5704
                        {
5705
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5706
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5707
                            if (modelItemIds.Count == 1)
5708
                            {
5709
                                string joinModelItemId = modelItemIds[0];
5710
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5711
                                if (survivorId != null)
5712
                                    break;
5713
                            }
5714
                        }
5715
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5716
                        {
5717
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5718
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5719
                            if (modelItemIds.Count == 1)
5720
                            {
5721
                                string joinModelItemId = modelItemIds[0];
5722
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5723
                                if (survivorId != null)
5724
                                    break;
5725
                            }
5726
                        }
5727
                    }
5728
                }
5729
            }
5730
        }
5731

    
5732
        /// <summary>
5733
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5734
        /// </summary>
5735
        /// <param name="x"></param>
5736
        /// <param name="y"></param>
5737
        /// <param name="originX"></param>
5738
        /// <param name="originY"></param>
5739
        /// <param name="SPPIDLabelLocation"></param>
5740
        /// <param name="location"></param>
5741
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5742
        {
5743
            if (location == Location.None)
5744
            {
5745
                x = originX;
5746
                y = originY;
5747
            }
5748
            else
5749
            {
5750
                if (location.HasFlag(Location.Center))
5751
                {
5752
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5753
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5754
                }
5755

    
5756
                if (location.HasFlag(Location.Left))
5757
                    x = SPPIDLabelLocation.X1;
5758
                else if (location.HasFlag(Location.Right))
5759
                    x = SPPIDLabelLocation.X2;
5760

    
5761
                if (location.HasFlag(Location.Down))
5762
                    y = SPPIDLabelLocation.Y1;
5763
                else if (location.HasFlag(Location.Up))
5764
                    y = SPPIDLabelLocation.Y2;
5765
            }
5766
        }
5767

    
5768
        /// <summary>
5769
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5770
        /// 1. Angle Valve
5771
        /// 2. 3개로 이루어진 Symbol Group
5772
        /// </summary>
5773
        /// <returns></returns>
5774
        private List<Symbol> GetPrioritySymbol()
5775
        {
5776
            DataTable symbolTable = document.SymbolTable;
5777
            // List에 순서대로 쌓는다.
5778
            List<Symbol> symbols = new List<Symbol>();
5779

    
5780
            // Angle Valve 부터
5781
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5782
            {
5783
                if (!symbols.Contains(symbol))
5784
                {
5785
                    double originX = 0;
5786
                    double originY = 0;
5787

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

    
5792
                    SlopeType slopeType1 = SlopeType.None;
5793
                    SlopeType slopeType2 = SlopeType.None;
5794
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5795
                    {
5796
                        double connectorX = 0;
5797
                        double connectorY = 0;
5798
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5799
                        if (slopeType1 == SlopeType.None)
5800
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5801
                        else
5802
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5803
                    }
5804

    
5805
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5806
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5807
                        symbols.Add(symbol);
5808
                }
5809
            }
5810

    
5811
            List<Symbol> tempSymbols = new List<Symbol>();
5812
            // Conn 갯수 기준
5813
            foreach (var item in document.SYMBOLS)
5814
            {
5815
                if (!symbols.Contains(item))
5816
                    tempSymbols.Add(item);
5817
            }
5818
            tempSymbols.Sort(SortSymbolPriority);
5819
            symbols.AddRange(tempSymbols);
5820

    
5821
            return symbols;
5822
        }
5823

    
5824
        private void SetPriorityLine(List<Line> lines)
5825
        {
5826
            lines.Sort(SortLinePriority);
5827

    
5828
            int SortLinePriority(Line a, Line b)
5829
            {
5830
                // Branch 없는것부터
5831
                int branchRetval = CompareBranchLine(a, b);
5832
                if (branchRetval != 0)
5833
                {
5834
                    return branchRetval;
5835
                }
5836
                else
5837
                {
5838
                    // Symbol 연결 갯수
5839
                    int connSymbolRetval = CompareConnSymbol(a, b);
5840
                    if (connSymbolRetval != 0)
5841
                    {
5842
                        return connSymbolRetval;
5843
                    }
5844
                    else
5845
                    {
5846
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5847
                        int connItemRetval = CompareConnItem(a, b);
5848
                        if (connItemRetval != 0)
5849
                        {
5850
                            return connItemRetval;
5851
                        }
5852
                        else
5853
                        {
5854
                            // ConnectedItem이 없는것
5855
                            int noneConnRetval = CompareNoneConn(a, b);
5856
                            if (noneConnRetval != 0)
5857
                            {
5858
                                return noneConnRetval;
5859
                            }
5860
                            else
5861
                            {
5862

    
5863
                            }
5864
                        }
5865
                    }
5866
                }
5867

    
5868
                return 0;
5869
            }
5870

    
5871
            int CompareNotSegmentLine(Line a, Line b)
5872
            {
5873
                List<Connector> connectorsA = a.CONNECTORS
5874
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5875
                    .ToList();
5876

    
5877
                List<Connector> connectorsB = b.CONNECTORS
5878
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5879
                    .ToList();
5880

    
5881
                // 오름차순
5882
                return connectorsB.Count.CompareTo(connectorsA.Count);
5883
            }
5884

    
5885
            int CompareConnSymbol(Line a, Line b)
5886
            {
5887
                List<Connector> connectorsA = a.CONNECTORS
5888
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5889
                    .ToList();
5890

    
5891
                List<Connector> connectorsB = b.CONNECTORS
5892
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5893
                    .ToList();
5894

    
5895
                // 오름차순
5896
                return connectorsB.Count.CompareTo(connectorsA.Count);
5897
            }
5898

    
5899
            int CompareConnItem(Line a, Line b)
5900
            {
5901
                List<Connector> connectorsA = a.CONNECTORS
5902
                    .Where(conn => conn.ConnectedObject != null && 
5903
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5904
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5905
                    .ToList();
5906

    
5907
                List<Connector> connectorsB = b.CONNECTORS
5908
                    .Where(conn => conn.ConnectedObject != null &&
5909
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5910
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5911
                    .ToList();
5912

    
5913
                // 오름차순
5914
                return connectorsB.Count.CompareTo(connectorsA.Count);
5915
            }
5916

    
5917
            int CompareBranchLine(Line a, Line b)
5918
            {
5919
                List<Connector> connectorsA = a.CONNECTORS
5920
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5921
                    .ToList();
5922
                List<Connector> connectorsB = b.CONNECTORS
5923
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5924
                    .ToList();
5925

    
5926
                // 내림차순
5927
                return connectorsA.Count.CompareTo(connectorsB.Count);
5928
            }
5929

    
5930
            int CompareNoneConn(Line a, Line b)
5931
            {
5932
                List<Connector> connectorsA = a.CONNECTORS
5933
                    .Where(conn => conn.ConnectedObject == null)
5934
                    .ToList();
5935

    
5936
                List<Connector> connectorsB = b.CONNECTORS
5937
                    .Where(conn => conn.ConnectedObject == null)
5938
                    .ToList();
5939

    
5940
                // 오름차순
5941
                return connectorsB.Count.CompareTo(connectorsA.Count);
5942
            }
5943
        }
5944

    
5945
        private void SortText(List<Text> texts)
5946
        {
5947
            texts.Sort(Sort);
5948

    
5949
            int Sort(Text a, Text b)
5950
            {
5951
                int yRetval = CompareY(a, b);
5952
                if (yRetval != 0)
5953
                {
5954
                    return yRetval;
5955
                }
5956
                else
5957
                {
5958
                    return CompareX(a, b);
5959
                }
5960
            }
5961

    
5962
            int CompareY(Text a, Text b)
5963
            {
5964
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5965
            }
5966

    
5967
            int CompareX(Text a, Text b)
5968
            {
5969
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5970
            }
5971
        }
5972
        private void SortNote(List<Note> notes)
5973
        {
5974
            notes.Sort(Sort);
5975

    
5976
            int Sort(Note a, Note b)
5977
            {
5978
                int yRetval = CompareY(a, b);
5979
                if (yRetval != 0)
5980
                {
5981
                    return yRetval;
5982
                }
5983
                else
5984
                {
5985
                    return CompareX(a, b);
5986
                }
5987
            }
5988

    
5989
            int CompareY(Note a, Note b)
5990
            {
5991
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5992
            }
5993

    
5994
            int CompareX(Note a, Note b)
5995
            {
5996
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5997
            }
5998
        }
5999

    
6000
        private void SortBranchLines()
6001
        {
6002
            BranchLines.Sort(SortBranchLine);
6003
            int SortBranchLine(Line a, Line b)
6004
            {
6005
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6006
                 x.ConnectedObject.GetType() == typeof(Line) &&
6007
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
6008
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6009

    
6010
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6011
                 x.ConnectedObject.GetType() == typeof(Line) &&
6012
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
6013
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6014

    
6015
                // 내림차순
6016
                return countA.CompareTo(countB);
6017
            }
6018
        }
6019

    
6020
        private static int SortSymbolPriority(Symbol a, Symbol b)
6021
        {
6022
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6023
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6024
            int retval = countB.CompareTo(countA);
6025
            if (retval != 0)
6026
                return retval;
6027
            else
6028
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
6029
        }
6030

    
6031
        private string GetSPPIDFileName(LMModelItem modelItem)
6032
        {
6033
            string symbolPath = null;
6034
            foreach (LMRepresentation rep in modelItem.Representations)
6035
            {
6036
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6037
                {
6038
                    symbolPath = rep.get_FileName();
6039
                    break;
6040
                }
6041
            }
6042
            return symbolPath;
6043
        }
6044

    
6045
        private string GetSPPIDFileName(string modelItemId)
6046
        {
6047
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6048
            string symbolPath = null;
6049
            foreach (LMRepresentation rep in modelItem.Representations)
6050
            {
6051
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6052
                {
6053
                    symbolPath = rep.get_FileName();
6054
                    break;
6055
                }
6056
            }
6057
            ReleaseCOMObjects(modelItem);
6058
            return symbolPath;
6059
        }
6060

    
6061
        /// <summary>
6062
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
6063
        /// </summary>
6064
        /// <param name="graphicOID"></param>
6065
        /// <param name="milliseconds"></param>
6066
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
6067
        {
6068
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
6069
            {
6070
                double minX = 0;
6071
                double minY = 0;
6072
                double maxX = 0;
6073
                double maxY = 0;
6074
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
6075
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
6076

    
6077
                Thread.Sleep(milliseconds);
6078
            }
6079
        }
6080

    
6081
        /// <summary>
6082
        /// ComObject를 Release
6083
        /// </summary>
6084
        /// <param name="objVars"></param>
6085
        public void ReleaseCOMObjects(params object[] objVars)
6086
        {
6087
            if (objVars != null)
6088
            {
6089
                int intNewRefCount = 0;
6090
                foreach (object obj in objVars)
6091
                {
6092
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
6093
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
6094
                }
6095
            }
6096
        }
6097

    
6098
        /// IDisposable 구현
6099
        ~AutoModeling()
6100
        {
6101
            this.Dispose(false);
6102
        }
6103

    
6104
        private bool disposed;
6105
        public void Dispose()
6106
        {
6107
            this.Dispose(true);
6108
            GC.SuppressFinalize(this);
6109
        }
6110

    
6111
        protected virtual void Dispose(bool disposing)
6112
        {
6113
            if (this.disposed) return;
6114
            if (disposing)
6115
            {
6116
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
6117
            }
6118
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
6119
            this.disposed = true;
6120
        }
6121
    }
6122
}
클립보드 이미지 추가 (최대 크기: 500 MB)