프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 14154713

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

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

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

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

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

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

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

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

    
402
                                    // 제거
403
                                    RemoveSymbol(connSymbol);
404
                                    RemoveLine(item);
405

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

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

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

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

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

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

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

    
587
                LMRelationships relationships = new LMRelationships();
588
                relationships.Collect(dataSource, Filter: filter);
589

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

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

    
749
                    }
750
                }
751
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
752
            }
753

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

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

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

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

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

    
1050
                LMDrawings drawings = new LMDrawings();
1051
                drawings.Collect(dataSource, Filter: filter);
1052

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

    
1079
                        drawingAttributeDT.Dispose();
1080
                    }
1081

    
1082
                    ReleaseCOMObjects(drawing);
1083
                }
1084

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

    
1096
            if (newDrawing != null)
1097
            {
1098
                SetBorderFile();
1099
                return true;
1100
            }
1101
            else
1102
                return false;
1103
        }
1104

    
1105
        private void SetBorderFile()
1106
        {
1107
            ETCSetting setting = ETCSetting.GetInstance();
1108

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

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

    
1133
            List<string> drawingNameList = new List<string>();
1134
            List<string> drawingNumberList = new List<string>();
1135

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

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

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

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

    
1196
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1197
            {
1198
                Log.Write("Setting Drawing X, Drawing Y");
1199
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1200
                Log.Write("Start coordinate correction");
1201
                document.CoordinateCorrection();
1202
                return true;
1203
            }
1204
            else
1205
            {
1206
                Log.Write("Need Drawing X, Y");
1207
                return false;
1208
            }
1209
        }
1210

    
1211
        /// <summary>
1212
        /// 심볼을 실제로 Modeling 메서드
1213
        /// </summary>
1214
        /// <param name="symbol">생성할 심볼</param>
1215
        /// <param name="targetSymbol">연결되어 있는 심볼</param>
1216
        private void SymbolModeling(Symbol symbol, Symbol targetSymbol)
1217
        {
1218
            // OWNERSYMBOL Attribute, 값을 가지고 있을 경우
1219
            BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(attr => attr.ATTRIBUTE == "OWNERSYMBOL");
1220
            if (itemAttribute != null && (string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE != "None"))
1221
                return;
1222
            // 이미 모델링 됐을 경우
1223
            else if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1224
                return;
1225

    
1226
            LMSymbol _LMSymbol = null;
1227

    
1228
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1229
            double x = symbol.SPPID.ORIGINAL_X;
1230
            double y = symbol.SPPID.ORIGINAL_Y;
1231
            int mirror = 0;
1232
            double angle = symbol.ANGLE;
1233

    
1234
            // OPC 일경우 180도 일때 Mirror
1235
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1236
                mirror = 1;
1237

    
1238
            // Mirror 계산
1239
            if (symbol.FLIP == 1)
1240
            {
1241
                mirror = 1;
1242
                angle += Math.PI;
1243
            }
1244

    
1245
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1246
            {
1247
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1248
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1249
                if (connector != null)
1250
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1251

    
1252
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1253
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1254
                if (temp != null)
1255
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1256
                ReleaseCOMObjects(temp);
1257
                temp = null;
1258

    
1259
                if (_LMSymbol != null && _TargetItem != null)
1260
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1261

    
1262
                ReleaseCOMObjects(_TargetItem);
1263
            }
1264
            else
1265
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1266

    
1267
            if (_LMSymbol != null)
1268
            {
1269
                _LMSymbol.Commit();
1270

    
1271
                // ConnCheck
1272
                List<string> ids = new List<string>();
1273
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1274
                {
1275
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1276
                        ids.Add(item.Id);
1277
                    ReleaseCOMObjects(item);
1278
                }
1279
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1280
                {
1281
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1282
                        ids.Add(item.Id);
1283
                    ReleaseCOMObjects(item);
1284
                }
1285

    
1286
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1287
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1288
                {
1289
                    double currentX = _LMSymbol.get_XCoordinate();
1290
                    double currentY = _LMSymbol.get_YCoordinate();
1291

    
1292

    
1293
                }
1294

    
1295
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1296
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1297
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1298

    
1299
                foreach (var item in symbol.ChildSymbols)
1300
                    CreateChildSymbol(item, _LMSymbol, symbol);
1301

    
1302
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1303
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1304

    
1305
                double[] range = null;
1306
                GetSPPIDSymbolRange(symbol, ref range);
1307
                symbol.SPPID.SPPID_Min_X = range[0];
1308
                symbol.SPPID.SPPID_Min_Y = range[1];
1309
                symbol.SPPID.SPPID_Max_X = range[2];
1310
                symbol.SPPID.SPPID_Max_Y = range[3];
1311

    
1312
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1313
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1314
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1315
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1316

    
1317
                ReleaseCOMObjects(_LMSymbol);
1318
            }
1319
        }
1320
        /// <summary>
1321
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1322
        /// Signal Point는 고려하지 않음
1323
        /// </summary>
1324
        /// <param name="symbol"></param>
1325
        /// <param name="_TargetItem"></param>
1326
        /// <param name="targetX"></param>
1327
        /// <param name="targetY"></param>
1328
        /// <returns></returns>
1329
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1330
        {
1331
            LMConnector tempConnector = null;
1332

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

    
1358
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1359
                            if (calcDistance > length)
1360
                            {
1361
                                lineX = tempX;
1362
                                lineY = tempY;
1363
                            }
1364
                        }
1365

    
1366
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1367
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1368
                        placeRunInputs.AddPoint(-1, -1);
1369
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1370
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1371
                        if (tempConnector != null)
1372
                            tempConnector.Commit();
1373
                        ReleaseCOMObjects(_LMAItem);
1374
                        _LMAItem = null;
1375
                        ReleaseCOMObjects(placeRunInputs);
1376
                        placeRunInputs = null;
1377
                    }
