프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ 27e624cd

이력 | 보기 | 이력해설 | 다운로드 (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 < int.MaxValue; 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
                else
1584
                    break;
1585
            }
1586

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

    
1590
            ReleaseCOMObjects(_TargetItem);
1591
        }
1592

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

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

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

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

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

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

    
1722
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range)
1723
        {
1724
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1725
            foreach (var symbol in symbols)
1726
            {
1727
                LMSymbol _TargetItem = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1728
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_TargetItem.get_GraphicOID().ToString()];
1729
                double x1 = 0;
1730
                double y1 = 0;
1731
                double x2 = 0;
1732
                double y2 = 0;
1733
                symbol2d.Range(out x1, out y1, out x2, out y2);
1734

    
1735
                tempRange[0] = Math.Min(tempRange[0], x1);
1736
                tempRange[1] = Math.Min(tempRange[1], y1);
1737
                tempRange[2] = Math.Max(tempRange[2], x2);
1738
                tempRange[3] = Math.Max(tempRange[3], y2);
1739

    
1740
                foreach (var childSymbol in symbol.ChildSymbols)
1741
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
1742

    
1743
                ReleaseCOMObjects(_TargetItem);
1744
            }
1745

    
1746
            range = tempRange;
1747
        }
1748

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

    
1770
                for (int i = 1; i < int.MaxValue; i++)
1771
                {
1772
                    double connX = 0;
1773
                    double connY = 0;
1774
                    if (_placement.PIDConnectPointLocation(_ChildSymbol, i, ref connX, ref connY))
1775
                        points.Add(new double[] { connX, connY });
1776
                    else
1777
                        break;
1778
                }
1779

    
1780
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1781
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range, points);
1782

    
1783
                ReleaseCOMObjects(_ChildSymbol);
1784
            }
1785
        }
1786

    
1787
        private void GetSPPIDChildSymbolRange(ChildSymbol childSymbol, ref double[] range)
1788
        {
1789
            LMSymbol _ChildSymbol = dataSource.GetSymbol(childSymbol.SPPID.RepresentationId);
1790
            if (_ChildSymbol != null)
1791
            {
1792
                Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_ChildSymbol.get_GraphicOID().ToString()];
1793
                double x1 = 0;
1794
                double y1 = 0;
1795
                double x2 = 0;
1796
                double y2 = 0;
1797
                symbol2d.Range(out x1, out y1, out x2, out y2);
1798
                range[0] = Math.Min(range[0], x1);
1799
                range[1] = Math.Min(range[1], y1);
1800
                range[2] = Math.Max(range[2], x2);
1801
                range[3] = Math.Max(range[3], y2);
1802

    
1803
                foreach (var loopChildSymbol in childSymbol.ChildSymbols)
1804
                    GetSPPIDChildSymbolRange(loopChildSymbol, ref range);
1805
                ReleaseCOMObjects(_ChildSymbol);
1806
            }
1807
        }
1808

    
1809
        /// <summary>
1810
        /// Label Symbol Modeling
1811
        /// </summary>
1812
        /// <param name="symbol"></param>
1813
        private void LabelSymbolModeling(Symbol symbol)
1814
        {
1815
            if (string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1816
            {
1817
                BaseModel.Attribute itemAttribute = symbol.ATTRIBUTES.Find(x => x.ATTRIBUTE == "OWNERSYMBOL");
1818
                if (itemAttribute == null || string.IsNullOrEmpty(itemAttribute.VALUE) || itemAttribute.VALUE == "None")
1819
                    return;
1820
                Array points = new double[] { 0, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y };
1821

    
1822
                string symbolUID = itemAttribute.VALUE;
1823
                object targetItem = SPPIDUtil.FindObjectByUID(document, symbolUID);
1824
                if (targetItem != null &&
1825
                    (targetItem.GetType() == typeof(Symbol) ||
1826
                    targetItem.GetType() == typeof(Equipment)))
1827
                {
1828
                    // Object 아이템이 Symbol일 경우 Equipment일 경우 
1829
                    string sRep = null;
1830
                    if (targetItem.GetType() == typeof(Symbol))
1831
                        sRep = ((Symbol)targetItem).SPPID.RepresentationId;
1832
                    else if (targetItem.GetType() == typeof(Equipment))
1833
                        sRep = ((Equipment)targetItem).SPPID.RepresentationId;
1834
                    if (!string.IsNullOrEmpty(sRep))
1835
                    {
1836
                        // LEADER Line 검사
1837
                        bool leaderLine = false;
1838
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1839
                        if (symbolMapping != null)
1840
                            leaderLine = symbolMapping.LEADERLINE;
1841

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

    
1846
                        //Leader 선 센터로
1847
                        if (_LMLabelPresist != null)
1848
                        {
1849
                            // Target Item에 Label의 Attribute Input
1850
                            InputSymbolAttribute(targetItem, symbol.ATTRIBUTES);
1851

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

    
1880
                                        if (result)
1881
                                            break;
1882
                                    }
1883

    
1884
                                    if (result)
1885
                                        break;
1886
                                }
1887
                            }
1888

    
1889
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1890
                            _LMLabelPresist.Commit();
1891
                            ReleaseCOMObjects(_LMLabelPresist);
1892
                        }
1893

    
1894
                        ReleaseCOMObjects(_TargetItem);
1895
                    }
1896
                }
1897
                else if (targetItem != null && targetItem.GetType() == typeof(Line))
1898
                {
1899
                    Line targetLine = targetItem as Line;
1900
                    Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
1901
                    LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, symbol.SPPID.ORIGINAL_X, symbol.SPPID.ORIGINAL_Y);
1902
                    if (connectedLMConnector != null)
1903
                    {
1904
                        // LEADER Line 검사
1905
                        bool leaderLine = false;
1906
                        SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == symbol.DBUID);
1907
                        if (symbolMapping != null)
1908
                            leaderLine = symbolMapping.LEADERLINE;
1909

    
1910
                        LMLabelPersist _LMLabelPresist = _placement.PIDPlaceLabel(symbol.SPPID.MAPPINGNAME, ref points, Rotation: 0, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
1911
                        if (_LMLabelPresist != null)
1912
                        {
1913
                            symbol.SPPID.RepresentationId = _LMLabelPresist.AsLMRepresentation().Id;
1914
                            _LMLabelPresist.Commit();
1915
                            ReleaseCOMObjects(_LMLabelPresist);
1916
                        }
1917
                        ReleaseCOMObjects(connectedLMConnector);
1918
                    }
1919

    
1920
                    foreach (var item in connectorVertices)
1921
                        if (item.Key != null)
1922
                            ReleaseCOMObjects(item.Key);
1923
                }
1924
            }
1925
        }
1926

    
1927
        /// <summary>
1928
        /// Equipment를 실제로 Modeling 메서드
1929
        /// </summary>
1930
        /// <param name="equipment"></param>
1931
        private void EquipmentModeling(Equipment equipment)
1932
        {
1933
            if (!string.IsNullOrEmpty(equipment.SPPID.RepresentationId))
1934
                return;
1935

    
1936
            LMSymbol _LMSymbol = null;
1937
            LMSymbol targetItem = null;
1938
            string mappingPath = equipment.SPPID.MAPPINGNAME;
1939
            double x = equipment.SPPID.ORIGINAL_X;
1940
            double y = equipment.SPPID.ORIGINAL_Y;
1941
            int mirror = 0;
1942
            double angle = equipment.ANGLE;
1943

    
1944
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
1945

    
1946
            Connector connector = equipment.CONNECTORS.Find(conn => !string.IsNullOrEmpty(conn.CONNECTEDITEM) && conn.CONNECTEDITEM != "None");
1947
            if (connector != null)
1948
            {
1949
                Equipment connEquipment = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as Equipment;
1950
                VendorPackage connVendorPackage = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM) as VendorPackage;
1951
                if (connEquipment != null)
1952
                {
1953
                    if (string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1954
                        EquipmentModeling(connEquipment);
1955

    
1956
                    if (!string.IsNullOrEmpty(connEquipment.SPPID.RepresentationId))
1957
                    {
1958
                        targetItem = dataSource.GetSymbol(connEquipment.SPPID.RepresentationId);
1959
                        if (targetItem != null)
1960
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1961
                        else
1962
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1963
                    }
1964
                    else
1965
                    {
1966
                        _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1967
                    }
1968
                }
1969
                else if (connVendorPackage != null)
1970
                {
1971
                    if (!string.IsNullOrEmpty(connVendorPackage.SPPID.RepresentationId))
1972
                    {
1973
                        targetItem = dataSource.GetSymbol(connVendorPackage.SPPID.RepresentationId);
1974
                        if (targetItem != null)
1975
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: targetItem);
1976
                        else
1977
                            _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1978
                    }
1979
                }
1980
                else
1981
                {
1982
                    _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1983
                }
1984
            }
1985
            else
1986
            {
1987
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1988
            }
1989

    
1990
            if (_LMSymbol != null)
1991
            {
1992
                _LMSymbol.Commit();
1993
                equipment.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1994
                equipment.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1995
                ReleaseCOMObjects(_LMSymbol);
1996
            }
1997

    
1998
            if (targetItem != null)
1999
            {
2000
                ReleaseCOMObjects(targetItem);
2001
            }
2002

    
2003
            ReleaseCOMObjects(_LMSymbol);
2004
        }
2005

    
2006
        private void VendorPackageModeling(VendorPackage vendorPackage)
2007
        {
2008
            ETCSetting setting = ETCSetting.GetInstance();
2009
            if (!string.IsNullOrEmpty(setting.VendorPackageSymbolPath))
2010
            {
2011
                string symbolPath = setting.VendorPackageSymbolPath;
2012
                double x = vendorPackage.SPPID.ORIGINAL_X;
2013
                double y = vendorPackage.SPPID.ORIGINAL_Y;
2014

    
2015
                LMSymbol symbol = _placement.PIDPlaceSymbol(symbolPath, x, y);
2016
                if (symbol != null)
2017
                {
2018
                    symbol.Commit();
2019
                    vendorPackage.SPPID.RepresentationId = symbol.AsLMRepresentation().Id;
2020
                }
2021

    
2022
                ReleaseCOMObjects(symbol);
2023
                symbol = null;
2024
            }
2025
        }
2026

    
2027
        /// <summary>
2028
        /// 첫 진입점
2029
        /// </summary>
2030
        /// <param name="symbol"></param>
2031
        private void SymbolModelingBySymbol(Symbol symbol)