1378
                }
1379
            }
1380

    
1381
            return tempConnector;
1382
        }
1383
        /// <summary>
1384
        /// Symbol의 PipingPoints를 구함
1385
        /// SignalPoint는 고려하지 않음
1386
        /// </summary>
1387
        /// <param name="symbol"></param>
1388
        /// <returns></returns>
1389
        private List<double[]> getPipingPoints(LMSymbol symbol)
1390
        {
1391
            LMModelItem modelItem = symbol.ModelItemObject;
1392
            LMPipingPoints pipingPoints = null;
1393
            if (modelItem.get_ItemTypeName() == "PipingComp")
1394
            {
1395
                LMPipingComp pipingComp = dataSource.GetPipingComp(modelItem.Id);
1396
                pipingPoints = pipingComp.PipingPoints;
1397
                ReleaseCOMObjects(pipingComp);
1398
                pipingComp = null;
1399
            }
1400
            else if (modelItem.get_ItemTypeName() == "Instrument")
1401
            {
1402
                LMInstrument instrument = dataSource.GetInstrument(modelItem.Id);
1403
                pipingPoints = instrument.PipingPoints;
1404
                ReleaseCOMObjects(instrument);
1405
                instrument = null;
1406
            }
1407
            else
1408
                Log.Write("다른 Type");
1409

    
1410
            List<double[]> info = new List<double[]>();
1411
            if (pipingPoints != null)
1412
            {
1413
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1414
                {
1415
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1416
                    {
1417
                        if (attribute.Name == "PipingPointNumber")
1418
                        {
1419
                            int index = Convert.ToInt32(attribute.get_Value());
1420
                            if (info.Find(loopX => loopX[0] == index) == null)
1421
                            {
1422
                                double x = 0;
1423
                                double y = 0;
1424
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1425
                                    info.Add(new double[] { index, x, y });
1426
                            }
1427
                        }
1428
                    }
1429
                }
1430
            }
1431
            ReleaseCOMObjects(modelItem);
1432
            modelItem = null;
1433
            ReleaseCOMObjects(pipingPoints);
1434
            pipingPoints = null;
1435

    
1436
            return info;
1437
        }
1438

    
1439
        private void RemoveSymbol(Symbol symbol)
1440
        {
1441
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1442
            {
1443
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1444
                if (_LMSymbol != null)
1445
                {
1446
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1447
                    ReleaseCOMObjects(_LMSymbol);
1448
                }
1449
            }
1450

    
1451
            symbol.SPPID.RepresentationId = string.Empty;
1452
            symbol.SPPID.ModelItemID = string.Empty;
1453
            symbol.SPPID.SPPID_X = double.NaN;
1454
            symbol.SPPID.SPPID_Y = double.NaN;
1455
            symbol.SPPID.SPPID_Min_X = double.NaN;
1456
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1457
            symbol.SPPID.SPPID_Max_X = double.NaN;
1458
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1459
        }
1460

    
1461
        private void RemoveSymbol(List<Symbol> symbols)
1462
        {
1463
            foreach (var symbol in symbols)
1464
            {
1465
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1466
                {
1467
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1468
                    if (_LMSymbol != null)
1469
                    {
1470
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1471
                        ReleaseCOMObjects(_LMSymbol);
1472
                    }
1473
                }
1474

    
1475
                symbol.SPPID.RepresentationId = string.Empty;
1476
                symbol.SPPID.ModelItemID = string.Empty;
1477
                symbol.SPPID.SPPID_X = double.NaN;
1478
                symbol.SPPID.SPPID_Y = double.NaN;
1479
                symbol.SPPID.SPPID_Min_X = double.NaN;
1480
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1481
                symbol.SPPID.SPPID_Max_X = double.NaN;
1482
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1483
            }
1484
        }
1485

    
1486
        /// <summary>
1487
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1488
        /// </summary>
1489
        /// <param name="targetConnector"></param>
1490
        /// <param name="targetSymbol"></param>
1491
        /// <param name="x"></param>
1492
        /// <param name="y"></param>
1493
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1494
        {
1495
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1496

    
1497
            double[] range = null;
1498
            List<double[]> points = new List<double[]>();
1499
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1500
            double x1 = range[0];
1501
            double y1 = range[1];
1502
            double x2 = range[2];
1503
            double y2 = range[3];
1504

    
1505
            // Origin 기준 Connector의 위치차이
1506
            double sceneX = 0;
1507
            double sceneY = 0;
1508
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1509
            double originX = 0;
1510
            double originY = 0;
1511
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1512
            double gapX = originX - sceneX;
1513
            double gapY = originY - sceneY;
1514

    
1515
            // SPPID Symbol과 ID2 심볼의 크기 차이
1516
            double sizeWidth = 0;
1517
            double sizeHeight = 0;
1518
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1519
            if (sizeWidth == 0 || sizeHeight == 0)
1520
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1521

    
1522
            double percentX = (x2 - x1) / sizeWidth;
1523
            double percentY = (y2 - y1) / sizeHeight;
1524

    
1525
            double SPPIDgapX = gapX * percentX;
1526
            double SPPIDgapY = gapY * percentY;
1527

    
1528
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1529
            double distance = double.MaxValue;
1530
            double[] resultPoint;
1531
            foreach (var point in points)
1532
            {
1533
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1534
                if (distance > result)
1535
                {
1536
                    distance = result;
1537
                    resultPoint = point;
1538
                    x = point[0];
1539
                    y = point[1];
1540
                }
1541
            }
1542

    
1543
            ReleaseCOMObjects(_TargetItem);
1544
        }
1545

    
1546
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1547
        {
1548
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1549
            if (index == 0)
1550
            {
1551
                x = targetLine.SPPID.START_X;
1552
                y = targetLine.SPPID.START_Y;
1553
            }
1554
            else
1555
            {
1556
                x = targetLine.SPPID.END_X;
1557
                y = targetLine.SPPID.END_Y;
1558
            }
1559
        }