2032
        {
2033
            SymbolModeling(symbol, null);   /// 심볼을 생성한다
2034
            List<object> endObjects = new List<object>();
2035
            endObjects.Add(symbol);
2036

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

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

    
2093
        private void SymbolModelingByNeerLineLoop(Line line, List<object> endObjects, Symbol prevSymbol)
2094
        {
2095
            foreach (var connector in line.CONNECTORS)
2096
            {
2097
                object connItem = SPPIDUtil.FindObjectByUID(document, connector.CONNECTEDITEM);
2098
                if (connItem != null && connItem.GetType() != typeof(Equipment))
2099
                {
2100
                    if (!endObjects.Contains(connItem))
2101
                    {
2102
                        endObjects.Add(connItem);
2103
                        if (connItem.GetType() == typeof(Symbol))
2104
                        {
2105
                            Symbol connSymbol = connItem as Symbol;
2106
                            if (string.IsNullOrEmpty(connSymbol.SPPID.RepresentationId))
2107
                            {
2108
                                Line connLine = SPPIDUtil.GetConnectedLine(prevSymbol, connSymbol);
2109
                                int branchCount = 0;
2110
                                if (connLine != null)
2111
                                    branchCount = SPPIDUtil.GetBranchLineCount(document, connLine);
2112

    
2113
                                List<Symbol> group = new List<Symbol>();
2114
                                SPPIDUtil.FindConnectedSymbolGroup(document, connSymbol, group);
2115
                                Symbol priority = prioritySymbols.Find(x => group.Contains(x));
2116
                                List<Symbol> endModelingGroup = new List<Symbol>();
2117
                                if (priority != null)
2118
                                {
2119
                                    SymbolGroupModeling(priority, group);
2120

    
2121
                                    // Range 겹치는지 확인해야함
2122
                                    double[] prevRange = null;
2123
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2124
                                    double[] groupRange = null;
2125
                                    GetSPPIDSymbolRange(group, ref groupRange);
2126

    
2127
                                    double distanceX = 0;
2128
                                    double distanceY = 0;
2129
                                    bool overlapX = false;
2130
                                    bool overlapY = false;
2131
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2132
                                    SPPIDUtil.CalcOverlap(prevRange, groupRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2133
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2134
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2135
                                    {
2136
                                        RemoveSymbol(group);
2137
                                        foreach (var _temp in group)
2138
                                            SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, distanceX, distanceY);
2139

    
2140
                                        SymbolGroupModeling(priority, group);
2141
                                    }
2142
                                    else if (branchCount > 0)
2143
                                    {
2144
                                        LMConnector _connector = JustLineModeling(connLine);
2145
                                        if (_connector != null)
2146
                                        {
2147
                                            double distance = GetConnectorDistance(_connector);
2148
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2149
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2150
                                            _connector.Commit();
2151
                                            ReleaseCOMObjects(_connector);
2152
                                            _connector = null;
2153
                                            if (cellCount < branchCount + 1)
2154
                                            {
2155
                                                int moveCount = branchCount - cellCount;
2156
                                                RemoveSymbol(group);
2157
                                                foreach (var _temp in group)
2158
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2159

    
2160
                                                SymbolGroupModeling(priority, group);
2161
                                            }
2162
                                        }
2163
                                    }
2164
                                }
2165
                                else
2166
                                {
2167
                                    SymbolModeling(connSymbol, null);
2168
                                    // Range 겹치는지 확인해야함
2169
                                    double[] prevRange = null;
2170
                                    GetSPPIDSymbolRange(prevSymbol, ref prevRange);
2171
                                    double[] connRange = null;
2172
                                    GetSPPIDSymbolRange(connSymbol, ref connRange);
2173

    
2174
                                    double distanceX = 0;
2175
                                    double distanceY = 0;
2176
                                    bool overlapX = false;
2177
                                    bool overlapY = false;
2178
                                    SlopeType slopeType = SPPIDUtil.CalcSlope(prevSymbol.SPPID.ORIGINAL_X, prevSymbol.SPPID.ORIGINAL_Y, connSymbol.SPPID.ORIGINAL_X, connSymbol.SPPID.ORIGINAL_Y);
2179
                                    SPPIDUtil.CalcOverlap(prevRange, connRange, ref distanceX, ref distanceY, ref overlapX, ref overlapY);
2180
                                    if ((slopeType == SlopeType.HORIZONTAL && overlapX) ||
2181
                                        (slopeType == SlopeType.VERTICAL && overlapY))
2182
                                    {
2183
                                        RemoveSymbol(connSymbol);
2184
                                        SPPIDUtil.CalcNewCoordinateForSymbol(connSymbol, prevSymbol, distanceX, distanceY);
2185

    
2186
                                        SymbolModeling(connSymbol, null);
2187
                                    }
2188
                                    else if (branchCount > 0)
2189
                                    {
2190
                                        LMConnector _connector = JustLineModeling(connLine);
2191
                                        if (_connector != null)
2192
                                        {
2193
                                            double distance = GetConnectorDistance(_connector);
2194
                                            int cellCount = (int)Math.Truncate(distance / GridSetting.GetInstance().Length);
2195
                                            _placement.PIDRemovePlacement(_connector.AsLMRepresentation());
2196
                                            _connector.Commit();
2197
                                            ReleaseCOMObjects(_connector);
2198
                                            _connector = null;
2199
                                            if (cellCount < branchCount + 1)
2200
                                            {
2201
                                                int moveCount = branchCount - cellCount;
2202
                                                RemoveSymbol(group);
2203
                                                foreach (var _temp in group)
2204
                                                    SPPIDUtil.CalcNewCoordinateForSymbol(_temp, prevSymbol, moveCount * GridSetting.GetInstance().Length, moveCount * GridSetting.GetInstance().Length);
2205

    
2206
                                                SymbolGroupModeling(priority, group);
2207
                                            }
2208
                                        }
2209
                                    }
2210
                                }
2211
                            }
2212
                            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetProgress, document.SYMBOLS.FindAll(x => !string.IsNullOrEmpty(x.SPPID.RepresentationId)).Count);
2213
                            SymbolModelingByNeerSymbolLoop(connSymbol, endObjects);
2214
                        }
2215
                        else if (connItem.GetType() == typeof(Line))
2216
                        {
2217
                            Line connLine = connItem as Line;
2218
                            if (!SPPIDUtil.IsBranchLine(connLine, line))
2219
                                SymbolModelingByNeerLineLoop(connLine, endObjects, prevSymbol);
2220
                        }
2221
                    }
2222
                }
2223
            }
2224
        }
2225

    
2226
        private void SymbolGroupModeling(Symbol firstSymbol, List<Symbol> group)
2227
        {
2228
            List<Symbol> endModelingGroup = new List<Symbol>();
2229
            SymbolModeling(firstSymbol, null);
2230
            endModelingGroup.Add(firstSymbol);
2231
            while (endModelingGroup.Count != group.Count)
2232
            {
2233
                foreach (var _symbol in group)
2234
                {
2235
                    if (!endModelingGroup.Contains(_symbol))
2236
                    {
2237
                        foreach (var _connector in _symbol.CONNECTORS)
2238
                        {
2239
                            Symbol _connSymbol = SPPIDUtil.FindObjectByUID(document, _connector.CONNECTEDITEM) as Symbol;
2240
                            if (_connSymbol != null && endModelingGroup.Contains(_connSymbol))
2241
                            {
2242
                                SymbolModeling(_symbol, _connSymbol);
2243
                                endModelingGroup.Add(_symbol);
2244
                                break;
2245
                            }
2246
                        }
2247
                    }
2248
                }
2249
            }
2250
        }
2251

    
2252
        /// <summary>
2253
        /// 심볼을 실제로 Modeling할때 ChildSymbol이 있다면 Modeling하는 메서드
2254
        /// </summary>
2255
        /// <param name="childSymbol"></param>
2256
        /// <param name="parentSymbol"></param>
2257
        private void CreateChildSymbol(ChildSymbol childSymbol, LMSymbol parentSymbol, Symbol parent)
2258
        {
2259
            Ingr.RAD2D.Symbol2d symbol2d = radApp.ActiveDocument.ActiveSheet.DrawingObjects[parentSymbol.get_GraphicOID().ToString()];
2260
            double x1 = 0;
2261
            double x2 = 0;
2262
            double y1 = 0;
2263
            double y2 = 0;
2264
            symbol2d.Range(out x1, out y1, out x2, out y2);
2265

    
2266
            LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(childSymbol.SPPID.MAPPINGNAME, (x1 + x2) / 2, (y1 + y2) / 2, TargetItem: parentSymbol);
2267
            if (_LMSymbol != null)
2268
            {
2269
                _LMSymbol.Commit();
2270
                childSymbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
2271
                foreach (var item in childSymbol.ChildSymbols)
2272
                    CreateChildSymbol(item, _LMSymbol, parent);
2273
            }
2274

    
2275

    
2276
            ReleaseCOMObjects(_LMSymbol);
2277
        }
2278
        double index = 0;
2279
        private void NewLineModeling(Line line, bool isBranchModeling = false)
2280
        {
2281
            if (!string.IsNullOrEmpty(line.SPPID.ModelItemId) || (BranchLines.Contains(line) && !isBranchModeling))
2282
                return;
2283

    
2284
            List<Line> group = new List<Line>();
2285
            GetConnectedLineGroup(line, group);
2286
            LineCoordinateCorrection(group);
2287

    
2288
            foreach (var groupLine in group)
2289
            {
2290
                if (!isBranchModeling && SPPIDUtil.IsBranchLine(groupLine))
2291
                {
2292
                    BranchLines.Add(groupLine);
2293
                    continue;
2294
                }
2295

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

    
2369
                            placeRunInputs.AddPoint(x, y);
2370

    
2371
                            if (groupLine.CONNECTORS.IndexOf(connector) == 1)
2372
                            {
2373
                                index += 0.01;
2374
                                if (groupLine.SlopeType == SlopeType.HORIZONTAL)
2375
                                    placeRunInputs.AddPoint(x, -0.1 - index);
2376
                                else if (groupLine.SlopeType == SlopeType.VERTICAL)
2377
                                    placeRunInputs.AddPoint(-0.1 - index, y);
2378
                                else
2379
                                {
2380
                                    Line nextLine = groupLine.CONNECTORS[1].ConnectedObject as Line;
2381
                                    if (SPPIDUtil.CalcAngle(nextLine.SPPID.START_X, nextLine.SPPID.START_Y, nextLine.SPPID.END_X, nextLine.SPPID.END_Y) < 45)
2382
                                        placeRunInputs.AddPoint(-0.1 - index, y);
2383
                                    else
2384
                                        placeRunInputs.AddPoint(x, -0.1 - index);
2385
                                }
2386
                            }
2387
                        }
2388
                    }
2389
                }
2390

    
2391
                LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2392
                if (_lMConnector != null)
2393
                {
2394
                    _lMConnector.Commit();
2395
                    groupLine.SPPID.ModelItemId = _lMConnector.ModelItemID;
2396

    
2397
                    bool bRemodelingStart = false;
2398
                    if (_LMSymbolStart != null)
2399
                        NeedReModeling(groupLine, _LMSymbolStart, ref bRemodelingStart);
2400
                    bool bRemodelingEnd = false;
2401
                    if (_LMSymbolEnd != null)
2402
                        NeedReModeling(groupLine, _LMSymbolEnd, ref bRemodelingEnd);
2403

    
2404
                    if (bRemodelingStart || bRemodelingEnd)
2405
                        ReModelingLine(groupLine, _lMConnector, _LMSymbolStart, _LMSymbolEnd, bRemodelingStart, bRemodelingEnd);
2406

    
2407
                    FlowMarkModeling(groupLine);
2408

    
2409
                    ReleaseCOMObjects(_lMConnector);
2410

    
2411
                    LMModelItem modelItem = dataSource.GetModelItem(groupLine.SPPID.ModelItemId);
2412
                    if (modelItem != null)
2413
                    {
2414
                        LMAAttribute attribute = modelItem.Attributes["FlowDirection"];
2415
                        if (attribute != null)
2416
                            attribute.set_Value("End 1 is upstream (Inlet)");
2417
                        modelItem.Commit();
2418
                    }
2419
                    ReleaseCOMObjects(modelItem);
2420
                    modelItem = null;
2421
                }
2422
                else if (!isBranchModeling)
2423
                {
2424
                    Log.Write("Main Line Modeling : " + groupLine.UID);
2425
                }
2426

    
2427
                List<object> removeLines = groupLine.CONNECTORS.FindAll(x =>
2428
                x.ConnectedObject != null &&
2429
                x.ConnectedObject.GetType() == typeof(Line) &&
2430
                !string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId))
2431
                .Select(x => x.ConnectedObject)
2432
                .ToList();
2433

    
2434
                foreach (var item in removeLines)
2435
                    RemoveLineForModeling(item as Line);
2436

    
2437
                ReleaseCOMObjects(_LMAItem);
2438
                _LMAItem = null;
2439
                ReleaseCOMObjects(placeRunInputs);
2440
                placeRunInputs = null;
2441
                ReleaseCOMObjects(_LMSymbolStart);
2442
                _LMSymbolStart = null;
2443
                ReleaseCOMObjects(_LMSymbolEnd);
2444
                _LMSymbolEnd = null;
2445

    
2446
                if (isBranchModeling && BranchLines.Contains(groupLine))
2447
                    BranchLines.Remove(groupLine);
2448
            }
2449
        }
2450

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

    
2512
            LMConnector _lMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2513
            if (_lMConnector != null)
2514
                _lMConnector.Commit();
2515

    
2516
            ReleaseCOMObjects(_LMAItem);
2517
            _LMAItem = null;
2518
            ReleaseCOMObjects(placeRunInputs);
2519
            placeRunInputs = null;
2520
            ReleaseCOMObjects(_LMSymbolStart);
2521
            _LMSymbolStart = null;
2522
            ReleaseCOMObjects(_LMSymbolEnd);
2523
            _LMSymbolEnd = null;
2524

    
2525
            return _lMConnector;
2526
        }
2527

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

    
2556
                ReleaseCOMObjects(modelItem);
2557
            }
2558
        }
2559

    
2560
        private void RemoveLine(Line line)
2561
        {
2562
            LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
2563
            if (modelItem != null)
2564
            {
2565
                foreach (LMRepresentation rep in modelItem.Representations)
2566
                {
2567
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
2568
                        _placement.PIDRemovePlacement(rep);
2569
                }
2570
                ReleaseCOMObjects(modelItem);
2571
            }
2572
            line.SPPID.ModelItemId = null;
2573
        }
2574

    
2575
        private void GetConnectedLineGroup(Line line, List<Line> group)
2576
        {
2577
            if (!group.Contains(line))
2578
                group.Add(line);
2579
            foreach (var connector in line.CONNECTORS)
2580
            {
2581
                if (connector.ConnectedObject != null &&
2582
                    connector.ConnectedObject.GetType() == typeof(Line) &&
2583
                    !group.Contains(connector.ConnectedObject) &&
2584
                    string.IsNullOrEmpty(((Line)connector.ConnectedObject).SPPID.ModelItemId))
2585
                {
2586
                    Line connLine = connector.ConnectedObject as Line;
2587
                    if (!SPPIDUtil.IsBranchLine(connLine, line))
2588
                    {
2589
                        if (line.CONNECTORS.IndexOf(connector) == 0)
2590
                            group.Insert(0, connLine);
2591
                        else
2592
                            group.Add(connLine);
2593
                        GetConnectedLineGroup(connLine, group);
2594
                    }
2595
                }
2596
            }
2597
        }
2598

    
2599
        private void LineCoordinateCorrection(List<Line> group)
2600
        {
2601
            // 순서대로 전 Item 기준 정렬
2602
            LineCoordinateCorrectionByStart(group);
2603

    
2604
            // 역으로 심볼이 있을 경우 좌표 보정
2605
            LineCoordinateCorrectionForLastLine(group);
2606
        }
2607

    
2608
        private void LineCoordinateCorrectionByStart(List<Line> group)
2609
        {
2610
            for (int i = 0; i < group.Count; i++)
2611
            {
2612
                Line line = group[i];
2613
                if (i == 0)
2614
                {
2615
                    Connector symbolConnector = line.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2616
                    if (symbolConnector != null)
2617
                        LineCoordinateCorrectionByConnItem(line, symbolConnector.ConnectedObject);
2618
                }
2619
                else if (i != 0)
2620
                {
2621
                    LineCoordinateCorrectionByConnItem(line, group[i - 1]);
2622
                }
2623
            }
2624
        }
2625

    
2626
        private void LineCoordinateCorrectionForLastLine(List<Line> group)
2627
        {
2628
            Line checkLine = group[group.Count - 1];
2629
            Connector lastSymbolConnector = checkLine.CONNECTORS.Find(x => x.ConnectedObject != null && x.ConnectedObject.GetType() == typeof(Symbol));
2630
            if (lastSymbolConnector != null)
2631
            {
2632
                LineCoordinateCorrectionByConnItem(checkLine, lastSymbolConnector.ConnectedObject);
2633
                for (int i = group.Count - 2; i >= 0; i--)
2634
                {
2635
                    Line line = group[i + 1];
2636
                    Line prevLine = group[i];
2637

    
2638
                    // 같으면 보정
2639
                    if (line.SlopeType == prevLine.SlopeType)
2640
                        LineCoordinateCorrectionByConnItem(prevLine, line);
2641
                    else
2642
                    {
2643
                        if (line.SlopeType == SlopeType.HORIZONTAL)
2644
                        {
2645
                            double prevX = 0;
2646
                            double prevY = 0;
2647
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2648
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(line, prevLine, prevX);
2649

    
2650
                            double x = 0;
2651
                            double y = 0;
2652
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2653
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(prevLine, line, y);
2654
                        }
2655
                        else if (line.SlopeType == SlopeType.VERTICAL)
2656
                        {
2657
                            double prevX = 0;
2658
                            double prevY = 0;
2659
                            GetTargetLineConnectorPoint(prevLine.CONNECTORS.Find(z => z.ConnectedObject == line), prevLine, ref prevX, ref prevY);
2660
                            ChangeLineSPPIDCoordinateByConnectorOnlyY(line, prevLine, prevY);
2661

    
2662
                            double x = 0;
2663
                            double y = 0;
2664
                            GetTargetLineConnectorPoint(line.CONNECTORS.Find(z => z.ConnectedObject == prevLine), line, ref x, ref y);
2665
                            ChangeLineSPPIDCoordinateByConnectorOnlyX(prevLine, line, x);
2666
                        }
2667
                        break;
2668
                    }
2669
                }
2670
            }
2671
        }
2672

    
2673
        private void LineCoordinateCorrectionByConnItem(Line line, object connItem)
2674
        {
2675
            double x = 0;
2676
            double y = 0;
2677
            if (connItem.GetType() == typeof(Symbol))
2678
            {
2679
                Symbol targetSymbol = connItem as Symbol;
2680
                Connector targetConnector = targetSymbol.CONNECTORS.Find(z => z.ConnectedObject == line);
2681
                if (targetConnector != null)
2682
                    GetTargetSymbolConnectorPoint(targetConnector, targetSymbol, ref x, ref y);
2683
                else
2684
                    throw new Exception("Target symbol UID : " + targetSymbol.UID + "\r\nLine UID : " + line.UID);
2685
            }
2686
            else if (connItem.GetType() == typeof(Line))
2687
            {
2688
                Line targetLine = connItem as Line;
2689
                GetTargetLineConnectorPoint(targetLine.CONNECTORS.Find(z => z.ConnectedObject == line), targetLine, ref x, ref y);
2690
            }
2691

    
2692
            ChangeLineSPPIDCoordinateByConnector(line, connItem, x, y);
2693
        }
2694

    
2695
        private void ChangeLineSPPIDCoordinateByConnector(Line line, object connItem, double x, double y, bool changeOtherCoordinate = true)
2696
        {
2697
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2698
            int index = line.CONNECTORS.IndexOf(connector);
2699
            if (index == 0)
2700
            {
2701
                line.SPPID.START_X = x;
2702
                line.SPPID.START_Y = y;
2703
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2704
                    line.SPPID.END_Y = y;
2705
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2706
                    line.SPPID.END_X = x;
2707
            }
2708
            else
2709
            {
2710
                line.SPPID.END_X = x;
2711
                line.SPPID.END_Y = y;
2712
                if (line.SlopeType == SlopeType.HORIZONTAL && changeOtherCoordinate)
2713
                    line.SPPID.START_Y = y;
2714
                else if (line.SlopeType == SlopeType.VERTICAL && changeOtherCoordinate)
2715
                    line.SPPID.START_X = x;
2716
            }
2717
        }
2718

    
2719
        private void ChangeLineSPPIDCoordinateByConnectorOnlyX(Line line, object connItem, double x)
2720
        {
2721
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2722
            int index = line.CONNECTORS.IndexOf(connector);
2723
            if (index == 0)
2724
            {
2725
                line.SPPID.START_X = x;
2726
                if (line.SlopeType == SlopeType.VERTICAL)
2727
                    line.SPPID.END_X = x;
2728
            }
2729
            else
2730
            {
2731
                line.SPPID.END_X = x;
2732
                if (line.SlopeType == SlopeType.VERTICAL)
2733
                    line.SPPID.START_X = x;
2734
            }
2735
        }
2736

    
2737
        private void ChangeLineSPPIDCoordinateByConnectorOnlyY(Line line, object connItem, double y)
2738
        {
2739
            Connector connector = line.CONNECTORS.Find(z => z.ConnectedObject == connItem);
2740
            int index = line.CONNECTORS.IndexOf(connector);
2741
            if (index == 0)
2742
            {
2743
                line.SPPID.START_Y = y;
2744
                if (line.SlopeType == SlopeType.HORIZONTAL)
2745
                    line.SPPID.END_Y = y;
2746
            }
2747
            else
2748
            {
2749
                line.SPPID.END_Y = y;
2750
                if (line.SlopeType == SlopeType.HORIZONTAL)
2751
                    line.SPPID.START_Y = y;
2752
            }
2753
        }
2754

    
2755
        private void NeedReModeling(Line line, LMSymbol symbol, ref bool result)
2756
        {
2757
            if (symbol != null)
2758
            {
2759
                string repID = symbol.AsLMRepresentation().Id;
2760
                string symbolUID = SPPIDUtil.FindSymbolByRepresentationID(document, repID).UID;
2761
                string lineUID = line.UID;
2762

    
2763
                SpecBreak startSpecBreak = document.SpecBreaks.Find(x =>
2764
                (x.DownStreamUID == symbolUID || x.UpStreamUID == symbolUID) &&
2765
                (x.DownStreamUID == lineUID || x.UpStreamUID == lineUID));
2766

    
2767
                EndBreak startEndBreak = document.EndBreaks.Find(x =>
2768
                (x.OWNER == symbolUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbolUID) &&
2769
                (x.OWNER == lineUID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == lineUID));
2770

    
2771
                if (startSpecBreak != null || startEndBreak != null)
2772
                    result = true;
2773
            }
2774
        }
2775

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

    
2802
            List<double[]> vertices = new List<double[]>();
2803
            for (int i = 1; i <= verticesCount; i++)
2804
            {
2805
                double x = 0;
2806
                double y = 0;
2807
                lineStringGeometry.GetVertex(i, ref x, ref y);
2808
                vertices.Add(new double[] { x, y });
2809
            }
2810

    
2811
            for (int i = 0; i < vertices.Count; i++)
2812
            {
2813
                double[] points = vertices[i];
2814
                // 시작 심볼이 있고 첫번째 좌표일 때
2815
                if (startSymbol != null && i == 0)
2816
                {
2817
                    if (bStart)
2818
                    {
2819
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i + 1][0], vertices[i + 1][1]);
2820
                        if (slopeType == SlopeType.HORIZONTAL)
2821
                            placeRunInputs.AddPoint(points[0], -0.1);
2822
                        else if (slopeType == SlopeType.VERTICAL)
2823
                            placeRunInputs.AddPoint(-0.1, points[1]);
2824
                        else
2825
                            placeRunInputs.AddPoint(points[0], -0.1);
2826

    
2827
                        placeRunInputs.AddPoint(points[0], points[1]);
2828
                    }
2829
                    else
2830
                    {
2831
                        placeRunInputs.AddSymbolTarget(startSymbol, points[0], points[1], diagonal);
2832
                    }
2833
                }
2834
                // 마지막 심볼이 있고 마지막 좌표일 때
2835
                else if (endSymbol != null && i == vertices.Count - 1)
2836
                {
2837
                    if (bEnd)
2838
                    {
2839
                        placeRunInputs.AddPoint(points[0], points[1]);
2840

    
2841
                        SlopeType slopeType = SPPIDUtil.CalcSlope(points[0], points[1], vertices[i - 1][0], vertices[i - 1][1]);
2842
                        if (slopeType == SlopeType.HORIZONTAL)
2843
                            placeRunInputs.AddPoint(points[0], -0.1);
2844
                        else if (slopeType == SlopeType.VERTICAL)
2845
                            placeRunInputs.AddPoint(-0.1, points[1]);
2846
                        else
2847
                            placeRunInputs.AddPoint(points[0], -0.1);
2848
                    }
2849
                    else
2850
                    {
2851
                        placeRunInputs.AddSymbolTarget(endSymbol, points[0], points[1], diagonal);
2852
                    }
2853
                }
2854
                // 첫번째이며 시작 심볼이 아니고 Connecotr일 경우
2855
                else if (i == 0 && prevLMConnector.ConnectItem1SymbolObject != null)
2856
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem1SymbolObject, points[0], points[1], diagonal);
2857
                // 마지막이며 마지막 심볼이 아니고 Connecotr일 경우
2858
                else if (i == vertices.Count - 1 && prevLMConnector.ConnectItem2SymbolObject != null)
2859
                    placeRunInputs.AddSymbolTarget(prevLMConnector.ConnectItem2SymbolObject, points[0], points[1], diagonal);
2860
                else
2861
                    placeRunInputs.AddPoint(points[0], points[1]);
2862
            }
2863

    
2864
            _placement.PIDRemovePlacement(prevLMConnector.AsLMRepresentation());
2865
            newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2866

    
2867
            ReleaseCOMObjects(placeRunInputs);
2868
            ReleaseCOMObjects(_LMAItem);
2869
            ReleaseCOMObjects(modelItem);
2870

    
2871
            if (newConnector != null)
2872
            {
2873
                newConnector.Commit();
2874
                if (startSymbol != null && bStart)
2875
                {
2876
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2877
                    placeRunInputs = new PlaceRunInputs();
2878
                    placeRunInputs.AddSymbolTarget(startSymbol, vertices[0][0], vertices[0][1]);
2879
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[0][0], vertices[0][1]);
2880
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2881
                    if (_LMConnector != null)
2882
                    {
2883
                        _LMConnector.Commit();
2884
                        RemoveConnectorForReModelingLine(newConnector);
2885
                        ZeroLengthModelItemID.Add(_LMConnector.ModelItemID);
2886
                        ReleaseCOMObjects(_LMConnector);
2887
                    }
2888
                    ReleaseCOMObjects(placeRunInputs);
2889
                    ReleaseCOMObjects(_LMAItem);
2890
                }
2891

    
2892
                if (endSymbol != null && bEnd)
2893
                {
2894
                    if (startSymbol != null)
2895
                    {
2896
                        Dictionary<LMConnector, List<double[]>> dicVertices = GetPipeRunVertices(newConnector.ModelItemID);
2897
                        newConnector = dicVertices.First().Key;
2898
                    }
2899

    
2900
                    _LMAItem = _placement.PIDCreateItem(symbolPath);
2901
                    placeRunInputs = new PlaceRunInputs();
2902
                    placeRunInputs.AddSymbolTarget(endSymbol, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2903
                    placeRunInputs.AddConnectorTarget(newConnector, vertices[vertices.Count - 1][0], vertices[vertices.Count - 1][1]);
2904
                    LMConnector _LMConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
2905
                    if (_LMConnector != null)
2906
                    {
2907
                        _LMConnector.Commit();
2908
                        RemoveConnectorForReModelingLine(newConnector);
2909
                        ZeroLengthModelItemIDReverse.Add(_LMConnector.ModelItemID);
2910
                        ReleaseCOMObjects(_LMConnector);
2911
                    }
2912
                    ReleaseCOMObjects(placeRunInputs);
2913
                    ReleaseCOMObjects(_LMAItem);
2914
                }
2915

    
2916
                line.SPPID.ModelItemId = newConnector.ModelItemID;
2917
                ReleaseCOMObjects(newConnector);
2918
            }
2919

    
2920
            ReleaseCOMObjects(modelItem);
2921
        }
2922

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

    
2945
                    if (result)
2946
                        break;
2947
                }
2948
            }
2949
            foreach (var item in dicVertices)
2950
                ReleaseCOMObjects(item.Key);
2951
        }
2952

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

    
2978
                            if (child != null)
2979
                                break;
2980
                        }
2981

    
2982
                        if (child != null)
2983
                            _LMSymbol = dataSource.GetSymbol(child.SPPID.RepresentationId);
2984
                    }
2985

    
2986
                    break;
2987
                }
2988
            }
2989

    
2990
            return _LMSymbol;
2991
        }
2992

    
2993
        /// <summary>
2994
        /// Connector를 가지고 있는 ChildSymbol Object 반환
2995
        /// </summary>