1560

    
1561
        /// <summary>
1562
        /// SPPID Symbol의 Range를 구한다.
1563
        /// </summary>
1564
        /// <param name="symbol"></param>
1565
        /// <param name="range"></param>
1566
        private void GetSPPIDSymbolRangeAndConnectionPoints(Symbol symbol, ref double[] range, List<double[]> points)
1567
        {
1568
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1569
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1570
            double x1 = 0;
1571
            double y1 = 0;
1572
            double x2 = 0;
1573
            double y2 = 0;
1574
            symbol2d.Range(out x1, out y1, out x2, out y2);
1575
            range = new double[] { x1, y1, x2, y2 };
1576
            
1577
            for (int i = 1; i < 30; i++)
1578
            {
1579
                double connX = 0;
1580
                double connY = 0;
1581
                if (_placement.PIDConnectPointLocation(_TargetItem, i, ref connX, ref connY))
1582
                    points.Add(new double[] { connX, connY });
1583
            }
1584

    
1585
            foreach (var childSymbol in symbol.ChildSymbols)
1586
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1587

    
1588
            ReleaseCOMObjects(_TargetItem);
1589
        }
1590

    
1591
        private void GetSPPIDSymbolRange(Symbol symbol, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1592
        {
1593
            LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1594
            if (_TargetItem != null)
1595
            {
1596
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1597
                double x1 = 0;
1598
                double y1 = 0;
1599
                double x2 = 0;
1600
                double y2 = 0;
1601
                if (!bForGraphic)
1602
                {
1603
                    symbol2d.Range(out x1, out y1, out x2, out y2);
1604
                    range = new double[] { x1, y1, x2, y2 };
1605
                }
1606
                else
1607
                {
1608
                    x1 = double.MaxValue;
1609
                    y1 = double.MaxValue;
1610
                    x2 = double.MinValue;
1611
                    y2 = double.MinValue;
1612
                    range = new double[] { x1, y1, x2, y2 };
1613

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

    
1675
                if (!bOnlySymbol)
1676
                {
1677
                    foreach (var childSymbol in symbol.ChildSymbols)
1678
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1679
                }
1680
                ReleaseCOMObjects(_TargetItem);
1681
            }
1682
        }
1683

    
1684
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1685
        {
1686
            if (labelPersist != null)
1687
            {
1688
                double x1 = double.MaxValue;
1689
                double y1 = double.MaxValue;
1690
                double x2 = double.MinValue;
1691
                double y2 = double.MinValue;
1692
                range = new double[] { x1, y1, x2, y2 };
1693

    
1694
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1695
                foreach (var item in dependency.DrawingObjects)
1696
                {
1697
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1698
                    if (textBox != null)
1699
                    {
1700
                        if (dependency != null)
1701
                        {
1702
                            double tempX1;
1703
                            double tempY1;
1704
                            double tempX2;
1705
                            double tempY2;
1706
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1707
                            x1 = Math.Min(x1, tempX1);
1708
                            y1 = Math.Min(y1, tempY1);
1709
                            x2 = Math.Max(x2, tempX2);
1710
                            y2 = Math.Max(y2, tempY2);
1711

    
1712
                            range = new double[] { x1, y1, x2, y2 };
1713
                        }
1714
                    }
1715
                }
1716
                
1717
            }
1718
        }
1719

    
1720
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1721
        {
1722
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1723
            foreach (var symbol in symbols)
1724
            {
1725
                double[] symbolRange = null;
1726
                GetSPPIDSymbolRange(symbol, ref symbolRange, bOnlySymbol, bForGraphic);
1727

    
1728
                tempRange[0] = Math.Min(tempRange[0], symbolRange[0]);
1729
                tempRange[1] = Math.Min(tempRange[1], symbolRange[1]);
1730
                tempRange[2] = Math.Max(tempRange[2], symbolRange[2]);
1731
                tempRange[3] = Math.Max(tempRange[3], symbolRange[3]);
1732

    
1733
                foreach (var childSymbol in symbol.ChildSymbols)
1734
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1735
            }
1736

    
1737
            range = tempRange;
1738
        }
1739

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

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

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

    
1774
                ReleaseCOMObjects(_ChildSymbol);
1775
            }
1776
        }
1777

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

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

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

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

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

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

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

    
1871
                                        if (result)
1872
                                            break;
1873
                                    }
1874

    
1875
                                    if (result)
1876
                                        break;
1877
                                }
1878
                            }
1879

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

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

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

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

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

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

    
1935
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1936

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

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

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

    
1989
            if (targetItem != null)
1990
            {
1991
                ReleaseCOMObjects(targetItem);
1992
            }
1993

    
1994
            ReleaseCOMObjects(_LMSymbol);
1995
        }
1996

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

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

    
2013
                ReleaseCOMObjects(symbol);
2014
                symbol = null;
2015
            }
2016
        }
2017

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2266

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

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

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

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

    
2360
                            placeRunInputs.AddPoint(x, y);
2361

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

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

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

    
2395
                    if (bRemodelingStart || bRemodelingEnd)
2396
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2397

    
2398
                    FlowMarkModeling(groupLine);
2399

    
2400
                    ReleaseCOMObjects(_lMConnector);
2401

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

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

    
2425
                foreach (var item in removeLines)
2426
                    RemoveLineForModeling(item as Line);
2427

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

    
2437
                if (isBranchModeling && BranchLines.Contains(groupLine))
2438
                    BranchLines.Remove(groupLine);
2439
            }
2440
        }
2441

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

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

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

    
2516
            return _lMConnector;
2517
        }
2518

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

    
2547
                ReleaseCOMObjects(modelItem);
2548
            }
2549
        }
2550

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

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

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

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

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

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

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

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

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

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

    
2683
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2684
        }