2996
        /// <param name="item"></param>
2997
        /// <param name="connector"></param>
2998
        /// <returns></returns>
2999
        private ChildSymbol GetChildSymbolByConnector(ChildSymbol item, Connector connector)
3000
        {
3001
            foreach (var childSymbol in item.ChildSymbols)
3002
            {
3003
                if (childSymbol.Connectors.Contains(connector))
3004
                    return childSymbol;
3005
                else
3006
                    return GetChildSymbolByConnector(childSymbol, connector);
3007
            }
3008

    
3009
            return null;
3010
        }
3011

    
3012
        /// <summary>
3013
        /// EndBreak 모델링 메서드
3014
        /// </summary>
3015
        /// <param name="endBreak"></param>
3016
        private void EndBreakModeling(EndBreak endBreak)
3017
        {
3018
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
3019
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
3020

    
3021
            LMConnector targetLMConnector = FindBreakLineTarget(ownerObj, connectedItem);
3022
            if (ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Symbol) && targetLMConnector != null)
3023
                targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3024

    
3025
            if (targetLMConnector != null)
3026
            {
3027
                // LEADER Line 검사
3028
                bool leaderLine = false;
3029
                SymbolMapping symbolMapping = document.SymbolMappings.Find(x => x.UID == endBreak.DBUID);
3030
                if (symbolMapping != null)
3031
                    leaderLine = symbolMapping.LEADERLINE;
3032

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

    
3058
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
3059
        {
3060
            string symbolPath = string.Empty;
3061
            #region get symbol path
3062
            if (string.IsNullOrEmpty(changeSymbolPath))
3063
            {
3064
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
3065
                symbolPath = GetSPPIDFileName(modelItem);
3066
                ReleaseCOMObjects(modelItem);
3067
            }
3068
            else
3069
                symbolPath = changeSymbolPath;
3070
            
3071
            #endregion
3072

    
3073
            LMConnector newConnector = null;
3074
            dynamic OID = connector.get_GraphicOID().ToString();
3075
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3076
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3077
            int verticesCount = lineStringGeometry.VertexCount;
3078
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3079
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
3080

    
3081
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3082
            {
3083
                double[] vertices = null;
3084
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3085
                double x = 0;
3086
                double y = 0;
3087
                lineStringGeometry.GetVertex(1, ref x, ref y);
3088

    
3089
                string flowDirection = string.Empty;
3090
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3091
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3092
                    flowDirection = flowAttribute.get_Value().ToString();
3093

    
3094
                if (flowDirection == "End 1 is downstream (Outlet)")
3095
                {
3096
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3097
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3098
                    flowDirection = "End 1 is upstream (Inlet)";
3099
                }
3100
                else
3101
                {
3102
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3103
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3104
                }
3105
                string oldModelItemId = connector.ModelItemID;
3106
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3107
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3108
                newConnector.Commit();
3109
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3110
                if (!string.IsNullOrEmpty(flowDirection))
3111
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3112
                ReleaseCOMObjects(connector);
3113

    
3114
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3115
                {
3116
                    foreach (var repId in line.SPPID.Representations)
3117
                    {
3118
                        LMConnector _connector = dataSource.GetConnector(repId);
3119
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3120
                        {
3121
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3122
                            {
3123
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3124
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3125
                            }
3126
                        }
3127
                        ReleaseCOMObjects(_connector);
3128
                        _connector = null;
3129
                    }
3130
                }
3131
            }
3132

    
3133
            return newConnector;
3134
        }
3135

    
3136
        /// <summary>
3137
        /// SpecBreak Modeling 메서드
3138
        /// </summary>
3139
        /// <param name="specBreak"></param>
3140
        private void SpecBreakModeling(SpecBreak specBreak)
3141
        {
3142
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3143
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3144

    
3145
            if (upStreamObj != null &&
3146
                downStreamObj != null)
3147
            {
3148
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3149
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && 
3150
                    targetLMConnector != null && 
3151
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3152
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3153

    
3154
                if (targetLMConnector != null)
3155
                {
3156
                    foreach (var attribute in specBreak.ATTRIBUTES)
3157
                    {
3158
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3159
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3160
                        {
3161
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3162
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector);
3163
                            Array array = null;
3164
                            if (point != null)
3165
                                array = new double[] { 0, point[0], point[1] };
3166
                            else
3167
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3168
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3169

    
3170
                            if (_LmLabelPersist != null)
3171
                            {
3172
                                _LmLabelPersist.Commit();
3173
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3174
                                if (_LmLabelPersist.ModelItemObject != null)
3175
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3176
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3177
                                ReleaseCOMObjects(_LmLabelPersist);
3178
                            }
3179

    
3180
                            // temp
3181
                            ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3182
                        }
3183
                    }
3184
                    ReleaseCOMObjects(targetLMConnector);
3185
                }
3186
                else
3187
                {
3188
                    Log.Write("Spec Break UID : " + specBreak.UID);
3189
                    Log.Write("Can't find targetLMConnector");
3190
                }
3191
            }
3192
        }
3193

    
3194
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3195
        {
3196
            LMConnector targetConnector = null;
3197
            Symbol targetSymbol = targetObj as Symbol;
3198
            Symbol connectedSymbol = connectedObj as Symbol;
3199
            Line targetLine = targetObj as Line;
3200
            Line connectedLine = connectedObj as Line;
3201
            if (targetSymbol != null && connectedSymbol != null)
3202
            {
3203
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3204
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3205

    
3206
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3207
                {
3208
                    if (connector.get_ItemStatus() != "Active")
3209
                        continue;
3210

    
3211
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3212
                    {
3213
                        targetConnector = connector;
3214
                        break;
3215
                    }
3216
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3217
                    {
3218
                        targetConnector = connector;
3219
                        break;
3220
                    }
3221
                }
3222

    
3223
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3224
                {
3225
                    if (connector.get_ItemStatus() != "Active")
3226
                        continue;
3227

    
3228
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3229
                    {
3230
                        targetConnector = connector;
3231
                        break;
3232
                    }
3233
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3234
                    {
3235
                        targetConnector = connector;
3236
                        break;
3237
                    }
3238
                }
3239

    
3240
                ReleaseCOMObjects(targetLMSymbol);
3241
                ReleaseCOMObjects(connectedLMSymbol);
3242
            }
3243
            else if (targetLine != null && connectedLine != null)
3244
            {
3245
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3246
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3247

    
3248
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
3249
                {
3250
                    foreach (LMRepresentation rep in targetModelItem.Representations)
3251
                    {
3252
                        if (targetConnector != null)
3253
                            break;
3254

    
3255
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3256
                        {
3257
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3258

    
3259
                            if (IsConnected(_LMConnector, connectedModelItem))
3260
                                targetConnector = _LMConnector;
3261
                            else
3262
                                ReleaseCOMObjects(_LMConnector);
3263
                        }
3264
                    }
3265

    
3266
                    ReleaseCOMObjects(targetModelItem);
3267
                }
3268
            }
3269
            else
3270
            {
3271
                LMSymbol connectedLMSymbol = null;
3272
                if (connectedSymbol != null)
3273
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3274
                else if (targetSymbol != null)
3275
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3276
                else
3277
                {
3278

    
3279
                }
3280
                LMModelItem targetModelItem = null;
3281
                if (targetLine != null)
3282
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3283
                else if (connectedLine != null)
3284
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3285
                else
3286
                {
3287

    
3288
                }
3289
                if (connectedLMSymbol != null && targetModelItem != null)
3290
                {
3291
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
3292
                    {
3293
                        if (connector.get_ItemStatus() != "Active")
3294
                            continue;
3295

    
3296
                        if (IsConnected(connector, targetModelItem))
3297
                        {
3298
                            targetConnector = connector;
3299
                            break;
3300
                        }
3301
                    }
3302

    
3303
                    if (targetConnector == null)
3304
                    {
3305
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
3306
                        {
3307
                            if (connector.get_ItemStatus() != "Active")
3308
                                continue;
3309

    
3310
                            if (IsConnected(connector, targetModelItem))
3311
                            {
3312
                                targetConnector = connector;
3313
                                break;
3314
                            }
3315
                        }
3316
                    }
3317
                }
3318

    
3319
            }
3320

    
3321
            return targetConnector;
3322
        }
3323

    
3324
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector)
3325
        {
3326
            double[] result = null;
3327
            Line targetLine = targetObj as Line;
3328
            Symbol targetSymbol = targetObj as Symbol;
3329
            Line connLine = connObj as Line;
3330
            Symbol connSymbol = connObj as Symbol;
3331

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

    
3370
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3371

    
3372
                    ReleaseCOMObjects(modelItem);
3373
                    ReleaseCOMObjects(connectedConnector);
3374

    
3375
                    if (vertices.Count > 0)
3376
                    {
3377
                        if (connIndex == 1)
3378
                            result = vertices[0];
3379
                        else if (connIndex == 2)
3380
                            result = vertices[vertices.Count - 1];
3381

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

    
3431
            return result;
3432
        }
3433

    
3434
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3435
        {
3436
            bool result = false;
3437

    
3438
            foreach (LMRepresentation rep in modelItem.Representations)
3439
            {
3440
                if (result)
3441
                    break;
3442

    
3443
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3444
                {
3445
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3446

    
3447
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3448
                        connector.ConnectItem1SymbolObject != null &&
3449
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3450
                    {
3451
                        result = true;
3452
                        ReleaseCOMObjects(_LMConnector);
3453
                        break;
3454
                    }
3455
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3456
                        connector.ConnectItem2SymbolObject != null &&
3457
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3458
                    {
3459
                        result = true;
3460
                        ReleaseCOMObjects(_LMConnector);
3461
                        break;
3462
                    }
3463
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3464
                        connector.ConnectItem1SymbolObject != null &&
3465
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3466
                    {
3467
                        result = true;
3468
                        ReleaseCOMObjects(_LMConnector);
3469
                        break;
3470
                    }
3471
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3472
                        connector.ConnectItem2SymbolObject != null &&
3473
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3474
                    {
3475
                        result = true;
3476
                        ReleaseCOMObjects(_LMConnector);
3477
                        break;
3478
                    }
3479

    
3480
                    ReleaseCOMObjects(_LMConnector);
3481
                }
3482
            }
3483

    
3484

    
3485
            return result;
3486
        }
3487

    
3488
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3489
        {
3490
            foreach (LMRepresentation rep in modelItem.Representations)
3491
            {
3492
                if (connectedConnector != null)
3493
                    break;
3494

    
3495
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3496
                {
3497
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3498

    
3499
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3500
                        connector.ConnectItem1SymbolObject != null &&
3501
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3502
                    {
3503
                        connectedConnector = _LMConnector;
3504
                        connectorIndex = 1;
3505
                        break;
3506
                    }
3507
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3508
                        connector.ConnectItem2SymbolObject != null &&
3509
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3510
                    {
3511
                        connectedConnector = _LMConnector;
3512
                        connectorIndex = 2;
3513
                        break;
3514
                    }
3515
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3516
                        connector.ConnectItem1SymbolObject != null &&
3517
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3518
                    {
3519
                        connectedConnector = _LMConnector;
3520
                        connectorIndex = 1;
3521
                        break;
3522
                    }
3523
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3524
                        connector.ConnectItem2SymbolObject != null &&
3525
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3526
                    {
3527
                        connectedConnector = _LMConnector;
3528
                        connectorIndex = 2;
3529
                        break;
3530
                    }
3531

    
3532
                    if (connectedConnector == null)
3533
                        ReleaseCOMObjects(_LMConnector);
3534
                }
3535
            }
3536
        }
3537

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

    
3560
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3561
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
3562
                List<double[]> vertices2 = null;
3563
                string graphicOID2 = string.Empty;
3564
                if (connector2 != null)
3565
                {
3566
                    vertices2 = GetConnectorVertices(connector2);
3567
                    graphicOID2 = connector2.get_GraphicOID();
3568
                }
3569
                _LMAItem item2 = modelItem2.AsLMAItem();
3570
                ReleaseCOMObjects(connector2);
3571
                connector2 = null;
3572

    
3573
                // item2가 item1으로 조인
3574
                _placement.PIDJoinRuns(ref item1, ref item2);
3575
                item1.Commit();
3576
                item2.Commit();
3577

    
3578
                string beforeID = string.Empty;
3579
                string afterID = string.Empty;
3580

    
3581
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3582
                {
3583
                    beforeID = modelItem2.Id;
3584
                    afterID = modelItem1.Id;
3585
                    survivorId = afterID;
3586
                }
3587
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3588
                {
3589
                    beforeID = modelItem1.Id;
3590
                    afterID = modelItem2.Id;
3591
                    survivorId = afterID;
3592
                }
3593
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3594
                {
3595
                    int model1Cnt = GetConnectorCount(modelId1);
3596
                    int model2Cnt = GetConnectorCount(modelId2);
3597
                    if (model1Cnt == 0)
3598
                    {
3599
                        beforeID = modelItem1.Id;
3600
                        afterID = modelItem2.Id;
3601
                        survivorId = afterID;
3602
                    }
3603
                    else if (model2Cnt == 0)
3604
                    {
3605
                        beforeID = modelItem2.Id;
3606
                        afterID = modelItem1.Id;
3607
                        survivorId = afterID;
3608
                    }
3609
                    else
3610
                        survivorId = null;
3611
                }
3612
                else
3613
                {
3614
                    Log.Write("잘못된 경우");
3615
                    survivorId = null;
3616
                }
3617

    
3618
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3619
                {
3620
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3621
                    foreach (var line in lines)
3622
                        line.SPPID.ModelItemId = afterID;
3623
                }
3624

    
3625
                ReleaseCOMObjects(modelItem1);
3626
                ReleaseCOMObjects(item1);
3627
                ReleaseCOMObjects(modelItem2);
3628
                ReleaseCOMObjects(item2);
3629
            }
3630
            catch (Exception ex)
3631
            {
3632
                Log.Write("Join Error");
3633
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3634
            }
3635
        }
3636

    
3637
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
3638
        {
3639
            bool result = false;
3640
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
3641
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
3642
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
3643

    
3644
            foreach (var item in endBreaks)
3645
            {
3646
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
3647
                {
3648
                    result = true;
3649
                    break;
3650
                }
3651
            }
3652

    
3653
            return result;
3654
        }
3655
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3656
        {
3657
            List<string> temp = new List<string>();
3658
            List<LMConnector> connectors = new List<LMConnector>();
3659
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3660
            {
3661
                if (connector.get_ItemStatus() != "Active")
3662
                    continue;
3663

    
3664
                LMModelItem modelItem = connector.ModelItemObject;
3665
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3666
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3667
                    temp.Add(modelItem.Id);
3668

    
3669
                if (temp.Contains(modelItem.Id) &&
3670
                    connOtherSymbol != null &&
3671
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3672
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3673
                    temp.Remove(modelItem.Id);
3674

    
3675

    
3676
                if (temp.Contains(modelItem.Id))
3677
                    connectors.Add(connector);
3678
                ReleaseCOMObjects(connOtherSymbol);
3679
                connOtherSymbol = null;
3680
                ReleaseCOMObjects(modelItem);
3681
                modelItem = null;
3682
            }
3683

    
3684
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3685
            {
3686
                if (connector.get_ItemStatus() != "Active")
3687
                    continue;
3688

    
3689
                LMModelItem modelItem = connector.ModelItemObject;
3690
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3691
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3692
                    temp.Add(modelItem.Id);
3693

    
3694
                if (temp.Contains(modelItem.Id) &&
3695
                    connOtherSymbol != null &&
3696
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3697
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3698
                    temp.Remove(modelItem.Id);
3699

    
3700
                if (temp.Contains(modelItem.Id))
3701
                    connectors.Add(connector);
3702
                ReleaseCOMObjects(connOtherSymbol);
3703
                connOtherSymbol = null;
3704
                ReleaseCOMObjects(modelItem);
3705
                modelItem = null;
3706
            }
3707

    
3708

    
3709
            List<string> result = new List<string>();
3710
            string originalName = GetSPPIDFileName(modelId);
3711
            foreach (var connector in connectors)
3712
            {
3713
                string fileName = GetSPPIDFileName(connector.ModelItemID);
3714
                if (originalName == fileName)
3715
                    result.Add(connector.ModelItemID);
3716
                else
3717
                {
3718
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
3719
                        result.Add(connector.ModelItemID);
3720
                    else
3721
                    {
3722
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
3723
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
3724
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
3725
                            result.Add(connector.ModelItemID);
3726
                    }
3727
                }
3728
            }
3729

    
3730
            foreach (var connector in connectors)
3731
                ReleaseCOMObjects(connector);
3732
            
3733
            return result;
3734

    
3735

    
3736
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3737
            {
3738
                LMSymbol findResult = null;
3739
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3740
                    findResult = connector.ConnectItem1SymbolObject;
3741
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3742
                    findResult = connector.ConnectItem2SymbolObject;
3743

    
3744
                return findResult;
3745
            }
3746
        }
3747

    
3748
        /// <summary>
3749
        /// PipeRun의 좌표를 가져오는 메서드
3750
        /// </summary>
3751
        /// <param name="modelId"></param>
3752
        /// <returns></returns>
3753
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
3754
        {
3755
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
3756
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
3757

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

    
3788
                ReleaseCOMObjects(modelItem);
3789
            }
3790

    
3791
            return connectorVertices;
3792
        }
3793

    
3794
        private List<double[]> GetConnectorVertices(LMConnector connector)
3795
        {
3796
            List<double[]> vertices = new List<double[]>();
3797
            if (connector != null)
3798
            {
3799
                dynamic OID = connector.get_GraphicOID().ToString();
3800
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3801
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3802
                int verticesCount = lineStringGeometry.VertexCount;
3803
                double[] value = null;
3804
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3805
                for (int i = 0; i < verticesCount; i++)
3806
                {
3807
                    double x = 0;
3808
                    double y = 0;
3809
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3810
                    vertices.Add(new double[] { x, y });
3811
                }
3812
            }
3813
            return vertices;
3814
        }
3815

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

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

    
3904
                    if ((x1 <= connX && x2 >= connX) ||
3905
                        (y1 <= connY && y2 >= connY))
3906
                    {
3907
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3908
                        if (length >= distance)
3909
                        {
3910
                            targetConnector = item.Key;
3911
                            length = distance;
3912
                        }
3913

    
3914
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3915
                        if (length >= distance)
3916
                        {
3917
                            targetConnector = item.Key;
3918
                            length = distance;
3919
                        }
3920
                    }
3921
                }
3922
            }
3923

    
3924
            // 못찾았을때.
3925
            length = double.MaxValue;
3926
            if (targetConnector == null)
3927
            {
3928
                foreach (var item in connectorVertices)
3929
                {
3930
                    List<double[]> points = item.Value;
3931

    
3932
                    foreach (double[] point in points)
3933
                    {
3934
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3935
                        if (length >= distance)
3936
                        {
3937
                            targetConnector = item.Key;
3938
                            length = distance;
3939
                        }
3940
                    }
3941
                }
3942
            }
3943

    
3944
            return targetConnector;
3945
        }