2685

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

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

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

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

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

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

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

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

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

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

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

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

    
2855
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2856
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2857

    
2858
            ReleaseCOMObjects(placeRunInputs);
2859
            ReleaseCOMObjects(_LMAItem);
2860
            ReleaseCOMObjects(modelItem);
2861

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

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

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

    
2907
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2908
                ReleaseCOMObjects(newConnector);
2909
            }
2910

    
2911
            ReleaseCOMObjects(modelItem);
2912
        }
2913

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

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

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

    
2969
                            if (child != null)
2970
                                break;
2971
                        }
2972

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

    
2977
                    break;
2978
                }
2979
            }
2980

    
2981
            return _LMSymbol;
2982
        }
2983

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

    
3000
            return null;
3001
        }
3002

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

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

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

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

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

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

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

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

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

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

    
3124
            return newConnector;
3125
        }
3126

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3310
            }
3311

    
3312
            return targetConnector;
3313
        }
3314

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

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

    
3361
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3362

    
3363
                    ReleaseCOMObjects(modelItem);
3364
                    ReleaseCOMObjects(connectedConnector);
3365

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

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

    
3422
            return result;
3423
        }
3424

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

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

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

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

    
3471
                    ReleaseCOMObjects(_LMConnector);
3472
                }
3473
            }
3474

    
3475

    
3476
            return result;
3477
        }
3478

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

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

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

    
3523
                    if (connectedConnector == null)
3524
                        ReleaseCOMObjects(_LMConnector);
3525
                }
3526
            }
3527
        }
3528

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

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

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

    
3569
                string beforeID = string.Empty;
3570
                string afterID = string.Empty;
3571

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

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

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

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

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

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

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

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

    
3666

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

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

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

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

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

    
3699

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

    
3721
            foreach (var connector in connectors)
3722
                ReleaseCOMObjects(connector);
3723
            
3724
            return result;
3725

    
3726

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

    
3735
                return findResult;
3736
            }
3737
        }
3738

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

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

    
3779
                ReleaseCOMObjects(modelItem);
3780
            }
3781

    
3782
            return connectorVertices;
3783
        }
3784

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

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

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

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

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

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

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

    
3935
            return targetConnector;
3936
        }
3937

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

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

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

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

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

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

    
3984
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3985

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

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

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

    
4032
                GridSetting gridSetting = GridSetting.GetInstance();
4033

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

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

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

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

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

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

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

    
4193
            x = resultPoint[0];
4194
            y = resultPoint[1];
4195

    
4196
            return targetConnector;
4197
        }
4198

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

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

    
4213
                ReleaseCOMObjects(modelItem);
4214
            }
4215

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

    
4222
            return result;
4223
        }
4224

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

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

    
4254
            return result;
4255
        }
4256

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

    
4272
            return result;
4273
        }
4274

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

    
4289
            return result;
4290
        }
4291

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

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

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

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

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

    
4336
                    GridSetting gridSetting = GridSetting.GetInstance();
4337
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4338

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

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

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

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

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

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

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

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

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

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

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

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

    
4481

    
4482
                    ReleaseCOMObjects(connector);
4483
                    connector = null;
4484
                }
4485

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

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

    
4531
                return 0;
4532
            }
4533

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

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

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

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

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

    
4676
                ReleaseCOMObjects(_Attributes);
4677
                ReleaseCOMObjects(_LMModelItem);
4678
                ReleaseCOMObjects(_LMSymbol);
4679
            }
4680
        }
4681

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

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

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

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

    
4719
                    ReleaseCOMObjects(targetLMConnector);
4720
                }
4721
            }
4722

    
4723

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4835
                    ReleaseCOMObjects(zeroLenthConnector);
4836
                    ReleaseCOMObjects(downStreamLMSymbol);
4837
                }
4838
            }
4839

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

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

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

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

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

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

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

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

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

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

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

    
5048
            LMItemNote _LMItemNote = null;
5049
            LMAAttribute _LMAAttribute = null;
5050

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

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

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

    
5075

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

    
5098
                        if (_LMAAttribute != null)
5099
                            ReleaseCOMObjects(_LMAAttribute);
5100
                        if (_LMItemNote != null)
5101
                            ReleaseCOMObjects(_LMItemNote);
5102
                    }
5103

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

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

    
5115
            LMItemNote _LMItemNote = null;
5116
            LMAAttribute _LMAAttribute = null;
5117

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

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

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

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

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

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

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

    
5201
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5202
                            if (_LMLabelPersist != null)
5203
                            {
5204
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5205
                                _LMLabelPersist.Commit();
5206
                               
5207
                                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_LMLabelPersist.get_GraphicOID().ToString()] as DependencyObject;
5208
                                if (dependency != null)
5209
                                {
5210
                                    radApp.ActiveSelectSet.RemoveAll();
5211
                                    radApp.ActiveSelectSet.Add(dependency);
5212
                                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
5213
                                    transform.DefineByMove2d(x - _LMLabelPersist.get_XCoordinate(), y - _LMLabelPersist.get_YCoordinate());
5214
                                    radApp.ActiveSelectSet.Transform(transform, true);
5215
                                    radApp.ActiveSelectSet.RemoveAll();
5216
                                }
5217

    
5218
                                ReleaseCOMObjects(_LMLabelPersist);
5219
                            }
5220
                        }
5221
                    }
5222
                }
5223
            }
5224
            if (_LMSymbol != null)
5225
                ReleaseCOMObjects(_LMSymbol);
5226
        }
5227

    
5228
        private void TextCorrectModeling(Text text)
5229
        {
5230
            if (text.SPPID.Range == null)
5231
                return;
5232

    
5233
            bool needRemodeling = false;
5234
            bool loop = true;
5235
            GridSetting gridSetting = GridSetting.GetInstance();
5236
            while (loop)
5237
            {
5238
                loop = false;
5239
                foreach (var overlapText in document.TEXTINFOS)
5240
                {
5241
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5242
                        continue;
5243

    
5244
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5245
                    {
5246
                        double percentX = 0;
5247
                        double percentY = 0;
5248
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
5249
                        {
5250
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
5251
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
5252
                        }
5253
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
5254
                        {
5255
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
5256
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
5257
                        }
5258

    
5259
                        double tempX = 0;
5260
                        double tempY = 0;
5261
                        bool overlapX = false;
5262
                        bool overlapY = false;
5263
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5264
                        if (percentX >= percentY)
5265
                        {
5266
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5267
                            double move = gridSetting.Length * count;
5268
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
5269
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
5270
                            needRemodeling = true;
5271
                            loop = true;
5272
                        }
5273
                        else
5274
                        {
5275
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5276
                            double move = gridSetting.Length * count;
5277
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
5278
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
5279
                            needRemodeling = true;
5280
                            loop = true;
5281
                        }
5282
                    }
5283
                }
5284
            }
5285
            
5286

    
5287
            if (needRemodeling)
5288
            {
5289
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
5290
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5291
                text.SPPID.RepresentationId = null;
5292

    
5293
                LMItemNote _LMItemNote = null;
5294
                LMAAttribute _LMAAttribute = null;
5295
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
5296
                if (_LMSymbol != null)
5297
                {
5298
                    _LMSymbol.Commit();
5299
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5300
                    if (_LMItemNote != null)
5301
                    {
5302
                        _LMItemNote.Commit();
5303
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5304
                        if (_LMAAttribute != null)
5305
                        {
5306
                            _LMAAttribute.set_Value(text.VALUE);
5307
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5308
                            _LMItemNote.Commit();
5309

    
5310
                            ReleaseCOMObjects(_LMAAttribute);
5311
                            ReleaseCOMObjects(_LMItemNote);
5312
                        }
5313
                    }
5314
                }
5315

    
5316
                ReleaseCOMObjects(symbol);
5317
                symbol = null;
5318
                ReleaseCOMObjects(_LMItemNote);
5319
                _LMItemNote = null;
5320
                ReleaseCOMObjects(_LMAAttribute);
5321
                _LMAAttribute = null;
5322
                ReleaseCOMObjects(_LMSymbol);
5323
                _LMSymbol = null;
5324
            }
5325
        }
5326

    
5327
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
5328
        {
5329
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
5330
            {
5331
                List<Text> allTexts = new List<Text>();
5332
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5333
                LMRepresentation representation = targetLabel.RepresentationObject;
5334
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
5335
                if (targetLabel.RepresentationObject != null && symbol != null)
5336
                {
5337
                    double[] symbolRange = null;
5338
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
5339
                    if (symbolRange != null)
5340
                    {
5341
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
5342
                        {
5343
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
5344
                            if (findText != null)
5345
                            {
5346
                                double[] range = null;
5347
                                GetSPPIDSymbolRange(labelPersist, ref range);
5348
                                findText.SPPID.Range = range;
5349
                                allTexts.Add(findText);
5350
                            }
5351

    
5352
                            ReleaseCOMObjects(labelPersist);
5353
                        }
5354

    
5355
                        if (allTexts.Count > 0)
5356
                        {
5357
                            #region Sort Text By Y
5358
                            allTexts.Sort(SortTextByY);
5359
                            int SortTextByY(Text a, Text b)
5360
                            {
5361
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
5362
                            }
5363
                            #endregion
5364

    
5365
                            #region 정렬하기전 방향
5366
                            List<Text> left = new List<Text>();
5367
                            List<Text> down = new List<Text>();
5368
                            List<Text> right = new List<Text>();
5369
                            List<Text> up = new List<Text>();
5370
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
5371
                            foreach (var loopText in allTexts)
5372
                            {
5373
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
5374
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
5375
                                double originX = 0;
5376
                                double originY = 0;
5377
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5378
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5379

    
5380
                                if (angle < 45)
5381
                                {
5382
                                    // Text 오른쪽
5383
                                    if (textCenterX > originX)
5384
                                        right.Add(loopText);
5385
                                    // Text 왼쪽
5386
                                    else
5387
                                        left.Add(loopText); 
5388
                                }
5389
                                else
5390
                                {
5391
                                    // Text 아래쪽
5392
                                    if (textCenterY > originY)
5393
                                        down.Add(loopText);
5394
                                    // Text 위쪽
5395
                                    else
5396
                                        up.Add(loopText);
5397
                                }
5398
                            }
5399
                            
5400
                            #endregion
5401

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

    
5444
                                double gapX = 0;
5445
                                double gapY = 0;
5446
                                if (angle < 45)
5447
                                {
5448
                                    // Text 오른쪽
5449
                                    if (textCenterX > originX)
5450
                                    {
5451
                                        gapX = rangeMinX[0] - symbolRange[2];
5452
                                        gapY = allTextCenterY - symbolCenterY;
5453
                                    }
5454
                                    // Text 왼쪽
5455
                                    else
5456
                                    {
5457
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
5458
                                        gapY = allTextCenterY - symbolCenterY;
5459
                                    }
5460
                                }
5461
                                else
5462
                                {
5463
                                    // Text 아래쪽
5464
                                    if (textCenterY > originY)
5465
                                    {
5466
                                        gapX = allTextCenterX - symbolCenterX;
5467
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
5468
                                    }
5469
                                    // Text 위쪽
5470
                                    else
5471
                                    {
5472
                                        gapX = allTextCenterX - symbolCenterX;
5473
                                        gapY = rangeMinY[0] - symbolRange[3];
5474
                                    }
5475
                                }
5476

    
5477
                                foreach (var item in texts)
5478
                                {
5479
                                    MoveText(item, gapX, gapY);
5480
                                    RemodelingAssociationText(item);
5481
                                }
5482
                                #endregion
5483
                            }
5484
                        }
5485
                    }
5486
                }
5487

    
5488
                void MoveText(Text moveText, double x, double y)
5489
                {
5490
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
5491
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
5492
                    moveText.SPPID.Range = new double[] {
5493
                        moveText.SPPID.Range[0] - x,
5494
                        moveText.SPPID.Range[1]- y,
5495
                        moveText.SPPID.Range[2]- x,
5496
                        moveText.SPPID.Range[3]- y
5497
                    };
5498
                }
5499

    
5500
                endTexts.AddRange(allTexts);
5501

    
5502
                ReleaseCOMObjects(targetLabel);
5503
                targetLabel = null;
5504
                ReleaseCOMObjects(representation);
5505
                representation = null;
5506
            }