3946

    
3947
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3948
        {
3949
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3950
            if (vertices.Count == 0)
3951
                return null;
3952

    
3953
            double length = double.MaxValue;
3954
            LMConnector targetConnector = null;
3955
            double[] resultPoint = null;
3956
            List<double[]> targetVertices = null;
3957

    
3958
            // Vertices 포인트에 제일 가까운곳
3959
            foreach (var item in vertices)
3960
            {
3961
                List<double[]> points = item.Value;
3962
                for (int i = 0; i < points.Count; i++)
3963
                {
3964
                    double[] point = points[i];
3965
                    double tempX = point[0];
3966
                    double tempY = point[1];
3967

    
3968
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3969
                    if (length >= distance)
3970
                    {
3971
                        targetConnector = item.Key;
3972
                        length = distance;
3973
                        resultPoint = point;
3974
                        targetVertices = item.Value;
3975
                    }
3976
                }
3977
            }
3978

    
3979
            // Vertices Cross에 제일 가까운곳
3980
            foreach (var item in vertices)
3981
            {
3982
                List<double[]> points = item.Value;
3983
                for (int i = 0; i < points.Count - 1; i++)
3984
                {
3985
                    double[] point1 = points[i];
3986
                    double[] point2 = points[i + 1];
3987

    
3988
                    double maxLineX = Math.Max(point1[0], point2[0]);
3989
                    double minLineX = Math.Min(point1[0], point2[0]);
3990
                    double maxLineY = Math.Max(point1[1], point2[1]);
3991
                    double minLineY = Math.Min(point1[1], point2[1]);
3992

    
3993
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
3994

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

    
4031
            foreach (var item in vertices)
4032
                if (item.Key != null && item.Key != targetConnector)
4033
                    ReleaseCOMObjects(item.Key);
4034

    
4035
            if (SPPIDUtil.IsBranchLine(line, targetLine))
4036
            {
4037
                double tempResultX = resultPoint[0];
4038
                double tempResultY = resultPoint[1];
4039
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4040

    
4041
                GridSetting gridSetting = GridSetting.GetInstance();
4042

    
4043
                for (int i = 0; i < targetVertices.Count; i++)
4044
                {
4045
                    double[] point = targetVertices[i];
4046
                    double tempX = targetVertices[i][0];
4047
                    double tempY = targetVertices[i][1];
4048
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
4049
                    if (tempX == tempResultX && tempY == tempResultY)
4050
                    {
4051
                        if (i == 0)
4052
                        {
4053
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
4054
                            bool containZeroLength = false;
4055
                            if (connSymbol != null)
4056
                            {
4057
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4058
                                {
4059
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4060
                                        containZeroLength = true;
4061
                                }
4062
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4063
                                {
4064
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4065
                                        containZeroLength = true;
4066
                                }
4067
                            }
4068

    
4069
                            if (connSymbol == null ||
4070
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4071
                                containZeroLength)
4072
                            {
4073
                                bool bCalcX = false;
4074
                                bool bCalcY = false;
4075
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4076
                                    bCalcX = true;
4077
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4078
                                    bCalcY = true;
4079
                                else
4080
                                {
4081
                                    bCalcX = true;
4082
                                    bCalcY = true;
4083
                                }
4084

    
4085
                                if (bCalcX)
4086
                                {
4087
                                    double nextX = targetVertices[i + 1][0];
4088
                                    double newX = 0;
4089
                                    if (nextX > tempX)
4090
                                    {
4091
                                        newX = tempX + gridSetting.Length;
4092
                                        if (newX > nextX)
4093
                                            newX = (point[0] + nextX) / 2;
4094
                                    }
4095
                                    else
4096
                                    {
4097
                                        newX = tempX - gridSetting.Length;
4098
                                        if (newX < nextX)
4099
                                            newX = (point[0] + nextX) / 2;
4100
                                    }
4101
                                    resultPoint = new double[] { newX, resultPoint[1] };
4102
                                }
4103

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

    
4142
                            if (connSymbol == null ||
4143
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4144
                                containZeroLength)
4145
                            {
4146
                                bool bCalcX = false;
4147
                                bool bCalcY = false;
4148
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4149
                                    bCalcX = true;
4150
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4151
                                    bCalcY = true;
4152
                                else
4153
                                {
4154
                                    bCalcX = true;
4155
                                    bCalcY = true;
4156
                                }
4157

    
4158
                                if (bCalcX)
4159
                                {
4160
                                    double nextX = targetVertices[i - 1][0];
4161
                                    double newX = 0;
4162
                                    if (nextX > tempX)
4163
                                    {
4164
                                        newX = tempX + gridSetting.Length;
4165
                                        if (newX > nextX)
4166
                                            newX = (point[0] + nextX) / 2;
4167
                                    }
4168
                                    else
4169
                                    {
4170
                                        newX = tempX - gridSetting.Length;
4171
                                        if (newX < nextX)
4172
                                            newX = (point[0] + nextX) / 2;
4173
                                    }
4174
                                    resultPoint = new double[] { newX, resultPoint[1] };
4175
                                }
4176

    
4177
                                if (bCalcY)
4178
                                {
4179
                                    double nextY = targetVertices[i - 1][1];
4180
                                    double newY = 0;
4181
                                    if (nextY > tempY)
4182
                                    {
4183
                                        newY = tempY + gridSetting.Length;
4184
                                        if (newY > nextY)
4185
                                            newY = (point[1] + nextY) / 2;
4186
                                    }
4187
                                    else
4188
                                    {
4189
                                        newY = tempY - gridSetting.Length;
4190
                                        if (newY < nextY)
4191
                                            newY = (point[1] + nextY) / 2;
4192
                                    }
4193
                                    resultPoint = new double[] { resultPoint[0], newY };
4194
                                }
4195
                            }
4196
                        }
4197
                        break;
4198
                    }
4199
                }
4200
            }
4201

    
4202
            x = resultPoint[0];
4203
            y = resultPoint[1];
4204

    
4205
            return targetConnector;
4206
        }
4207

    
4208
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
4209
        {
4210
            LMConnector result = null;
4211
            List<LMConnector> connectors = new List<LMConnector>();
4212
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4213

    
4214
            if (modelItem != null)
4215
            {
4216
                foreach (LMRepresentation rep in modelItem.Representations)
4217
                {
4218
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4219
                        connectors.Add(dataSource.GetConnector(rep.Id));
4220
                }
4221

    
4222
                ReleaseCOMObjects(modelItem);
4223
            }
4224

    
4225
            if (connectors.Count == 1)
4226
                result = connectors[0];
4227
            else
4228
                foreach (var item in connectors)
4229
                    ReleaseCOMObjects(item);
4230

    
4231
            return result;
4232
        }
4233

    
4234
        private LMConnector GetLMConnectorFirst(string modelItemID)
4235
        {
4236
            LMConnector result = null;
4237
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4238

    
4239
            if (modelItem != null)
4240
            {
4241
                foreach (LMRepresentation rep in modelItem.Representations)
4242
                {
4243
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && 
4244
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
4245
                    {
4246
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4247
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
4248
                        {
4249
                            result = connector;
4250
                            break;
4251
                        }
4252
                        else
4253
                        {
4254
                            ReleaseCOMObjects(connector);
4255
                            connector = null;
4256
                        }
4257
                    }
4258
                }
4259
                ReleaseCOMObjects(modelItem);
4260
                modelItem = null;
4261
            }
4262

    
4263
            return result;
4264
        }
4265

    
4266
        private int GetConnectorCount(string modelItemID)
4267
        {
4268
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4269
            int result = 0;
4270
            if (modelItem != null)
4271
            {
4272
                foreach (LMRepresentation rep in modelItem.Representations)
4273
                {
4274
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4275
                        result++;
4276
                    ReleaseCOMObjects(rep);
4277
                }
4278
                ReleaseCOMObjects(modelItem);
4279
            }
4280

    
4281
            return result;
4282
        }
4283

    
4284
        public List<string> GetRepresentations(string modelItemID)
4285
        {
4286
            List<string> result = new List<string>(); ;
4287
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4288
            if (modelItem != null)
4289
            {
4290
                foreach (LMRepresentation rep in modelItem.Representations)
4291
                {
4292
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4293
                        result.Add(rep.Id);
4294
                }
4295
                ReleaseCOMObjects(modelItem);
4296
            }
4297

    
4298
            return result;
4299
        }
4300

    
4301
        private void LineNumberModeling(LineNumber lineNumber)
4302
        {
4303
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4304
            if (line != null)
4305
            {
4306
                double x = 0;
4307
                double y = 0;
4308
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4309

    
4310
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4311
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
4312
                if (connectedLMConnector != null)
4313
                {
4314
                    Array points = new double[] { 0, x, y };
4315
                    lineNumber.SPPID.SPPID_X = x;
4316
                    lineNumber.SPPID.SPPID_Y = y;
4317
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4318

    
4319
                    if (_LmLabelPresist != null)
4320
                    {
4321
                        _LmLabelPresist.Commit();
4322
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4323
                        ReleaseCOMObjects(_LmLabelPresist);
4324
                    }
4325
                }
4326

    
4327
                foreach (var item in connectorVertices)
4328
                    ReleaseCOMObjects(item.Key);
4329
            }
4330
        }
4331
        private void LineNumberCorrectModeling(LineNumber lineNumber)
4332
        {
4333
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4334
            if (line == null || line.SPPID.Vertices == null)
4335
                return;
4336

    
4337
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
4338
            {
4339
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
4340
                if (removeLabel != null)
4341
                {
4342
                    lineNumber.SPPID.SPPID_X = removeLabel.get_XCoordinate();
4343
                    lineNumber.SPPID.SPPID_Y = removeLabel.get_YCoordinate();
4344

    
4345
                    GridSetting gridSetting = GridSetting.GetInstance();
4346
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4347

    
4348
                    double[] labelRange = null;
4349
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
4350
                    List<double[]> vertices = GetConnectorVertices(connector);
4351

    
4352
                    double[] resultStart = null;
4353
                    double[] resultEnd = null;
4354
                    double distance = double.MaxValue;
4355
                    for (int i = 0; i < vertices.Count - 1; i++)
4356
                    {
4357
                        double[] startPoint = vertices[i];
4358
                        double[] endPoint = vertices[i + 1];
4359
                        foreach (var item in line.SPPID.Vertices)
4360
                        {
4361
                            double[] lineStartPoint = item[0];
4362
                            double[] lineEndPoint = item[item.Count - 1];
4363

    
4364
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
4365
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
4366
                            if (tempDistance < distance)
4367
                            {
4368
                                distance = tempDistance;
4369
                                resultStart = startPoint;
4370
                                resultEnd = endPoint;
4371
                            }
4372
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
4373
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
4374
                            if (tempDistance < distance)
4375
                            {
4376
                                distance = tempDistance;
4377
                                resultStart = startPoint;
4378
                                resultEnd = endPoint;
4379
                            }
4380
                        }
4381
                    }
4382

    
4383
                    if (resultStart != null && resultEnd != null)
4384
                    {
4385
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
4386
                        double lineStartX = 0;
4387
                        double lineStartY = 0;
4388
                        double lineEndX = 0;
4389
                        double lineEndY = 0;
4390
                        double lineNumberX = 0;
4391
                        double lineNumberY = 0;
4392
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
4393
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
4394

    
4395
                        double lineX = (lineStartX + lineEndX) / 2;
4396
                        double lineY = (lineStartY + lineEndY) / 2;
4397
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
4398
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
4399

    
4400
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4401
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4402
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4403
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4404

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

    
4442
                        if (offsetY != 0 || offsetY != 0)
4443
                        {
4444
                            if (connector.ConnectItem1SymbolObject != null &&
4445
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
4446
                            {
4447
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
4448

    
4449
                                double x1, y1, x2, y2, originX, originY;
4450
                                symbol.Range(out x1, out y1, out x2, out y2);
4451
                                symbol.GetOrigin(out originX, out originY);
4452
                                if (originX < lineNumber.SPPID.SPPID_X)
4453
                                    lineNumber.SPPID.SPPID_X = originX + gridSetting.Length * 35;
4454
                                else
4455
                                    lineNumber.SPPID.SPPID_X = originX - gridSetting.Length * 35;
4456
                            }
4457
                            else if (connector.ConnectItem2SymbolObject != null &&
4458
                                    connector.ConnectItem2SymbolObject.get_RepresentationType() == "OPC")
4459
                            {
4460
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem2SymbolObject.get_GraphicOID().ToString()];
4461

    
4462
                                double x1, y1, x2, y2, originX, originY;
4463
                                symbol.Range(out x1, out y1, out x2, out y2);
4464
                                symbol.GetOrigin(out originX, out originY);
4465
                                if (originX < lineNumber.SPPID.SPPID_X)
4466
                                    lineNumber.SPPID.SPPID_X = originX + gridSetting.Length * 35;
4467
                                else
4468
                                    lineNumber.SPPID.SPPID_X = originX - gridSetting.Length * 35;
4469
                            }
4470

    
4471
                            radApp.ActiveSelectSet.RemoveAll();
4472
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[removeLabel.get_GraphicOID().ToString()] as DependencyObject;
4473
                            if (dependency != null)
4474
                            {
4475
                                radApp.ActiveSelectSet.Add(dependency);
4476
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
4477
                                transform.DefineByMove2d(-offsetX, -offsetY);
4478
                                radApp.ActiveSelectSet.Transform(transform, true);
4479
                                radApp.ActiveSelectSet.RemoveAll();
4480
                            }
4481
                        }
4482

    
4483
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4484
                        {
4485
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4486
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4487
                        }
4488
                    }
4489

    
4490

    
4491
                    ReleaseCOMObjects(connector);
4492
                    connector = null;
4493
                }
4494

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

    
4526
        /// <summary>
4527
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
4528
        /// </summary>
4529
        /// <param name="lineNumber"></param>
4530
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
4531
        {
4532
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
4533
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
4534
            {
4535
                if (a.ATTRIBUTE == "Tag Seq No")
4536
                    return 1;
4537
                else if (b.ATTRIBUTE == "Tag Seq No")
4538
                    return -1;
4539

    
4540
                return 0;
4541
            }
4542

    
4543
            foreach (LineRun run in lineNumber.RUNS)
4544
            {
4545
                foreach (var item in run.RUNITEMS)
4546
                {
4547
                    if (item.GetType() == typeof(Symbol))
4548
                    {
4549
                        Symbol symbol = item as Symbol;
4550
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4551
                        if (_LMSymbol != null)
4552
                        {
4553
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4554

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

    
4608
                                                    if (_LMAAttribute != null)
4609
                                                    {
4610
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4611
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4612
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
4613
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4614
                                                    }
4615
                                                }
4616
                                                if (dt != null)
4617
                                                    dt.Dispose();
4618
                                            }
4619
                                        }
4620
                                        else if (_LMAAttribute != null)
4621
                                        {
4622
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4623
                                                _LMAAttribute.set_Value(attribute.VALUE);
4624
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4625
                                                _LMAAttribute.set_Value(attribute.VALUE);
4626
                                        }
4627
                                    }
4628
                                }
4629
                                _LMModelItem.Commit();
4630
                            }
4631
                            if (_LMModelItem != null)
4632
                                ReleaseCOMObjects(_LMModelItem);
4633
                            endLine.Add(line.SPPID.ModelItemId);
4634
                        }
4635
                    }
4636
                }
4637
            }
4638
        }
4639

    
4640
        /// <summary>
4641
        /// Symbol Attribute 입력 메서드
4642
        /// </summary>
4643
        /// <param name="item"></param>
4644
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
4645
        {
4646
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
4647
            string sRep = null;
4648
            if (targetItem.GetType() == typeof(Symbol))
4649
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
4650
            else if (targetItem.GetType() == typeof(Equipment))
4651
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
4652

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

    
4685
                ReleaseCOMObjects(_Attributes);
4686
                ReleaseCOMObjects(_LMModelItem);
4687
                ReleaseCOMObjects(_LMSymbol);
4688
            }
4689
        }
4690

    
4691
        /// <summary>
4692
        /// Input SpecBreak Attribute
4693
        /// </summary>
4694
        /// <param name="specBreak"></param>
4695
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4696
        {
4697
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4698
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4699

    
4700
            if (upStreamObj != null &&
4701
                downStreamObj != null)
4702
            {
4703
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4704

    
4705
                if (targetLMConnector != null)
4706
                {
4707
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4708
                    {
4709
                        string symbolPath = _LMLabelPersist.get_FileName();
4710
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4711
                        if (mapping != null)
4712
                        {
4713
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4714
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4715
                            {
4716
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4717
                                if (values.Length == 2)
4718
                                {
4719
                                    string upStreamValue = values[0];
4720
                                    string downStreamValue = values[1];
4721

    
4722
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4723
                                }
4724
                            }
4725
                        }
4726
                    }
4727

    
4728
                    ReleaseCOMObjects(targetLMConnector);
4729
                }
4730
            }
4731

    
4732

    
4733
            #region 내부에서만 쓰는 메서드
4734
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4735
            {
4736
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4737
                Line upStreamLine = _upStreamObj as Line;
4738
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4739
                Line downStreamLine = _downStreamObj as Line;
4740
                // 둘다 Line일 경우
4741
                if (upStreamLine != null && downStreamLine != null)
4742
                {
4743
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4744
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4745
                }
4746
                // 둘다 Symbol일 경우
4747
                else if (upStreamSymbol != null && downStreamSymbol != null)
4748
                {
4749
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4750
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4751
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4752

    
4753
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
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 upStreamLMSymbol.Avoid2Connectors)
4763
                    {
4764
                        if (connector.get_ItemStatus() != "Active")
4765
                            continue;
4766

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

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

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

    
4780
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4781
                    {
4782
                        if (connector.get_ItemStatus() != "Active")
4783
                            continue;
4784

    
4785
                        if (connector.Id != zeroLenthConnector.Id)
4786
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4787
                    }
4788

    
4789
                    ReleaseCOMObjects(zeroLenthConnector);
4790
                    ReleaseCOMObjects(upStreamLMSymbol);
4791
                    ReleaseCOMObjects(downStreamLMSymbol);
4792
                }
4793
                else if (upStreamSymbol != null && downStreamLine != null)
4794
                {
4795
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4796
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4797
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4798

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

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

    
4808
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4809
                    {
4810
                        if (connector.get_ItemStatus() != "Active")
4811
                            continue;
4812

    
4813
                        if (connector.Id == zeroLenthConnector.Id)
4814
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4815
                    }
4816

    
4817
                    ReleaseCOMObjects(zeroLenthConnector);
4818
                    ReleaseCOMObjects(upStreamLMSymbol);
4819
                }
4820
                else if (upStreamLine != null && downStreamSymbol != null)
4821
                {
4822
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4823
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4824
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4825

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

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

    
4835
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4836
                    {
4837
                        if (connector.get_ItemStatus() != "Active")
4838
                            continue;
4839

    
4840
                        if (connector.Id == zeroLenthConnector.Id)
4841
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4842
                    }
4843

    
4844
                    ReleaseCOMObjects(zeroLenthConnector);
4845
                    ReleaseCOMObjects(downStreamLMSymbol);
4846
                }
4847
            }
4848

    
4849
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4850
            {
4851
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4852
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4853
                {
4854
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4855
                    if (_LMAAttribute != null)
4856
                    {
4857
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4858
                            _LMAAttribute.set_Value(value);
4859
                        else if (_LMAAttribute.get_Value() != value)
4860
                            _LMAAttribute.set_Value(value);
4861
                    }
4862

    
4863
                    _LMModelItem.Commit();
4864
                }
4865
                if (_LMModelItem != null)
4866
                    ReleaseCOMObjects(_LMModelItem);
4867
            }
4868

    
4869
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4870
            {
4871
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4872
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4873
                {
4874
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4875
                    if (_LMAAttribute != null)
4876
                    {
4877
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4878
                            _LMAAttribute.set_Value(value);
4879
                        else if (_LMAAttribute.get_Value() != value)
4880
                            _LMAAttribute.set_Value(value);
4881
                    }
4882

    
4883
                    _LMModelItem.Commit();
4884
                }
4885
                if (_LMModelItem != null)
4886
                    ReleaseCOMObjects(_LMModelItem);
4887
            }
4888
            #endregion
4889
        }
4890

    
4891
        private void InputEndBreakAttribute(EndBreak endBreak)