5507
        }
5508

    
5509
        private void RemodelingAssociationText(Text text)
5510
        {
5511
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5512
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5513
            removeLabel.Commit();
5514
            ReleaseCOMObjects(removeLabel);
5515
            removeLabel = null;
5516

    
5517
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5518
            if (owner != null && owner.GetType() == typeof(Symbol))
5519
            {
5520
                Symbol symbol = owner as Symbol;
5521
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5522
                if (_LMSymbol != null)
5523
                {
5524
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5525
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5526
                    {
5527
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5528

    
5529
                        if (mapping != null)
5530
                        {
5531
                            double x = 0;
5532
                            double y = 0;
5533

    
5534
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5535
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5536
                            if (_LMLabelPersist != null)
5537
                            {
5538
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5539
                                _LMLabelPersist.Commit();
5540
                            }
5541
                            ReleaseCOMObjects(_LMLabelPersist);
5542
                            _LMLabelPersist = null;
5543
                        }
5544
                    }
5545
                }
5546
                ReleaseCOMObjects(_LMSymbol);
5547
                _LMSymbol = null;
5548
            }
5549
        }
5550

    
5551
        /// <summary>
5552
        /// Note Modeling
5553
        /// </summary>
5554
        /// <param name="note"></param>
5555
        private void NoteModeling(Note note, List<Note> correctList)
5556
        {
5557
            LMSymbol _LMSymbol = null;
5558
            LMItemNote _LMItemNote = null;
5559
            LMAAttribute _LMAAttribute = null;
5560

    
5561
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5562
            {
5563
                double x = 0;
5564
                double y = 0;
5565

    
5566
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5567
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5568
                note.SPPID.SPPID_X = x;
5569
                note.SPPID.SPPID_Y = y;
5570

    
5571
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5572
                if (_LMSymbol != null)
5573
                {
5574
                    _LMSymbol.Commit();
5575
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5576
                    if (_LMItemNote != null)
5577
                    {
5578
                        _LMItemNote.Commit();
5579
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5580
                        if (_LMAAttribute != null)
5581
                        {
5582
                            _LMAAttribute.set_Value(note.VALUE);
5583
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5584

    
5585
                            double[] range = null;
5586
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5587
                            {
5588
                                double[] temp = null;
5589
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5590
                                if (temp != null)
5591
                                {
5592
                                    if (range == null)
5593
                                        range = temp;
5594
                                    else
5595
                                    {
5596
                                        range = new double[] {
5597
                                            Math.Min(range[0], temp[0]),
5598
                                            Math.Min(range[1], temp[1]),
5599
                                            Math.Max(range[2], temp[2]),
5600
                                            Math.Max(range[3], temp[3])
5601
                                        };
5602
                                    }
5603
                                }
5604
                            }
5605
                            if (range != null)
5606
                                correctList.Add(note);
5607
                            note.SPPID.Range = range;
5608

    
5609

    
5610
                            _LMItemNote.Commit();
5611
                        }
5612
                    }
5613
                }
5614
            }
5615

    
5616
            if (_LMAAttribute != null)
5617
                ReleaseCOMObjects(_LMAAttribute);
5618
            if (_LMItemNote != null)
5619
                ReleaseCOMObjects(_LMItemNote);
5620
            if (_LMSymbol != null)
5621
                ReleaseCOMObjects(_LMSymbol);
5622
        }
5623

    
5624
        private void NoteCorrectModeling(Note note, List<Note> endList)
5625
        {
5626
            bool needRemodeling = false;
5627
            bool loop = true;
5628
            GridSetting gridSetting = GridSetting.GetInstance();
5629
            while (loop)
5630
            {
5631
                loop = false;
5632
                foreach (var overlap in endList)
5633
                {
5634
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5635
                    {
5636
                        double tempX = 0;
5637
                        double tempY = 0;
5638
                        bool overlapX = false;
5639
                        bool overlapY = false;
5640
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5641
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5642
                        if (overlapY && angle >= 45)
5643
                        {
5644
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5645
                            double move = gridSetting.Length * count;
5646
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5647
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5648
                            needRemodeling = true;
5649
                            loop = true;
5650
                        }
5651
                        if (overlapX && angle <= 45)
5652
                        {
5653
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5654
                            double move = gridSetting.Length * count;
5655
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5656
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5657
                            needRemodeling = true;
5658
                            loop = true;
5659
                        }
5660
                    }
5661
                }
5662
            }
5663

    
5664

    
5665
            if (needRemodeling)
5666
            {
5667
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5668
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5669
                note.SPPID.RepresentationId = null;
5670

    
5671
                LMItemNote _LMItemNote = null;
5672
                LMAAttribute _LMAAttribute = null;
5673
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5674
                if (_LMSymbol != null)
5675
                {
5676
                    _LMSymbol.Commit();
5677
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5678
                    if (_LMItemNote != null)
5679
                    {
5680
                        _LMItemNote.Commit();
5681
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5682
                        if (_LMAAttribute != null)
5683
                        {
5684
                            _LMAAttribute.set_Value(note.VALUE);
5685
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5686
                            _LMItemNote.Commit();
5687

    
5688
                            ReleaseCOMObjects(_LMAAttribute);
5689
                            ReleaseCOMObjects(_LMItemNote);
5690
                        }
5691
                    }
5692
                }
5693

    
5694
                ReleaseCOMObjects(symbol);
5695
                symbol = null;
5696
                ReleaseCOMObjects(_LMItemNote);
5697
                _LMItemNote = null;
5698
                ReleaseCOMObjects(_LMAAttribute);
5699
                _LMAAttribute = null;
5700
                ReleaseCOMObjects(_LMSymbol);
5701
                _LMSymbol = null;
5702
            }
5703

    
5704
            endList.Add(note);
5705
        }
5706

    
5707
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5708
        {
5709
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5710
            if (modelItem != null)
5711
            {
5712
                foreach (LMRepresentation rep in modelItem.Representations)
5713
                {
5714
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5715
                    {
5716
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5717
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5718
                        {
5719
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5720
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5721
                            if (modelItemIds.Count == 1)
5722
                            {
5723
                                string joinModelItemId = modelItemIds[0];
5724
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5725
                                if (survivorId != null)
5726
                                    break;
5727
                            }
5728
                        }
5729
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5730
                        {
5731
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5732
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5733
                            if (modelItemIds.Count == 1)
5734
                            {
5735
                                string joinModelItemId = modelItemIds[0];
5736
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5737
                                if (survivorId != null)
5738
                                    break;
5739
                            }
5740
                        }
5741
                    }
5742
                }
5743
            }
5744
        }
5745

    
5746
        /// <summary>
5747
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5748
        /// </summary>
5749
        /// <param name="x"></param>
5750
        /// <param name="y"></param>
5751
        /// <param name="originX"></param>
5752
        /// <param name="originY"></param>
5753
        /// <param name="SPPIDLabelLocation"></param>
5754
        /// <param name="location"></param>
5755
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5756
        {
5757
            if (location == Location.None)
5758
            {
5759
                x = originX;
5760
                y = originY;
5761
            }
5762
            else
5763
            {
5764
                if (location.HasFlag(Location.Center))
5765
                {
5766
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5767
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5768
                }
5769

    
5770
                if (location.HasFlag(Location.Left))
5771
                    x = SPPIDLabelLocation.X1;
5772
                else if (location.HasFlag(Location.Right))
5773
                    x = SPPIDLabelLocation.X2;
5774

    
5775
                if (location.HasFlag(Location.Down))
5776
                    y = SPPIDLabelLocation.Y1;
5777
                else if (location.HasFlag(Location.Up))
5778
                    y = SPPIDLabelLocation.Y2;
5779
            }
5780
        }
5781

    
5782
        /// <summary>
5783
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5784
        /// 1. Angle Valve
5785
        /// 2. 3개로 이루어진 Symbol Group
5786
        /// </summary>
5787
        /// <returns></returns>
5788
        private List<Symbol> GetPrioritySymbol()
5789
        {
5790
            DataTable symbolTable = document.SymbolTable;
5791
            // List에 순서대로 쌓는다.
5792
            List<Symbol> symbols = new List<Symbol>();
5793

    
5794
            // Angle Valve 부터
5795
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5796
            {
5797
                if (!symbols.Contains(symbol))
5798
                {
5799
                    double originX = 0;
5800
                    double originY = 0;
5801

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

    
5806
                    SlopeType slopeType1 = SlopeType.None;
5807
                    SlopeType slopeType2 = SlopeType.None;
5808
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5809
                    {
5810
                        double connectorX = 0;
5811
                        double connectorY = 0;
5812
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5813
                        if (slopeType1 == SlopeType.None)
5814
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5815
                        else
5816
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5817
                    }
5818

    
5819
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5820
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5821
                        symbols.Add(symbol);
5822
                }
5823
            }
5824

    
5825
            List<Symbol> tempSymbols = new List<Symbol>();
5826
            // Conn 갯수 기준
5827
            foreach (var item in document.SYMBOLS)
5828
            {
5829
                if (!symbols.Contains(item))
5830
                    tempSymbols.Add(item);
5831
            }
5832
            tempSymbols.Sort(SortSymbolPriority);
5833
            symbols.AddRange(tempSymbols);
5834

    
5835
            return symbols;
5836
        }
5837

    
5838
        private void SetPriorityLine(List<Line> lines)