4892
        {
4893
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
4894
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
4895

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

    
4948
                            modelItemIDs = modelItemIDs.Distinct().ToList();
4949
                            if (modelItemIDs.Count == 1)
4950
                            {
4951
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
4952
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
4953
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
4954
                                {
4955
                                    bool result = false;
4956
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
4957
                                    {
4958
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
4959
                                            result = true;
4960
                                        ReleaseCOMObjects(loop);
4961
                                    }
4962

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

    
5009
                                        loopModelItems = loopModelItems.Distinct().ToList();
5010
                                        if (loopModelItems.Count == 1)
5011
                                        {
5012
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
5013
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5014
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5015
                                            modelItem.Commit();
5016
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5017
                                            ZeroLengthModelItem.Commit();
5018

    
5019
                                            ReleaseCOMObjects(loopModelItem);
5020
                                            loopModelItem = null;
5021
                                        }
5022
                                    }
5023
                                }
5024
                                else
5025
                                {
5026
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5027
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5028
                                    ZeroLengthModelItem.Commit();
5029
                                }
5030
                                ReleaseCOMObjects(modelItem);
5031
                                modelItem = null;
5032
                                ReleaseCOMObjects(onlyOne);
5033
                                onlyOne = null;
5034
                            }
5035
                        }
5036
                        ReleaseCOMObjects(connector);
5037
                        connector = null;
5038
                        ReleaseCOMObjects(ZeroLengthModelItem);
5039
                        ZeroLengthModelItem = null;
5040
                    }
5041
                    ReleaseCOMObjects(representation);
5042
                    representation = null;
5043
                }
5044
                ReleaseCOMObjects(labelPersist);
5045
                labelPersist = null;
5046
            }
5047
        }
5048

    
5049
        /// <summary>
5050
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5051
        /// </summary>
5052
        /// <param name="text"></param>
5053
        private void NormalTextModeling(Text text)
5054
        {
5055
            LMSymbol _LMSymbol = null;
5056

    
5057
            LMItemNote _LMItemNote = null;
5058
            LMAAttribute _LMAAttribute = null;
5059

    
5060
            double x = 0;
5061
            double y = 0;
5062
            double angle = text.ANGLE;
5063
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5064

    
5065
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5066
            text.SPPID.SPPID_X = x;
5067
            text.SPPID.SPPID_Y = y;
5068

    
5069
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
5070
            if (_LMSymbol != null)
5071
            {
5072
                _LMSymbol.Commit();
5073
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5074
                if (_LMItemNote != null)
5075
                {
5076
                    _LMItemNote.Commit();
5077
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5078
                    if (_LMAAttribute != null)
5079
                    {
5080
                        _LMAAttribute.set_Value(text.VALUE);
5081
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5082
                        _LMItemNote.Commit();
5083

    
5084

    
5085
                        double[] range = null;
5086
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5087
                        {
5088
                            double[] temp = null;
5089
                            GetSPPIDSymbolRange(labelPersist, ref temp);
5090
                            if (temp != null)
5091
                            {
5092
                                if (range == null)
5093
                                    range = temp;
5094
                                else
5095
                                {
5096
                                    range = new double[] {
5097
                                            Math.Min(range[0], temp[0]),
5098
                                            Math.Min(range[1], temp[1]),
5099
                                            Math.Max(range[2], temp[2]),
5100
                                            Math.Max(range[3], temp[3])
5101
                                        };
5102
                                }
5103
                            }
5104
                        }
5105
                        text.SPPID.Range = range;
5106

    
5107
                        if (_LMAAttribute != null)
5108
                            ReleaseCOMObjects(_LMAAttribute);
5109
                        if (_LMItemNote != null)
5110
                            ReleaseCOMObjects(_LMItemNote);
5111
                    }
5112

    
5113
                    TextCorrectModeling(text);
5114
                }
5115
            }
5116
            if (_LMSymbol != null)
5117
                ReleaseCOMObjects(_LMSymbol);
5118
        }
5119

    
5120
        private void DefaultTextModeling(string value, double x, double y)
5121
        {
5122
            LMSymbol _LMSymbol = null;
5123

    
5124
            LMItemNote _LMItemNote = null;
5125
            LMAAttribute _LMAAttribute = null;
5126

    
5127
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
5128
            if (_LMSymbol != null)
5129
            {
5130
                _LMSymbol.Commit();
5131
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5132
                if (_LMItemNote != null)
5133
                {
5134
                    _LMItemNote.Commit();
5135
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5136
                    if (_LMAAttribute != null)
5137
                    {
5138
                        _LMAAttribute.set_Value(value);
5139
                        _LMItemNote.Commit();
5140

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

    
5152
        private void AssociationTextModeling(Text text)
5153
        {
5154
            LMSymbol _LMSymbol = null;
5155
            LMConnector connectedLMConnector = null;
5156
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5157
            if (owner != null && owner.GetType() == typeof(Symbol))
5158
            {
5159
                Symbol symbol = owner as Symbol;
5160
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5161
                if (_LMSymbol != null)
5162
                {
5163
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5164
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5165
                    {
5166
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5167

    
5168
                        if (mapping != null)
5169
                        {
5170
                            double x = 0;
5171
                            double y = 0;
5172

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

    
5195
                if (connectedLMConnector != null)
5196
                {
5197
                    BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5198
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5199
                    {
5200
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5201

    
5202
                        if (mapping != null)
5203
                        {
5204
                            double x = 0;
5205
                            double y = 0;
5206
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5207
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5208
                            Array array = new double[] { 0, x, y };
5209

    
5210
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5211
                            if (_LMLabelPersist != null)
5212
                            {
5213
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5214
                                _LMLabelPersist.Commit();
5215
                               
5216
                                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_LMLabelPersist.get_GraphicOID().ToString()] as DependencyObject;
5217
                                if (dependency != null)
5218
                                {
5219
                                    radApp.ActiveSelectSet.RemoveAll();
5220
                                    radApp.ActiveSelectSet.Add(dependency);
5221
                                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
5222
                                    transform.DefineByMove2d(x - _LMLabelPersist.get_XCoordinate(), y - _LMLabelPersist.get_YCoordinate());
5223
                                    radApp.ActiveSelectSet.Transform(transform, true);
5224
                                    radApp.ActiveSelectSet.RemoveAll();
5225
                                }
5226

    
5227
                                ReleaseCOMObjects(_LMLabelPersist);
5228
                            }
5229
                        }
5230
                    }
5231
                }
5232
            }
5233
            if (_LMSymbol != null)
5234
                ReleaseCOMObjects(_LMSymbol);
5235
        }
5236

    
5237
        private void TextCorrectModeling(Text text)
5238
        {
5239
            if (text.SPPID.Range == null)
5240
                return;
5241

    
5242
            bool needRemodeling = false;
5243
            bool loop = true;
5244
            GridSetting gridSetting = GridSetting.GetInstance();
5245
            while (loop)
5246
            {
5247
                loop = false;
5248
                foreach (var overlapText in document.TEXTINFOS)
5249
                {
5250
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5251
                        continue;
5252

    
5253
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5254
                    {
5255
                        double percentX = 0;
5256
                        double percentY = 0;
5257
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
5258
                        {
5259
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
5260
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
5261
                        }
5262
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
5263
                        {
5264
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
5265
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
5266
                        }
5267

    
5268
                        double tempX = 0;
5269
                        double tempY = 0;
5270
                        bool overlapX = false;
5271
                        bool overlapY = false;
5272
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5273
                        if (percentX >= percentY)
5274
                        {
5275
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5276
                            double move = gridSetting.Length * count;
5277
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
5278
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
5279
                            needRemodeling = true;
5280
                            loop = true;
5281
                        }
5282
                        else
5283
                        {
5284
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5285
                            double move = gridSetting.Length * count;
5286
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
5287
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
5288
                            needRemodeling = true;
5289
                            loop = true;
5290
                        }
5291
                    }
5292
                }
5293
            }
5294
            
5295

    
5296
            if (needRemodeling)
5297
            {
5298
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
5299
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5300
                text.SPPID.RepresentationId = null;
5301

    
5302
                LMItemNote _LMItemNote = null;
5303
                LMAAttribute _LMAAttribute = null;
5304
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
5305
                if (_LMSymbol != null)
5306
                {
5307
                    _LMSymbol.Commit();
5308
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5309
                    if (_LMItemNote != null)
5310
                    {
5311
                        _LMItemNote.Commit();
5312
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5313
                        if (_LMAAttribute != null)
5314
                        {
5315
                            _LMAAttribute.set_Value(text.VALUE);
5316
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5317
                            _LMItemNote.Commit();
5318

    
5319
                            ReleaseCOMObjects(_LMAAttribute);
5320
                            ReleaseCOMObjects(_LMItemNote);
5321
                        }
5322
                    }
5323
                }
5324

    
5325
                ReleaseCOMObjects(symbol);
5326
                symbol = null;
5327
                ReleaseCOMObjects(_LMItemNote);
5328
                _LMItemNote = null;
5329
                ReleaseCOMObjects(_LMAAttribute);
5330
                _LMAAttribute = null;
5331
                ReleaseCOMObjects(_LMSymbol);
5332
                _LMSymbol = null;
5333
            }
5334
        }
5335

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

    
5361
                            ReleaseCOMObjects(labelPersist);
5362
                        }
5363

    
5364
                        if (allTexts.Count > 0)
5365
                        {
5366
                            #region Sort Text By Y
5367
                            allTexts.Sort(SortTextByY);
5368
                            int SortTextByY(Text a, Text b)
5369
                            {
5370
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
5371
                            }
5372
                            #endregion
5373

    
5374
                            #region 정렬하기전 방향
5375
                            List<Text> left = new List<Text>();
5376
                            List<Text> down = new List<Text>();
5377
                            List<Text> right = new List<Text>();
5378
                            List<Text> up = new List<Text>();
5379
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
5380
                            foreach (var loopText in allTexts)
5381
                            {
5382
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
5383
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
5384
                                double originX = 0;
5385
                                double originY = 0;
5386
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5387
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5388

    
5389
                                if (angle < 45)
5390
                                {
5391
                                    // Text 오른쪽
5392
                                    if (textCenterX > originX)
5393
                                        right.Add(loopText);
5394
                                    // Text 왼쪽
5395
                                    else
5396
                                        left.Add(loopText); 
5397
                                }
5398
                                else
5399
                                {
5400
                                    // Text 아래쪽
5401
                                    if (textCenterY > originY)
5402
                                        down.Add(loopText);
5403
                                    // Text 위쪽
5404
                                    else
5405
                                        up.Add(loopText);
5406
                                }
5407
                            }
5408
                            
5409
                            #endregion
5410

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

    
5453
                                double gapX = 0;
5454
                                double gapY = 0;
5455
                                if (angle < 45)
5456
                                {
5457
                                    // Text 오른쪽
5458
                                    if (textCenterX > originX)
5459
                                    {
5460
                                        gapX = rangeMinX[0] - symbolRange[2];
5461
                                        gapY = allTextCenterY - symbolCenterY;
5462
                                    }
5463
                                    // Text 왼쪽
5464
                                    else
5465
                                    {
5466
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
5467
                                        gapY = allTextCenterY - symbolCenterY;
5468
                                    }
5469
                                }
5470
                                else
5471
                                {
5472
                                    // Text 아래쪽
5473
                                    if (textCenterY > originY)
5474
                                    {
5475
                                        gapX = allTextCenterX - symbolCenterX;
5476
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
5477
                                    }
5478
                                    // Text 위쪽
5479
                                    else
5480
                                    {
5481
                                        gapX = allTextCenterX - symbolCenterX;
5482
                                        gapY = rangeMinY[0] - symbolRange[3];
5483
                                    }
5484
                                }
5485

    
5486
                                foreach (var item in texts)
5487
                                {
5488
                                    MoveText(item, gapX, gapY);
5489
                                    RemodelingAssociationText(item);
5490
                                }
5491
                                #endregion
5492
                            }
5493
                        }
5494
                    }
5495
                }
5496

    
5497
                void MoveText(Text moveText, double x, double y)
5498
                {
5499
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
5500
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
5501
                    moveText.SPPID.Range = new double[] {
5502
                        moveText.SPPID.Range[0] - x,
5503
                        moveText.SPPID.Range[1]- y,
5504
                        moveText.SPPID.Range[2]- x,
5505
                        moveText.SPPID.Range[3]- y
5506
                    };
5507
                }
5508

    
5509
                endTexts.AddRange(allTexts);
5510

    
5511
                ReleaseCOMObjects(targetLabel);
5512
                targetLabel = null;
5513
                ReleaseCOMObjects(representation);
5514
                representation = null;
5515
            }
5516
        }
5517

    
5518
        private void RemodelingAssociationText(Text text)
5519
        {
5520
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5521
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5522
            removeLabel.Commit();
5523
            ReleaseCOMObjects(removeLabel);
5524
            removeLabel = null;
5525

    
5526
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5527
            if (owner != null && owner.GetType() == typeof(Symbol))
5528
            {
5529
                Symbol symbol = owner as Symbol;
5530
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5531
                if (_LMSymbol != null)
5532
                {
5533
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5534
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5535
                    {
5536
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5537

    
5538
                        if (mapping != null)
5539
                        {
5540
                            double x = 0;
5541
                            double y = 0;
5542

    
5543
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5544
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5545
                            if (_LMLabelPersist != null)
5546
                            {
5547
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5548
                                _LMLabelPersist.Commit();
5549
                            }
5550
                            ReleaseCOMObjects(_LMLabelPersist);
5551
                            _LMLabelPersist = null;
5552
                        }
5553
                    }
5554
                }
5555
                ReleaseCOMObjects(_LMSymbol);
5556
                _LMSymbol = null;
5557
            }
5558
        }
5559

    
5560
        /// <summary>