5839
        {
5840
            lines.Sort(SortLinePriority);
5841

    
5842
            int SortLinePriority(Line a, Line b)
5843
            {
5844
                // Branch 없는것부터
5845
                int branchRetval = CompareBranchLine(a, b);
5846
                if (branchRetval != 0)
5847
                {
5848
                    return branchRetval;
5849
                }
5850
                else
5851
                {
5852
                    // Symbol 연결 갯수
5853
                    int connSymbolRetval = CompareConnSymbol(a, b);
5854
                    if (connSymbolRetval != 0)
5855
                    {
5856
                        return connSymbolRetval;
5857
                    }
5858
                    else
5859
                    {
5860
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5861
                        int connItemRetval = CompareConnItem(a, b);
5862
                        if (connItemRetval != 0)
5863
                        {
5864
                            return connItemRetval;
5865
                        }
5866
                        else
5867
                        {
5868
                            // ConnectedItem이 없는것
5869
                            int noneConnRetval = CompareNoneConn(a, b);
5870
                            if (noneConnRetval != 0)
5871
                            {
5872
                                return noneConnRetval;
5873
                            }
5874
                            else
5875
                            {
5876

    
5877
                            }
5878
                        }
5879
                    }
5880
                }
5881

    
5882
                return 0;
5883
            }
5884

    
5885
            int CompareNotSegmentLine(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 CompareConnSymbol(Line a, Line b)
5900
            {
5901
                List<Connector> connectorsA = a.CONNECTORS
5902
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5903
                    .ToList();
5904

    
5905
                List<Connector> connectorsB = b.CONNECTORS
5906
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5907
                    .ToList();
5908

    
5909
                // 오름차순
5910
                return connectorsB.Count.CompareTo(connectorsA.Count);
5911
            }
5912

    
5913
            int CompareConnItem(Line a, Line b)
5914
            {
5915
                List<Connector> connectorsA = a.CONNECTORS
5916
                    .Where(conn => conn.ConnectedObject != null && 
5917
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5918
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5919
                    .ToList();
5920

    
5921
                List<Connector> connectorsB = b.CONNECTORS
5922
                    .Where(conn => conn.ConnectedObject != null &&
5923
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5924
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5925
                    .ToList();
5926

    
5927
                // 오름차순
5928
                return connectorsB.Count.CompareTo(connectorsA.Count);
5929
            }
5930

    
5931
            int CompareBranchLine(Line a, Line b)
5932
            {
5933
                List<Connector> connectorsA = a.CONNECTORS
5934
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5935
                    .ToList();
5936
                List<Connector> connectorsB = b.CONNECTORS
5937
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5938
                    .ToList();
5939

    
5940
                // 내림차순
5941
                return connectorsA.Count.CompareTo(connectorsB.Count);
5942
            }
5943

    
5944
            int CompareNoneConn(Line a, Line b)
5945
            {
5946
                List<Connector> connectorsA = a.CONNECTORS
5947
                    .Where(conn => conn.ConnectedObject == null)
5948
                    .ToList();
5949

    
5950
                List<Connector> connectorsB = b.CONNECTORS
5951
                    .Where(conn => conn.ConnectedObject == null)
5952
                    .ToList();
5953

    
5954
                // 오름차순
5955
                return connectorsB.Count.CompareTo(connectorsA.Count);
5956
            }
5957
        }
5958

    
5959
        private void SortText(List<Text> texts)
5960
        {
5961
            texts.Sort(Sort);
5962

    
5963
            int Sort(Text a, Text b)
5964
            {
5965
                int yRetval = CompareY(a, b);
5966
                if (yRetval != 0)
5967
                {
5968
                    return yRetval;
5969
                }
5970
                else
5971
                {
5972
                    return CompareX(a, b);
5973
                }
5974
            }
5975

    
5976
            int CompareY(Text a, Text b)
5977
            {
5978
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5979
            }
5980

    
5981
            int CompareX(Text a, Text b)
5982
            {
5983
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5984
            }
5985
        }
5986
        private void SortNote(List<Note> notes)
5987
        {
5988
            notes.Sort(Sort);
5989

    
5990
            int Sort(Note a, Note b)
5991
            {
5992
                int yRetval = CompareY(a, b);
5993
                if (yRetval != 0)
5994
                {
5995
                    return yRetval;
5996
                }
5997
                else
5998
                {
5999
                    return CompareX(a, b);
6000
                }
6001
            }
6002

    
6003
            int CompareY(Note a, Note b)
6004
            {
6005
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6006
            }
6007

    
6008
            int CompareX(Note a, Note b)
6009
            {
6010
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6011
            }
6012
        }
6013

    
6014
        private void SortBranchLines()
6015
        {
6016
            BranchLines.Sort(SortBranchLine);
6017
            int SortBranchLine(Line a, Line b)
6018
            {
6019
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6020
                 x.ConnectedObject.GetType() == typeof(Line) &&
6021
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
6022
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6023

    
6024
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6025
                 x.ConnectedObject.GetType() == typeof(Line) &&
6026
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
6027
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6028

    
6029
                // 내림차순
6030
                return countA.CompareTo(countB);
6031
            }
6032
        }
6033

    
6034
        private static int SortSymbolPriority(Symbol a, Symbol b)
6035
        {
6036
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6037
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6038
            int retval = countB.CompareTo(countA);
6039
            if (retval != 0)
6040
                return retval;
6041
            else
6042
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
6043
        }
6044

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

    
6059
        private string GetSPPIDFileName(string modelItemId)
6060
        {
6061
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6062
            string symbolPath = null;
6063
            foreach (LMRepresentation rep in modelItem.Representations)
6064
            {
6065
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6066
                {
6067
                    symbolPath = rep.get_FileName();
6068
                    break;
6069
                }
6070
            }
6071
            ReleaseCOMObjects(modelItem);
6072
            return symbolPath;
6073
        }
6074

    
6075
        /// <summary>
6076
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
6077
        /// </summary>
6078
        /// <param name="graphicOID"></param>
6079
        /// <param name="milliseconds"></param>
6080
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
6081
        {
6082
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
6083
            {
6084
                double minX = 0;
6085
                double minY = 0;
6086
                double maxX = 0;
6087
                double maxY = 0;
6088
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
6089
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
6090

    
6091
                Thread.Sleep(milliseconds);
6092
            }
6093
        }
6094

    
6095
        /// <summary>
6096
        /// ComObject를 Release
6097
        /// </summary>
6098
        /// <param name="objVars"></param>
6099
        public void ReleaseCOMObjects(params object[] objVars)
6100
        {
6101
            if (objVars != null)
6102
            {
6103
                int intNewRefCount = 0;
6104
                foreach (object obj in objVars)
6105
                {
6106
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
6107
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
6108
                }
6109
            }
6110
        }
6111

    
6112
        /// IDisposable 구현
6113
        ~AutoModeling()
6114
        {
6115
            this.Dispose(false);
6116
        }
6117

    
6118
        private bool disposed;
6119
        public void Dispose()
6120
        {
6121
            this.Dispose(true);
6122
            GC.SuppressFinalize(this);
6123
        }
6124

    
6125
        protected virtual void Dispose(bool disposing)
6126
        {
6127
            if (this.disposed) return;
6128
            if (disposing)
6129
            {
6130
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
6131
            }
6132
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
6133
            this.disposed = true;
6134
        }
6135
    }
6136
}
클립보드 이미지 추가 (최대 크기: 500 MB)