5561
        /// Note Modeling
5562
        /// </summary>
5563
        /// <param name="note"></param>
5564
        private void NoteModeling(Note note, List<Note> correctList)
5565
        {
5566
            LMSymbol _LMSymbol = null;
5567
            LMItemNote _LMItemNote = null;
5568
            LMAAttribute _LMAAttribute = null;
5569

    
5570
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5571
            {
5572
                double x = 0;
5573
                double y = 0;
5574

    
5575
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5576
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5577
                note.SPPID.SPPID_X = x;
5578
                note.SPPID.SPPID_Y = y;
5579

    
5580
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5581
                if (_LMSymbol != null)
5582
                {
5583
                    _LMSymbol.Commit();
5584
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5585
                    if (_LMItemNote != null)
5586
                    {
5587
                        _LMItemNote.Commit();
5588
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5589
                        if (_LMAAttribute != null)
5590
                        {
5591
                            _LMAAttribute.set_Value(note.VALUE);
5592
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5593

    
5594
                            double[] range = null;
5595
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5596
                            {
5597
                                double[] temp = null;
5598
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5599
                                if (temp != null)
5600
                                {
5601
                                    if (range == null)
5602
                                        range = temp;
5603
                                    else
5604
                                    {
5605
                                        range = new double[] {
5606
                                            Math.Min(range[0], temp[0]),
5607
                                            Math.Min(range[1], temp[1]),
5608
                                            Math.Max(range[2], temp[2]),
5609
                                            Math.Max(range[3], temp[3])
5610
                                        };
5611
                                    }
5612
                                }
5613
                            }
5614
                            if (range != null)
5615
                                correctList.Add(note);
5616
                            note.SPPID.Range = range;
5617

    
5618

    
5619
                            _LMItemNote.Commit();
5620
                        }
5621
                    }
5622
                }
5623
            }
5624

    
5625
            if (_LMAAttribute != null)
5626
                ReleaseCOMObjects(_LMAAttribute);
5627
            if (_LMItemNote != null)
5628
                ReleaseCOMObjects(_LMItemNote);
5629
            if (_LMSymbol != null)
5630
                ReleaseCOMObjects(_LMSymbol);
5631
        }
5632

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

    
5673

    
5674
            if (needRemodeling)
5675
            {
5676
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5677
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5678
                note.SPPID.RepresentationId = null;
5679

    
5680
                LMItemNote _LMItemNote = null;
5681
                LMAAttribute _LMAAttribute = null;
5682
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5683
                if (_LMSymbol != null)
5684
                {
5685
                    _LMSymbol.Commit();
5686
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5687
                    if (_LMItemNote != null)
5688
                    {
5689
                        _LMItemNote.Commit();
5690
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5691
                        if (_LMAAttribute != null)
5692
                        {
5693
                            _LMAAttribute.set_Value(note.VALUE);
5694
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5695
                            _LMItemNote.Commit();
5696

    
5697
                            ReleaseCOMObjects(_LMAAttribute);
5698
                            ReleaseCOMObjects(_LMItemNote);
5699
                        }
5700
                    }
5701
                }
5702

    
5703
                ReleaseCOMObjects(symbol);
5704
                symbol = null;
5705
                ReleaseCOMObjects(_LMItemNote);
5706
                _LMItemNote = null;
5707
                ReleaseCOMObjects(_LMAAttribute);
5708
                _LMAAttribute = null;
5709
                ReleaseCOMObjects(_LMSymbol);
5710
                _LMSymbol = null;
5711
            }
5712

    
5713
            endList.Add(note);
5714
        }
5715

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

    
5755
        /// <summary>
5756
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5757
        /// </summary>
5758
        /// <param name="x"></param>
5759
        /// <param name="y"></param>
5760
        /// <param name="originX"></param>
5761
        /// <param name="originY"></param>
5762
        /// <param name="SPPIDLabelLocation"></param>
5763
        /// <param name="location"></param>
5764
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5765
        {
5766
            if (location == Location.None)
5767
            {
5768
                x = originX;
5769
                y = originY;
5770
            }
5771
            else
5772
            {
5773
                if (location.HasFlag(Location.Center))
5774
                {
5775
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5776
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5777
                }
5778

    
5779
                if (location.HasFlag(Location.Left))
5780
                    x = SPPIDLabelLocation.X1;
5781
                else if (location.HasFlag(Location.Right))
5782
                    x = SPPIDLabelLocation.X2;
5783

    
5784
                if (location.HasFlag(Location.Down))
5785
                    y = SPPIDLabelLocation.Y1;
5786
                else if (location.HasFlag(Location.Up))
5787
                    y = SPPIDLabelLocation.Y2;
5788
            }
5789
        }
5790

    
5791
        /// <summary>
5792
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5793
        /// 1. Angle Valve
5794
        /// 2. 3개로 이루어진 Symbol Group
5795
        /// </summary>
5796
        /// <returns></returns>
5797
        private List<Symbol> GetPrioritySymbol()
5798
        {
5799
            DataTable symbolTable = document.SymbolTable;
5800
            // List에 순서대로 쌓는다.
5801
            List<Symbol> symbols = new List<Symbol>();
5802

    
5803
            // Angle Valve 부터
5804
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5805
            {
5806
                if (!symbols.Contains(symbol))
5807
                {
5808
                    double originX = 0;
5809
                    double originY = 0;
5810

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

    
5815
                    SlopeType slopeType1 = SlopeType.None;
5816
                    SlopeType slopeType2 = SlopeType.None;
5817
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5818
                    {
5819
                        double connectorX = 0;
5820
                        double connectorY = 0;
5821
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5822
                        if (slopeType1 == SlopeType.None)
5823
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5824
                        else
5825
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5826
                    }
5827

    
5828
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5829
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5830
                        symbols.Add(symbol);
5831
                }
5832
            }
5833

    
5834
            List<Symbol> tempSymbols = new List<Symbol>();
5835
            // Conn 갯수 기준
5836
            foreach (var item in document.SYMBOLS)
5837
            {
5838
                if (!symbols.Contains(item))
5839
                    tempSymbols.Add(item);
5840
            }
5841
            tempSymbols.Sort(SortSymbolPriority);
5842
            symbols.AddRange(tempSymbols);
5843

    
5844
            return symbols;
5845
        }
5846

    
5847
        private void SetPriorityLine(List<Line> lines)
5848
        {
5849
            lines.Sort(SortLinePriority);
5850

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

    
5886
                            }
5887
                        }
5888
                    }
5889
                }
5890

    
5891
                return 0;
5892
            }
5893

    
5894
            int CompareNotSegmentLine(Line a, Line b)
5895
            {
5896
                List<Connector> connectorsA = a.CONNECTORS
5897
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5898
                    .ToList();
5899

    
5900
                List<Connector> connectorsB = b.CONNECTORS
5901
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5902
                    .ToList();
5903

    
5904
                // 오름차순
5905
                return connectorsB.Count.CompareTo(connectorsA.Count);
5906
            }
5907

    
5908
            int CompareConnSymbol(Line a, Line b)
5909
            {
5910
                List<Connector> connectorsA = a.CONNECTORS
5911
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5912
                    .ToList();
5913

    
5914
                List<Connector> connectorsB = b.CONNECTORS
5915
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5916
                    .ToList();
5917

    
5918
                // 오름차순
5919
                return connectorsB.Count.CompareTo(connectorsA.Count);
5920
            }
5921

    
5922
            int CompareConnItem(Line a, Line b)
5923
            {
5924
                List<Connector> connectorsA = a.CONNECTORS
5925
                    .Where(conn => conn.ConnectedObject != null && 
5926
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5927
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5928
                    .ToList();
5929

    
5930
                List<Connector> connectorsB = b.CONNECTORS
5931
                    .Where(conn => conn.ConnectedObject != null &&
5932
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5933
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5934
                    .ToList();
5935

    
5936
                // 오름차순
5937
                return connectorsB.Count.CompareTo(connectorsA.Count);
5938
            }
5939

    
5940
            int CompareBranchLine(Line a, Line b)
5941
            {
5942
                List<Connector> connectorsA = a.CONNECTORS
5943
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5944
                    .ToList();
5945
                List<Connector> connectorsB = b.CONNECTORS
5946
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5947
                    .ToList();
5948

    
5949
                // 내림차순
5950
                return connectorsA.Count.CompareTo(connectorsB.Count);
5951
            }
5952

    
5953
            int CompareNoneConn(Line a, Line b)
5954
            {
5955
                List<Connector> connectorsA = a.CONNECTORS
5956
                    .Where(conn => conn.ConnectedObject == null)
5957
                    .ToList();
5958

    
5959
                List<Connector> connectorsB = b.CONNECTORS
5960
                    .Where(conn => conn.ConnectedObject == null)
5961
                    .ToList();
5962

    
5963
                // 오름차순
5964
                return connectorsB.Count.CompareTo(connectorsA.Count);
5965
            }
5966
        }
5967

    
5968
        private void SortText(List<Text> texts)
5969
        {
5970
            texts.Sort(Sort);
5971

    
5972
            int Sort(Text a, Text b)
5973
            {
5974
                int yRetval = CompareY(a, b);
5975
                if (yRetval != 0)
5976
                {
5977
                    return yRetval;
5978
                }
5979
                else
5980
                {
5981
                    return CompareX(a, b);
5982
                }
5983
            }
5984

    
5985
            int CompareY(Text a, Text b)
5986
            {
5987
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
5988
            }
5989

    
5990
            int CompareX(Text a, Text b)
5991
            {
5992
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
5993
            }
5994
        }
5995
        private void SortNote(List<Note> notes)
5996
        {
5997
            notes.Sort(Sort);
5998

    
5999
            int Sort(Note a, Note b)
6000
            {
6001
                int yRetval = CompareY(a, b);
6002
                if (yRetval != 0)
6003
                {
6004
                    return yRetval;
6005
                }
6006
                else
6007
                {
6008
                    return CompareX(a, b);
6009
                }
6010
            }
6011

    
6012
            int CompareY(Note a, Note b)
6013
            {
6014
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6015
            }
6016

    
6017
            int CompareX(Note a, Note b)
6018
            {
6019
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6020
            }
6021
        }
6022

    
6023
        private void SortBranchLines()
6024
        {
6025
            BranchLines.Sort(SortBranchLine);
6026
            int SortBranchLine(Line a, Line b)
6027
            {
6028
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6029
                 x.ConnectedObject.GetType() == typeof(Line) &&
6030
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
6031
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6032

    
6033
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6034
                 x.ConnectedObject.GetType() == typeof(Line) &&
6035
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
6036
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6037

    
6038
                // 내림차순
6039
                return countA.CompareTo(countB);
6040
            }
6041
        }
6042

    
6043
        private static int SortSymbolPriority(Symbol a, Symbol b)
6044
        {
6045
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6046
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6047
            int retval = countB.CompareTo(countA);
6048
            if (retval != 0)
6049
                return retval;
6050
            else
6051
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
6052
        }
6053

    
6054
        private string GetSPPIDFileName(LMModelItem modelItem)
6055
        {
6056
            string symbolPath = null;
6057
            foreach (LMRepresentation rep in modelItem.Representations)
6058
            {
6059
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6060
                {
6061
                    symbolPath = rep.get_FileName();
6062
                    break;
6063
                }
6064
            }
6065
            return symbolPath;
6066
        }
6067

    
6068
        private string GetSPPIDFileName(string modelItemId)
6069
        {
6070
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6071
            string symbolPath = null;
6072
            foreach (LMRepresentation rep in modelItem.Representations)
6073
            {
6074
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6075
                {
6076
                    symbolPath = rep.get_FileName();
6077
                    break;
6078
                }
6079
            }
6080
            ReleaseCOMObjects(modelItem);
6081
            return symbolPath;
6082
        }
6083

    
6084
        /// <summary>
6085
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
6086
        /// </summary>
6087
        /// <param name="graphicOID"></param>
6088
        /// <param name="milliseconds"></param>
6089
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
6090
        {
6091
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
6092
            {
6093
                double minX = 0;
6094
                double minY = 0;
6095
                double maxX = 0;
6096
                double maxY = 0;
6097
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
6098
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
6099

    
6100
                Thread.Sleep(milliseconds);
6101
            }
6102
        }
6103

    
6104
        /// <summary>
6105
        /// ComObject를 Release
6106
        /// </summary>
6107
        /// <param name="objVars"></param>
6108
        public void ReleaseCOMObjects(params object[] objVars)
6109
        {
6110
            if (objVars != null)
6111
            {
6112
                int intNewRefCount = 0;
6113
                foreach (object obj in objVars)
6114
                {
6115
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
6116
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
6117
                }
6118
            }
6119
        }
6120

    
6121
        /// IDisposable 구현
6122
        ~AutoModeling()
6123
        {
6124
            this.Dispose(false);
6125
        }
6126

    
6127
        private bool disposed;
6128
        public void Dispose()
6129
        {
6130
            this.Dispose(true);
6131
            GC.SuppressFinalize(this);
6132
        }
6133

    
6134
        protected virtual void Dispose(bool disposing)
6135
        {
6136
            if (this.disposed) return;
6137
            if (disposing)
6138
            {
6139
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
6140
            }
6141
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
6142
            this.disposed = true;
6143
        }
6144
    }
6145
}
클립보드 이미지 추가 (최대 크기: 500 MB)