프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / DTI_PID / SPPIDConverter / AutoModeling.cs @ d02afdce

이력 | 보기 | 이력해설 | 다운로드 (289 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
    [Flags]
28
    public enum SegmentLocation
29
    {
30
        None = 0,
31
        Right = 1,
32
        Left = 2,
33
        Down = 4,
34
        Up = 8
35
    }
36
    public class AutoModeling : IDisposable
37
    {
38
        Placement _placement;
39
        LMADataSource dataSource;
40
        string drawingID;
41
        dynamic newDrawing;
42
        dynamic application;
43
        bool closeDocument;
44
        Ingr.RAD2D.Application radApp;
45
        SPPID_Document document;
46
        ETCSetting _ETCSetting;
47

    
48
        public string DocumentLabelText { get; set; }
49

    
50
        List<Line> BranchLines = new List<Line>();
51
        List<string> ZeroLengthSymbolToSymbolModelItemID = new List<string>();
52
        List<string> ZeroLengthModelItemID = new List<string>();
53
        List<string> ZeroLengthModelItemIDReverse = new List<string>();
54
        List<Symbol> prioritySymbols;
55
        List<string> FlowMarkRepIds = new List<string>();
56

    
57
        public AutoModeling(SPPID_Document document, bool closeDocument)
58
        {
59
            application = Interaction.GetObject("", "PIDAutomation.Application");
60
            WrapperApplication wApp = new WrapperApplication(application.Application);
61
            radApp = wApp.RADApplication;
62

    
63
            this.closeDocument = closeDocument;
64
            this.document = document;
65
            this._ETCSetting = ETCSetting.GetInstance();
66
        }
67

    
68
        private void SetSystemEditingCommand(bool value)
69
        {
70
            foreach (var item in radApp.Commands)
71
            {
72
                if (item.Argument == "SystemEditingCmd.SystemEditing")
73
                {
74
                    if (item.Checked != value)
75
                    {
76
                        radApp.RunMacro("systemeditingcmd.dll");
77
                        break;
78
                    }
79

    
80
                }
81
            }
82
        }
83

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

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

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

    
164
                if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible)
165
                {
166
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.ClearParent, null);
167
                    SplashScreenManager.CloseForm(false);
168
                    Log.Write("\r\n");
169
                }
170
                Thread.Sleep(1000);
171

    
172
                Log.Write("End Modeling");
173
                radApp.ActiveWindow.Fit();
174

    
175
                ReleaseCOMObjects(application);
176
                application = null;
177
                if (radApp.ActiveDocument != null)
178
                {
179
                    if (closeDocument && newDrawing != null)
180
                    {
181
                        newDrawing.Save();
182
                        newDrawing.CloseDrawing(true);
183
                        ReleaseCOMObjects(newDrawing);
184
                        newDrawing = null;
185
                    }
186
                    else if (newDrawing == null)
187
                    {
188
                        Log.Write("error document");
189
                    }
190
                }
191

    
192
                ReleaseCOMObjects(dataSource);
193
                dataSource = null;
194
                ReleaseCOMObjects(_placement);
195
                _placement = null;
196

    
197
                Thread.Sleep(1000);
198
            }
199
        }
200

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

    
270
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetAllProgress, step1_Line.Count);
271
            SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.SetStep, "Line Modeling - 1");
272

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

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

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

    
350
                        GridSetting grid = GridSetting.GetInstance();
351
                        int count = grid.DrainValveCellCount;
352
                        double length = grid.Length;
353

    
354
                        // 길이 확인
355
                        if (!string.IsNullOrEmpty(item.SPPID.ModelItemId))
356
                        {
357
                            LMConnector _LMConnector = GetLMConnectorOnlyOne(item.SPPID.ModelItemId);
358
                            if (_LMConnector != null)
359
                            {
360
                                double[] connectorRange = GetConnectorRange(_LMConnector);
361
                                double connectorLength = double.NaN;
362
                                if (item.SlopeType == SlopeType.HORIZONTAL)
363
                                    connectorLength = connectorRange[2] - connectorRange[0];
364
                                else if (item.SlopeType == SlopeType.VERTICAL)
365
                                    connectorLength = connectorRange[3] - connectorRange[1];
366

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

    
411
                                    // 제거
412
                                    RemoveSymbol(connSymbol);
413
                                    RemoveLine(item);
414

    
415
                                    // 재생성
416
                                    SymbolModelingBySymbol(connSymbol);
417
                                    NewLineModeling(item, true);
418
                                }
419
                            }
420

    
421
                            ReleaseCOMObjects(_LMConnector);
422
                            _LMConnector = null;
423
                        }
424
                    }
425
                    SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
426
                }
427
                catch (Exception ex)
428
                {
429
                    Log.Write("Error in NewLineModeling");
430
                    Log.Write("UID : " + item.UID);
431
                    Log.Write(ex.Message);
432
                    Log.Write(ex.StackTrace);
433
                }
434

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

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

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

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

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

    
596
                LMRelationships relationships = new LMRelationships();
597
                relationships.Collect(dataSource, Filter: filter);
598

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

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

    
758
                    }
759
                }
760
                SplashScreenManager.Default.SendCommand(SPPIDSplashScreen.SplashScreenCommand.UpProgress, null);
761
            }
762

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

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

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

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

    
1050
                //current LMDrawing 가져오기
1051
                LMAFilter filter = new LMAFilter();
1052
                LMACriterion criterion = new LMACriterion();
1053
                filter.ItemType = "Drawing";
1054
                criterion.SourceAttributeName = "Name";
1055
                criterion.Operator = "=";
1056
                criterion.set_ValueAttribute(drawingName);
1057
                filter.get_Criteria().Add(criterion);
1058

    
1059
                LMDrawings drawings = new LMDrawings();
1060
                drawings.Collect(dataSource, Filter: filter);
1061

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

    
1088
                        drawingAttributeDT.Dispose();
1089
                    }
1090

    
1091
                    ReleaseCOMObjects(drawing);
1092
                }
1093

    
1094
                drawingID = ((dynamic)drawings).Nth(1).Id;
1095
                ReleaseCOMObjects(filter);
1096
                ReleaseCOMObjects(criterion);
1097
                ReleaseCOMObjects(drawings);
1098
                filter = null;
1099
                criterion = null;
1100
                drawings = null;
1101
            }
1102
            else
1103
                Log.Write("Fail Create Drawing");
1104

    
1105
            if (newDrawing != null)
1106
            {
1107
                SetBorderFile();
1108
                return true;
1109
            }
1110
            else
1111
                return false;
1112
        }
1113

    
1114
        private void SetBorderFile()
1115
        {
1116
            ETCSetting setting = ETCSetting.GetInstance();
1117

    
1118
            if (!string.IsNullOrEmpty(setting.BorderFilePath) && System.IO.File.Exists(setting.BorderFilePath))
1119
            {
1120
                foreach (Ingr.RAD2D.SmartFrame2d smartFrame in radApp.ActiveDocument.ActiveSheet.SmartFrames2d)
1121
                {
1122
                    if (!string.IsNullOrEmpty(smartFrame.LinkMoniker) && smartFrame.LinkMoniker != setting.BorderFilePath)
1123
                    {
1124
                        smartFrame.ChangeSource(Ingr.RAD2D.OLEInsertionTypeConstant.igOLELinked, setting.BorderFilePath, true);
1125
                        smartFrame.Update();
1126
                    }
1127
                        
1128
                }
1129
            }
1130
        }
1131

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

    
1142
            List<string> drawingNameList = new List<string>();
1143
            List<string> drawingNumberList = new List<string>();
1144

    
1145
            foreach (LMDrawing item in drawings)
1146
            {
1147
                drawingNameList.Add(item.Attributes["Name"].get_Value().ToString());
1148
                drawingNumberList.Add(item.Attributes["DrawingNumber"].get_Value().ToString());
1149
            }
1150

    
1151
            int nameLength = drawingName.Length;
1152
            while (drawingNameList.Contains(drawingName))
1153
            {
1154
                if (nameLength == drawingName.Length)
1155
                    drawingName += "-1";
1156
                else
1157
                {
1158
                    int index = Convert.ToInt32(drawingName.Remove(0, nameLength + 1));
1159
                    drawingName = drawingName.Substring(0, nameLength + 1);
1160
                    drawingName += ++index;
1161
                }
1162
            }
1163

    
1164
            int numberLength = drawingNumber.Length;
1165
            while (drawingNameList.Contains(drawingNumber))
1166
            {
1167
                if (numberLength == drawingNumber.Length)
1168
                    drawingNumber += "-1";
1169
                else
1170
                {
1171
                    int index = Convert.ToInt32(drawingNumber.Remove(0, numberLength + 1));
1172
                    drawingNumber = drawingNumber.Substring(0, numberLength + 1);
1173
                    drawingNumber += ++index;
1174
                }
1175
            }
1176
            ReleaseCOMObjects(drawings);
1177
            drawings = null;
1178
        }
1179

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

    
1205
            if (Settings.Default.DrawingX != 0 && Settings.Default.DrawingY != 0)
1206
            {
1207
                Log.Write("Setting Drawing X, Drawing Y");
1208
                document.SetSPPIDLocation(Settings.Default.DrawingX, Settings.Default.DrawingY);
1209
                Log.Write("Start coordinate correction");
1210
                document.CoordinateCorrection();
1211
                return true;
1212
            }
1213
            else
1214
            {
1215
                Log.Write("Need Drawing X, Y");
1216
                return false;
1217
            }
1218
        }
1219

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

    
1235
            LMSymbol _LMSymbol = null;
1236

    
1237
            string mappingPath = symbol.SPPID.MAPPINGNAME;
1238
            double x = symbol.SPPID.ORIGINAL_X;
1239
            double y = symbol.SPPID.ORIGINAL_Y;
1240
            int mirror = 0;
1241
            double angle = symbol.ANGLE;
1242

    
1243
            // OPC 일경우 180도 일때 Mirror
1244
            if (mappingPath.Contains("Piping OPC's") && angle == Math.PI)
1245
                mirror = 1;
1246

    
1247
            // Mirror 계산
1248
            if (symbol.FLIP == 1)
1249
            {
1250
                mirror = 1;
1251
                angle += Math.PI;
1252
            }
1253

    
1254
            if (targetSymbol != null && !string.IsNullOrEmpty(targetSymbol.SPPID.RepresentationId))
1255
            {
1256
                LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);   /// RepresentationId로 SPPID 심볼을 찾음
1257
                Connector connector = SPPIDUtil.FindSymbolConnectorByUID(document, symbol.UID, targetSymbol);
1258
                if (connector != null)
1259
                    GetTargetSymbolConnectorPoint(connector, targetSymbol, ref x, ref y);
1260

    
1261
                LMConnector temp = LineModelingForSymbolZeroLength(symbol, _TargetItem, x, y);
1262
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle, TargetItem: _TargetItem);
1263
                if (temp != null)
1264
                    _placement.PIDRemovePlacement(temp.AsLMRepresentation());
1265
                ReleaseCOMObjects(temp);
1266
                temp = null;
1267

    
1268
                if (_LMSymbol != null && _TargetItem != null)
1269
                    symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1270

    
1271
                ReleaseCOMObjects(_TargetItem);
1272
            }
1273
            else
1274
                _LMSymbol = _placement.PIDPlaceSymbol(mappingPath, x, y, Mirror: mirror, Rotation: angle);
1275

    
1276
            if (_LMSymbol != null)
1277
            {
1278
                _LMSymbol.Commit();
1279

    
1280
                // ConnCheck
1281
                List<string> ids = new List<string>();
1282
                foreach (LMConnector item in _LMSymbol.Connect1Connectors)
1283
                {
1284
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1285
                        ids.Add(item.Id);
1286
                    ReleaseCOMObjects(item);
1287
                }
1288
                foreach (LMConnector item in _LMSymbol.Connect2Connectors)
1289
                {
1290
                    if (item.get_ItemStatus() == "Active" && !ids.Contains(item.Id))
1291
                        ids.Add(item.Id);
1292
                    ReleaseCOMObjects(item);
1293
                }
1294

    
1295
                int createdSymbolCount = document.SYMBOLS.FindAll(i => i.CONNECTORS.Find(j => j.CONNECTEDITEM == symbol.UID) != null && !string.IsNullOrEmpty(i.SPPID.RepresentationId)).Count;
1296
                if (targetSymbol == null && ids.Count != createdSymbolCount)
1297
                {
1298
                    double currentX = _LMSymbol.get_XCoordinate();
1299
                    double currentY = _LMSymbol.get_YCoordinate();
1300

    
1301

    
1302
                }
1303

    
1304
                symbol.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
1305
                symbol.SPPID.ModelItemID = _LMSymbol.ModelItemID;
1306
                symbol.SPPID.GraphicOID = _LMSymbol.get_GraphicOID().ToString();
1307

    
1308
                foreach (var item in symbol.ChildSymbols)
1309
                    CreateChildSymbol(item, _LMSymbol, symbol);
1310

    
1311
                symbol.SPPID.SPPID_X = _LMSymbol.get_XCoordinate();
1312
                symbol.SPPID.SPPID_Y = _LMSymbol.get_YCoordinate();
1313

    
1314
                double[] range = null;
1315
                GetSPPIDSymbolRange(symbol, ref range);
1316
                symbol.SPPID.SPPID_Min_X = range[0];
1317
                symbol.SPPID.SPPID_Min_Y = range[1];
1318
                symbol.SPPID.SPPID_Max_X = range[2];
1319
                symbol.SPPID.SPPID_Max_Y = range[3];
1320

    
1321
                foreach (var item in symbol.SPPID.CorrectionX_GroupSymbols)
1322
                    item.SPPID.ORIGINAL_X = symbol.SPPID.SPPID_X;
1323
                foreach (var item in symbol.SPPID.CorrectionY_GroupSymbols)
1324
                    item.SPPID.ORIGINAL_Y = symbol.SPPID.SPPID_Y;
1325

    
1326
                ReleaseCOMObjects(_LMSymbol);
1327
            }
1328
        }
1329
        /// <summary>
1330
        /// targetX와 targetY 기준 제일 먼 PipingPoint에 TempLine Modeling
1331
        /// Signal Point는 고려하지 않음
1332
        /// </summary>
1333
        /// <param name="symbol"></param>
1334
        /// <param name="_TargetItem"></param>
1335
        /// <param name="targetX"></param>
1336
        /// <param name="targetY"></param>
1337
        /// <returns></returns>
1338
        private LMConnector LineModelingForSymbolZeroLength(Symbol symbol, LMSymbol _TargetItem, double targetX, double targetY)
1339
        {
1340
            LMConnector tempConnector = null;
1341

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

    
1367
                            double calcDistance = SPPIDUtil.CalcPointToPointdDistance(targetX, targetY, tempX, tempY);
1368
                            if (calcDistance > length)
1369
                            {
1370
                                lineX = tempX;
1371
                                lineY = tempY;
1372
                            }
1373
                        }
1374

    
1375
                        _LMAItem _LMAItem = _placement.PIDCreateItem(sppidLine);
1376
                        PlaceRunInputs placeRunInputs = new PlaceRunInputs();
1377
                        placeRunInputs.AddPoint(-1, -1);
1378
                        placeRunInputs.AddSymbolTarget(_TargetItem, lineX, lineY);
1379
                        tempConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
1380
                        if (tempConnector != null)
1381
                            tempConnector.Commit();
1382
                        ReleaseCOMObjects(_LMAItem);
1383
                        _LMAItem = null;
1384
                        ReleaseCOMObjects(placeRunInputs);
1385
                        placeRunInputs = null;
1386
                    }
1387
                }
1388
            }
1389

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

    
1419
            List<double[]> info = new List<double[]>();
1420
            if (pipingPoints != null)
1421
            {
1422
                foreach (LMPipingPoint pipingPoint in pipingPoints)
1423
                {
1424
                    foreach (LMAAttribute attribute in pipingPoint.Attributes)
1425
                    {
1426
                        if (attribute.Name == "PipingPointNumber")
1427
                        {
1428
                            int index = Convert.ToInt32(attribute.get_Value());
1429
                            if (info.Find(loopX => loopX[0] == index) == null)
1430
                            {
1431
                                double x = 0;
1432
                                double y = 0;
1433
                                if (_placement.PIDConnectPointLocation(symbol, index, ref x, ref y))
1434
                                    info.Add(new double[] { index, x, y });
1435
                            }
1436
                        }
1437
                    }
1438
                }
1439
            }
1440
            ReleaseCOMObjects(modelItem);
1441
            modelItem = null;
1442
            ReleaseCOMObjects(pipingPoints);
1443
            pipingPoints = null;
1444

    
1445
            return info;
1446
        }
1447

    
1448
        private void RemoveSymbol(Symbol symbol)
1449
        {
1450
            if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1451
            {
1452
                LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1453
                if (_LMSymbol != null)
1454
                {
1455
                    _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1456
                    ReleaseCOMObjects(_LMSymbol);
1457
                }
1458
            }
1459

    
1460
            symbol.SPPID.RepresentationId = string.Empty;
1461
            symbol.SPPID.ModelItemID = string.Empty;
1462
            symbol.SPPID.SPPID_X = double.NaN;
1463
            symbol.SPPID.SPPID_Y = double.NaN;
1464
            symbol.SPPID.SPPID_Min_X = double.NaN;
1465
            symbol.SPPID.SPPID_Min_Y = double.NaN;
1466
            symbol.SPPID.SPPID_Max_X = double.NaN;
1467
            symbol.SPPID.SPPID_Max_Y = double.NaN;
1468
        }
1469

    
1470
        private void RemoveSymbol(List<Symbol> symbols)
1471
        {
1472
            foreach (var symbol in symbols)
1473
            {
1474
                if (!string.IsNullOrEmpty(symbol.SPPID.RepresentationId))
1475
                {
1476
                    LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
1477
                    if (_LMSymbol != null)
1478
                    {
1479
                        _placement.PIDRemovePlacement(_LMSymbol.AsLMRepresentation());
1480
                        ReleaseCOMObjects(_LMSymbol);
1481
                    }
1482
                }
1483

    
1484
                symbol.SPPID.RepresentationId = string.Empty;
1485
                symbol.SPPID.ModelItemID = string.Empty;
1486
                symbol.SPPID.SPPID_X = double.NaN;
1487
                symbol.SPPID.SPPID_Y = double.NaN;
1488
                symbol.SPPID.SPPID_Min_X = double.NaN;
1489
                symbol.SPPID.SPPID_Min_Y = double.NaN;
1490
                symbol.SPPID.SPPID_Max_X = double.NaN;
1491
                symbol.SPPID.SPPID_Max_Y = double.NaN;
1492
            }
1493
        }
1494

    
1495
        /// <summary>
1496
        /// ID2의 Symbol Width와 Height를 비교해서 상대적인 SPPID Connector좌표를 가져온다.
1497
        /// </summary>
1498
        /// <param name="targetConnector"></param>
1499
        /// <param name="targetSymbol"></param>
1500
        /// <param name="x"></param>
1501
        /// <param name="y"></param>
1502
        private void GetTargetSymbolConnectorPoint(Connector targetConnector, Symbol targetSymbol, ref double x, ref double y)
1503
        {
1504
            LMSymbol _TargetItem = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
1505

    
1506
            double[] range = null;
1507
            List<double[]> points = new List<double[]>();
1508
            GetSPPIDSymbolRangeAndConnectionPoints(targetSymbol, ref range, points);
1509
            double x1 = range[0];
1510
            double y1 = range[1];
1511
            double x2 = range[2];
1512
            double y2 = range[3];
1513

    
1514
            // Origin 기준 Connector의 위치차이
1515
            double sceneX = 0;
1516
            double sceneY = 0;
1517
            SPPIDUtil.ConvertPointBystring(targetConnector.SCENECONNECTPOINT, ref sceneX, ref sceneY);
1518
            double originX = 0;
1519
            double originY = 0;
1520
            SPPIDUtil.ConvertPointBystring(targetSymbol.ORIGINALPOINT, ref originX, ref originY);
1521
            double gapX = originX - sceneX;
1522
            double gapY = originY - sceneY;
1523

    
1524
            // SPPID Symbol과 ID2 심볼의 크기 차이
1525
            double sizeWidth = 0;
1526
            double sizeHeight = 0;
1527
            SPPIDUtil.ConvertPointBystring(targetSymbol.SIZE, ref sizeWidth, ref sizeHeight);
1528
            if (sizeWidth == 0 || sizeHeight == 0)
1529
                throw new Exception("Check symbol size! \r\nUID : " + targetSymbol.UID);
1530

    
1531
            double percentX = (x2 - x1) / sizeWidth;
1532
            double percentY = (y2 - y1) / sizeHeight;
1533

    
1534
            double SPPIDgapX = gapX * percentX;
1535
            double SPPIDgapY = gapY * percentY;
1536

    
1537
            double[] SPPIDOriginPoint = new double[] { _TargetItem.get_XCoordinate() - SPPIDgapX, _TargetItem.get_YCoordinate() + SPPIDgapY };
1538
            double distance = double.MaxValue;
1539
            double[] resultPoint;
1540
            foreach (var point in points)
1541
            {
1542
                double result = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], SPPIDOriginPoint[0], SPPIDOriginPoint[1]);
1543
                if (distance > result)
1544
                {
1545
                    distance = result;
1546
                    resultPoint = point;
1547
                    x = point[0];
1548
                    y = point[1];
1549
                }
1550
            }
1551

    
1552
            ReleaseCOMObjects(_TargetItem);
1553
        }
1554

    
1555
        private void GetTargetLineConnectorPoint(Connector targetConnector, Line targetLine, ref double x, ref double y)
1556
        {
1557
            int index = targetLine.CONNECTORS.IndexOf(targetConnector);
1558
            if (index == 0)
1559
            {
1560
                x = targetLine.SPPID.START_X;
1561
                y = targetLine.SPPID.START_Y;
1562
            }
1563
            else
1564
            {
1565
                x = targetLine.SPPID.END_X;
1566
                y = targetLine.SPPID.END_Y;
1567
            }
1568
        }
1569

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

    
1594
            foreach (var childSymbol in symbol.ChildSymbols)
1595
                GetSPPIDChildSymbolRange(childSymbol, ref range, points);
1596

    
1597
            ReleaseCOMObjects(_TargetItem);
1598
        }
1599

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

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

    
1684
                if (!bOnlySymbol)
1685
                {
1686
                    foreach (var childSymbol in symbol.ChildSymbols)
1687
                        GetSPPIDChildSymbolRange(childSymbol, ref range);
1688
                }
1689
                ReleaseCOMObjects(_TargetItem);
1690
            }
1691
        }
1692

    
1693
        private void GetSPPIDSymbolRange(LMLabelPersist labelPersist, ref double[] range)
1694
        {
1695
            if (labelPersist != null)
1696
            {
1697
                double x1 = double.MaxValue;
1698
                double y1 = double.MaxValue;
1699
                double x2 = double.MinValue;
1700
                double y2 = double.MinValue;
1701
                range = new double[] { x1, y1, x2, y2 };
1702

    
1703
                Ingr.RAD2D.DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[labelPersist.get_GraphicOID().ToString()] as DependencyObject;
1704
                foreach (var item in dependency.DrawingObjects)
1705
                {
1706
                    Ingr.RAD2D.TextBox textBox = item as Ingr.RAD2D.TextBox;
1707
                    if (textBox != null)
1708
                    {
1709
                        if (dependency != null)
1710
                        {
1711
                            double tempX1;
1712
                            double tempY1;
1713
                            double tempX2;
1714
                            double tempY2;
1715
                            textBox.Range(out tempX1, out tempY1, out tempX2, out tempY2);
1716
                            x1 = Math.Min(x1, tempX1);
1717
                            y1 = Math.Min(y1, tempY1);
1718
                            x2 = Math.Max(x2, tempX2);
1719
                            y2 = Math.Max(y2, tempY2);
1720

    
1721
                            range = new double[] { x1, y1, x2, y2 };
1722
                        }
1723
                    }
1724
                }
1725
                
1726
            }
1727
        }
1728

    
1729
        private void GetSPPIDSymbolRange(List<Symbol> symbols, ref double[] range, bool bOnlySymbol = false, bool bForGraphic = false)
1730
        {
1731
            double[] tempRange = new double[] { double.MaxValue, double.MaxValue, double.MinValue, double.MinValue };
1732
            foreach (var symbol in symbols)
1733
            {
1734
                double[] symbolRange = null;
1735
                GetSPPIDSymbolRange(symbol, ref symbolRange, bOnlySymbol, bForGraphic);
1736

    
1737
                tempRange[0] = Math.Min(tempRange[0], symbolRange[0]);
1738
                tempRange[1] = Math.Min(tempRange[1], symbolRange[1]);
1739
                tempRange[2] = Math.Max(tempRange[2], symbolRange[2]);
1740
                tempRange[3] = Math.Max(tempRange[3], symbolRange[3]);
1741

    
1742
                foreach (var childSymbol in symbol.ChildSymbols)
1743
                    GetSPPIDChildSymbolRange(childSymbol, ref tempRange);
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: symbol.ANGLE, 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, bForGraphic: true);
2124
                                    double[] groupRange = null;
2125
                                    GetSPPIDSymbolRange(group, ref groupRange, bForGraphic: true);
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, bForGraphic: true);
2171
                                    double[] connRange = null;
2172
                                    GetSPPIDSymbolRange(connSymbol, ref connRange, bForGraphic: true);
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
                SegmentLocation location;
3034
                double[] point = GetSegmentPoint(ownerObj, connectedItem, targetLMConnector, out location);
3035
                Array array = null;
3036
                if (point != null)
3037
                    array = new double[] { 0, point[0], point[1] };
3038
                else
3039
                    array = new double[] { 0, endBreak.SPPID.ORIGINAL_X, endBreak.SPPID.ORIGINAL_Y };
3040
                LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(endBreak.SPPID.MAPPINGNAME, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: leaderLine);
3041
                if (_LmLabelPersist != null)
3042
                {
3043
                    _LmLabelPersist.Commit();
3044
                    endBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3045
                    if (_LmLabelPersist.ModelItemObject != null)
3046
                        endBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3047
                    endBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3048

    
3049
                    MoveDependencyObject(endBreak.SPPID.GraphicOID, location);
3050

    
3051
                    ReleaseCOMObjects(_LmLabelPersist);
3052
                }
3053
                ReleaseCOMObjects(targetLMConnector);
3054
            }
3055
            else
3056
            {
3057
                Log.Write("End Break UID : " + endBreak.UID);
3058
                Log.Write("Can't find targetLMConnector");
3059
            }
3060
        }
3061

    
3062
        private void MoveDependencyObject(string graphicOID, SegmentLocation location)
3063
        {
3064
            double x = 0, y = 0;
3065
            if (location.HasFlag(SegmentLocation.Up))
3066
                y = GridSetting.GetInstance().Length * 3;
3067
            else if (location.HasFlag(SegmentLocation.Down))
3068
                y = -GridSetting.GetInstance().Length * 3;
3069

    
3070
            if (location.HasFlag(SegmentLocation.Right))
3071
                x = GridSetting.GetInstance().Length * 3;
3072
            else if (location.HasFlag(SegmentLocation.Left))
3073
                x = -GridSetting.GetInstance().Length * 3;
3074

    
3075
            if (x != 0 || y != 0)
3076
            {
3077
                radApp.ActiveSelectSet.RemoveAll();
3078
                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] as DependencyObject;
3079
                if (dependency != null)
3080
                {
3081
                    radApp.ActiveSelectSet.Add(dependency);
3082
                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
3083
                    transform.DefineByMove2d(x, y);
3084
                    radApp.ActiveSelectSet.Transform(transform, true);
3085
                    radApp.ActiveSelectSet.RemoveAll();
3086
                }
3087
            }
3088
        }
3089

    
3090
        private LMConnector ReModelingZeroLengthLMConnectorForSegment(LMConnector connector, string changeSymbolPath = null)
3091
        {
3092
            string symbolPath = string.Empty;
3093
            #region get symbol path
3094
            if (string.IsNullOrEmpty(changeSymbolPath))
3095
            {
3096
                LMModelItem modelItem = dataSource.GetModelItem(connector.ModelItemID);
3097
                symbolPath = GetSPPIDFileName(modelItem);
3098
                ReleaseCOMObjects(modelItem);
3099
            }
3100
            else
3101
                symbolPath = changeSymbolPath;
3102
            
3103
            #endregion
3104

    
3105
            LMConnector newConnector = null;
3106
            dynamic OID = connector.get_GraphicOID().ToString();
3107
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3108
            Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3109
            int verticesCount = lineStringGeometry.VertexCount;
3110
            PlaceRunInputs placeRunInputs = new PlaceRunInputs();
3111
            _LMAItem _LMAItem = _placement.PIDCreateItem(symbolPath);
3112

    
3113
            if (Convert.ToBoolean(connector.get_IsZeroLength()))
3114
            {
3115
                double[] vertices = null;
3116
                lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3117
                double x = 0;
3118
                double y = 0;
3119
                lineStringGeometry.GetVertex(1, ref x, ref y);
3120

    
3121
                string flowDirection = string.Empty;
3122
                LMAAttribute flowAttribute = connector.ModelItemObject.Attributes["FlowDirection"];
3123
                if (flowAttribute != null && !DBNull.Value.Equals(flowAttribute.get_Value()))
3124
                    flowDirection = flowAttribute.get_Value().ToString();
3125

    
3126
                if (flowDirection == "End 1 is downstream (Outlet)")
3127
                {
3128
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3129
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3130
                    flowDirection = "End 1 is upstream (Inlet)";
3131
                }
3132
                else
3133
                {
3134
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem1SymbolObject, x, y);
3135
                    placeRunInputs.AddSymbolTarget(connector.ConnectItem2SymbolObject, x, y);
3136
                }
3137
                string oldModelItemId = connector.ModelItemID;
3138
                _placement.PIDRemovePlacement(connector.AsLMRepresentation());
3139
                newConnector = _placement.PIDPlaceRun(_LMAItem, placeRunInputs);
3140
                newConnector.Commit();
3141
                ZeroLengthSymbolToSymbolModelItemID.Add(newConnector.ModelItemID);
3142
                if (!string.IsNullOrEmpty(flowDirection))
3143
                    newConnector.ModelItemObject.Attributes["FlowDirection"].set_Value(flowDirection);
3144
                ReleaseCOMObjects(connector);
3145

    
3146
                foreach (var line in document.LINES.FindAll(z => z.SPPID.ModelItemId == oldModelItemId))
3147
                {
3148
                    foreach (var repId in line.SPPID.Representations)
3149
                    {
3150
                        LMConnector _connector = dataSource.GetConnector(repId);
3151
                        if (_connector != null && _connector.get_ItemStatus() == "Active")
3152
                        {
3153
                            if (line.SPPID.ModelItemId != _connector.ModelItemID)
3154
                            {
3155
                                line.SPPID.ModelItemId = _connector.ModelItemID;
3156
                                line.SPPID.Representations = GetRepresentations(line.SPPID.ModelItemId);
3157
                            }
3158
                        }
3159
                        ReleaseCOMObjects(_connector);
3160
                        _connector = null;
3161
                    }
3162
                }
3163
            }
3164

    
3165
            return newConnector;
3166
        }
3167

    
3168
        /// <summary>
3169
        /// SpecBreak Modeling 메서드
3170
        /// </summary>
3171
        /// <param name="specBreak"></param>
3172
        private void SpecBreakModeling(SpecBreak specBreak)
3173
        {
3174
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
3175
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
3176

    
3177
            if (upStreamObj != null &&
3178
                downStreamObj != null)
3179
            {
3180
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
3181
                if (upStreamObj.GetType() == typeof(Symbol) && downStreamObj.GetType() == typeof(Symbol) && 
3182
                    targetLMConnector != null && 
3183
                    !IsModelingEndBreak(upStreamObj as Symbol, downStreamObj as Symbol))
3184
                    targetLMConnector = ReModelingZeroLengthLMConnectorForSegment(targetLMConnector);
3185

    
3186
                if (targetLMConnector != null)
3187
                {
3188
                    foreach (var attribute in specBreak.ATTRIBUTES)
3189
                    {
3190
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID);
3191
                        if (mapping != null && !string.IsNullOrEmpty(mapping.SPPIDSYMBOLNAME) && mapping.SPPIDSYMBOLNAME != "None")
3192
                        {
3193
                            string MappingPath = mapping.SPPIDSYMBOLNAME;
3194
                            SegmentLocation location;
3195
                            double[] point = GetSegmentPoint(upStreamObj, downStreamObj, targetLMConnector, out location);
3196
                            Array array = null;
3197
                            if (point != null)
3198
                                array = new double[] { 0, point[0], point[1] };
3199
                            else
3200
                                array = new double[] { 0, specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y };
3201
                            LMLabelPersist _LmLabelPersist = _placement.PIDPlaceLabel(MappingPath, ref array, LabeledItem: targetLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
3202

    
3203
                            if (_LmLabelPersist != null)
3204
                            {
3205
                                _LmLabelPersist.Commit();
3206
                                specBreak.SPPID.RepresentationId = _LmLabelPersist.AsLMRepresentation().Id;
3207
                                if (_LmLabelPersist.ModelItemObject != null)
3208
                                    specBreak.SPPID.ModelItemID = _LmLabelPersist.ModelItemID;
3209
                                specBreak.SPPID.GraphicOID = _LmLabelPersist.get_GraphicOID().ToString();
3210

    
3211
                                MoveDependencyObject(specBreak.SPPID.GraphicOID, location);
3212

    
3213
                                ReleaseCOMObjects(_LmLabelPersist);
3214
                            }
3215

    
3216
                            // temp
3217
                            ReleaseCOMObjects(_placement.PIDPlaceSymbol(@"\Design\Annotation\Graphics\Break.sym", specBreak.SPPID.ORIGINAL_X, specBreak.SPPID.ORIGINAL_Y, Rotation: specBreak.ANGLE));
3218
                        }
3219
                    }
3220
                    ReleaseCOMObjects(targetLMConnector);
3221
                }
3222
                else
3223
                {
3224
                    Log.Write("Spec Break UID : " + specBreak.UID);
3225
                    Log.Write("Can't find targetLMConnector");
3226
                }
3227
            }
3228
        }
3229

    
3230
        private LMConnector FindBreakLineTarget(object targetObj, object connectedObj)
3231
        {
3232
            LMConnector targetConnector = null;
3233
            Symbol targetSymbol = targetObj as Symbol;
3234
            Symbol connectedSymbol = connectedObj as Symbol;
3235
            Line targetLine = targetObj as Line;
3236
            Line connectedLine = connectedObj as Line;
3237
            if (targetSymbol != null && connectedSymbol != null)
3238
            {
3239
                LMSymbol targetLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3240
                LMSymbol connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3241

    
3242
                foreach (LMConnector connector in targetLMSymbol.Avoid1Connectors)
3243
                {
3244
                    if (connector.get_ItemStatus() != "Active")
3245
                        continue;
3246

    
3247
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3248
                    {
3249
                        targetConnector = connector;
3250
                        break;
3251
                    }
3252
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3253
                    {
3254
                        targetConnector = connector;
3255
                        break;
3256
                    }
3257
                }
3258

    
3259
                foreach (LMConnector connector in targetLMSymbol.Avoid2Connectors)
3260
                {
3261
                    if (connector.get_ItemStatus() != "Active")
3262
                        continue;
3263

    
3264
                    if (connector.ConnectItem1SymbolObject.Id == connectedLMSymbol.Id)
3265
                    {
3266
                        targetConnector = connector;
3267
                        break;
3268
                    }
3269
                    else if (connector.ConnectItem2SymbolObject.Id == connectedLMSymbol.Id)
3270
                    {
3271
                        targetConnector = connector;
3272
                        break;
3273
                    }
3274
                }
3275

    
3276
                ReleaseCOMObjects(targetLMSymbol);
3277
                ReleaseCOMObjects(connectedLMSymbol);
3278
            }
3279
            else if (targetLine != null && connectedLine != null)
3280
            {
3281
                LMModelItem targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3282
                LMModelItem connectedModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3283

    
3284
                if (targetModelItem != null && targetModelItem.get_ItemStatus() == "Active" && connectedModelItem != null && connectedModelItem.get_ItemStatus() == "Active")
3285
                {
3286
                    foreach (LMRepresentation rep in targetModelItem.Representations)
3287
                    {
3288
                        if (targetConnector != null)
3289
                            break;
3290

    
3291
                        if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3292
                        {
3293
                            LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3294

    
3295
                            if (IsConnected(_LMConnector, connectedModelItem))
3296
                                targetConnector = _LMConnector;
3297
                            else
3298
                                ReleaseCOMObjects(_LMConnector);
3299
                        }
3300
                    }
3301

    
3302
                    ReleaseCOMObjects(targetModelItem);
3303
                }
3304
            }
3305
            else
3306
            {
3307
                LMSymbol connectedLMSymbol = null;
3308
                if (connectedSymbol != null)
3309
                    connectedLMSymbol = dataSource.GetSymbol(connectedSymbol.SPPID.RepresentationId);
3310
                else if (targetSymbol != null)
3311
                    connectedLMSymbol = dataSource.GetSymbol(targetSymbol.SPPID.RepresentationId);
3312
                else
3313
                {
3314

    
3315
                }
3316
                LMModelItem targetModelItem = null;
3317
                if (targetLine != null)
3318
                    targetModelItem = dataSource.GetModelItem(targetLine.SPPID.ModelItemId);
3319
                else if (connectedLine != null)
3320
                    targetModelItem = dataSource.GetModelItem(connectedLine.SPPID.ModelItemId);
3321
                else
3322
                {
3323

    
3324
                }
3325
                if (connectedLMSymbol != null && targetModelItem != null)
3326
                {
3327
                    foreach (LMConnector connector in connectedLMSymbol.Avoid1Connectors)
3328
                    {
3329
                        if (connector.get_ItemStatus() != "Active")
3330
                            continue;
3331

    
3332
                        if (IsConnected(connector, targetModelItem))
3333
                        {
3334
                            targetConnector = connector;
3335
                            break;
3336
                        }
3337
                    }
3338

    
3339
                    if (targetConnector == null)
3340
                    {
3341
                        foreach (LMConnector connector in connectedLMSymbol.Avoid2Connectors)
3342
                        {
3343
                            if (connector.get_ItemStatus() != "Active")
3344
                                continue;
3345

    
3346
                            if (IsConnected(connector, targetModelItem))
3347
                            {
3348
                                targetConnector = connector;
3349
                                break;
3350
                            }
3351
                        }
3352
                    }
3353
                }
3354

    
3355
            }
3356

    
3357
            return targetConnector;
3358
        }
3359

    
3360
        private double[] GetSegmentPoint(object targetObj, object connObj, LMConnector targetConnector, out SegmentLocation location)
3361
        {
3362
            double[] result = null;
3363
            Line targetLine = targetObj as Line;
3364
            Symbol targetSymbol = targetObj as Symbol;
3365
            Line connLine = connObj as Line;
3366
            Symbol connSymbol = connObj as Symbol;
3367
            location = SegmentLocation.None;
3368
            if (Convert.ToBoolean(targetConnector.get_IsZeroLength()))
3369
            {
3370
                result = GetConnectorVertices(targetConnector)[0];
3371
                if (targetSymbol != null && connSymbol != null)
3372
                {
3373
                    SlopeType slopeType = SPPIDUtil.CalcSlope(targetSymbol.SPPID.SPPID_X, targetSymbol.SPPID.SPPID_Y, connSymbol.SPPID.SPPID_X, connSymbol.SPPID.SPPID_Y);
3374
                    result = new double[] { result[0], result[1] };
3375
                    if (slopeType == SlopeType.HORIZONTAL)
3376
                        location = SegmentLocation.Up;
3377
                    else if (slopeType == SlopeType.VERTICAL)
3378
                        location = SegmentLocation.Right;
3379
                }
3380
                else if (targetLine != null)
3381
                {
3382
                    result = new double[] { result[0], result[1] };
3383
                    if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3384
                        location = SegmentLocation.Up;
3385
                    else if (targetLine.SlopeType == SlopeType.VERTICAL)
3386
                        location = SegmentLocation.Right;
3387
                }
3388
                else if (connLine != null)
3389
                {
3390
                    result = new double[] { result[0], result[1] };
3391
                    if (connLine.SlopeType == SlopeType.HORIZONTAL)
3392
                        location = SegmentLocation.Up;
3393
                    else if (connLine.SlopeType == SlopeType.VERTICAL)
3394
                        location = SegmentLocation.Right;
3395
                }
3396
            }
3397
            else
3398
            {
3399
                if (targetObj.GetType() == typeof(Line) && connObj.GetType() == typeof(Line))
3400
                {
3401
                    Line line = connObj as Line;
3402
                    LMConnector connectedConnector = null;
3403
                    int connIndex = 0;
3404
                    LMModelItem modelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
3405
                    FindConnectedConnector(targetConnector, modelItem, ref connectedConnector, ref connIndex);
3406

    
3407
                    List<double[]> vertices = GetConnectorVertices(targetConnector);
3408

    
3409
                    ReleaseCOMObjects(modelItem);
3410
                    ReleaseCOMObjects(connectedConnector);
3411

    
3412
                    if (vertices.Count > 0)
3413
                    {
3414
                        if (connIndex == 1)
3415
                            result = vertices[0];
3416
                        else if (connIndex == 2)
3417
                            result = vertices[vertices.Count - 1];
3418

    
3419
                        if (targetLine.SlopeType == SlopeType.HORIZONTAL)
3420
                        {
3421
                            result = new double[] { result[0], result[1] };
3422
                            location = SegmentLocation.Up;
3423
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3424
                                location = location | SegmentLocation.Right;
3425
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3426
                                location = location | SegmentLocation.Left;
3427
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X < targetLine.SPPID.END_X)
3428
                                location = location | SegmentLocation.Left;
3429
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_X > targetLine.SPPID.END_X)
3430
                                location = location | SegmentLocation.Right;
3431
                        }
3432
                        else if (targetLine.SlopeType == SlopeType.VERTICAL)
3433
                        {
3434
                            result = new double[] { result[0], result[1] };
3435
                            location = SegmentLocation.Right;
3436
                            if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3437
                                location = location | SegmentLocation.Up;
3438
                            else if (targetLine.CONNECTORS[0].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3439
                                location = location | SegmentLocation.Down;
3440
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y < targetLine.SPPID.END_Y)
3441
                                location = location | SegmentLocation.Down;
3442
                            else if (targetLine.CONNECTORS[1].CONNECTEDITEM == connLine.UID && targetLine.SPPID.START_Y > targetLine.SPPID.END_Y)
3443
                                location = location | SegmentLocation.Up;
3444
                        }
3445
                            
3446
                    }
3447
                }
3448
                else
3449
                {
3450
                    Log.Write("error in GetSegemtPoint");
3451
                }
3452
            }
3453

    
3454
            return result;
3455
        }
3456

    
3457
        private bool IsConnected(LMConnector connector, LMModelItem modelItem)
3458
        {
3459
            bool result = false;
3460

    
3461
            foreach (LMRepresentation rep in modelItem.Representations)
3462
            {
3463
                if (result)
3464
                    break;
3465

    
3466
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3467
                {
3468
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3469

    
3470
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3471
                        connector.ConnectItem1SymbolObject != null &&
3472
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3473
                    {
3474
                        result = true;
3475
                        ReleaseCOMObjects(_LMConnector);
3476
                        break;
3477
                    }
3478
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3479
                        connector.ConnectItem2SymbolObject != null &&
3480
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3481
                    {
3482
                        result = true;
3483
                        ReleaseCOMObjects(_LMConnector);
3484
                        break;
3485
                    }
3486
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3487
                        connector.ConnectItem1SymbolObject != null &&
3488
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3489
                    {
3490
                        result = true;
3491
                        ReleaseCOMObjects(_LMConnector);
3492
                        break;
3493
                    }
3494
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3495
                        connector.ConnectItem2SymbolObject != null &&
3496
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3497
                    {
3498
                        result = true;
3499
                        ReleaseCOMObjects(_LMConnector);
3500
                        break;
3501
                    }
3502

    
3503
                    ReleaseCOMObjects(_LMConnector);
3504
                }
3505
            }
3506

    
3507

    
3508
            return result;
3509
        }
3510

    
3511
        private void FindConnectedConnector(LMConnector connector, LMModelItem modelItem, ref LMConnector connectedConnector, ref int connectorIndex)
3512
        {
3513
            foreach (LMRepresentation rep in modelItem.Representations)
3514
            {
3515
                if (connectedConnector != null)
3516
                    break;
3517

    
3518
                if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3519
                {
3520
                    LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3521

    
3522
                    if (_LMConnector.ConnectItem1SymbolObject != null &&
3523
                        connector.ConnectItem1SymbolObject != null &&
3524
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3525
                    {
3526
                        connectedConnector = _LMConnector;
3527
                        connectorIndex = 1;
3528
                        break;
3529
                    }
3530
                    else if (_LMConnector.ConnectItem1SymbolObject != null &&
3531
                        connector.ConnectItem2SymbolObject != null &&
3532
                        _LMConnector.ConnectItem1SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3533
                    {
3534
                        connectedConnector = _LMConnector;
3535
                        connectorIndex = 2;
3536
                        break;
3537
                    }
3538
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3539
                        connector.ConnectItem1SymbolObject != null &&
3540
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem1SymbolObject.Id)
3541
                    {
3542
                        connectedConnector = _LMConnector;
3543
                        connectorIndex = 1;
3544
                        break;
3545
                    }
3546
                    else if (_LMConnector.ConnectItem2SymbolObject != null &&
3547
                        connector.ConnectItem2SymbolObject != null &&
3548
                        _LMConnector.ConnectItem2SymbolObject.Id == connector.ConnectItem2SymbolObject.Id)
3549
                    {
3550
                        connectedConnector = _LMConnector;
3551
                        connectorIndex = 2;
3552
                        break;
3553
                    }
3554

    
3555
                    if (connectedConnector == null)
3556
                        ReleaseCOMObjects(_LMConnector);
3557
                }
3558
            }
3559
        }
3560

    
3561
        /// <summary>
3562
        /// FromModelItem을 ToModelItem으로 PipeRunJoin하는 메서드
3563
        /// </summary>
3564
        /// <param name="modelItemID1"></param>
3565
        /// <param name="modelItemID2"></param>
3566
        private void JoinRun(string modelId1, string modelId2, ref string survivorId, bool IsSameConnector = true)
3567
        {
3568
            try
3569
            {
3570
                LMModelItem modelItem1 = dataSource.GetModelItem(modelId1);
3571
                LMConnector connector1 = GetLMConnectorFirst(modelId1);
3572
                List<double[]> vertices1 = null;
3573
                string graphicOID1 = string.Empty;
3574
                if (connector1 != null)
3575
                {
3576
                    vertices1 = GetConnectorVertices(connector1);
3577
                    graphicOID1 = connector1.get_GraphicOID();
3578
                }
3579
                _LMAItem item1 = modelItem1.AsLMAItem();
3580
                ReleaseCOMObjects(connector1);
3581
                connector1 = null;
3582

    
3583
                LMModelItem modelItem2 = dataSource.GetModelItem(modelId2);
3584
                LMConnector connector2 = GetLMConnectorFirst(modelId2);
3585
                List<double[]> vertices2 = null;
3586
                string graphicOID2 = string.Empty;
3587
                if (connector2 != null)
3588
                {
3589
                    vertices2 = GetConnectorVertices(connector2);
3590
                    graphicOID2 = connector2.get_GraphicOID();
3591
                }
3592
                _LMAItem item2 = modelItem2.AsLMAItem();
3593
                ReleaseCOMObjects(connector2);
3594
                connector2 = null;
3595

    
3596
                // item2가 item1으로 조인
3597
                _placement.PIDJoinRuns(ref item1, ref item2);
3598
                item1.Commit();
3599
                item2.Commit();
3600

    
3601
                string beforeID = string.Empty;
3602
                string afterID = string.Empty;
3603

    
3604
                if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() != "Active")
3605
                {
3606
                    beforeID = modelItem2.Id;
3607
                    afterID = modelItem1.Id;
3608
                    survivorId = afterID;
3609
                }
3610
                else if (modelItem1.get_ItemStatus() != "Active" && modelItem2.get_ItemStatus() == "Active")
3611
                {
3612
                    beforeID = modelItem1.Id;
3613
                    afterID = modelItem2.Id;
3614
                    survivorId = afterID;
3615
                }
3616
                else if (modelItem1.get_ItemStatus() == "Active" && modelItem2.get_ItemStatus() == "Active")
3617
                {
3618
                    int model1Cnt = GetConnectorCount(modelId1);
3619
                    int model2Cnt = GetConnectorCount(modelId2);
3620
                    if (model1Cnt == 0)
3621
                    {
3622
                        beforeID = modelItem1.Id;
3623
                        afterID = modelItem2.Id;
3624
                        survivorId = afterID;
3625
                    }
3626
                    else if (model2Cnt == 0)
3627
                    {
3628
                        beforeID = modelItem2.Id;
3629
                        afterID = modelItem1.Id;
3630
                        survivorId = afterID;
3631
                    }
3632
                    else
3633
                        survivorId = null;
3634
                }
3635
                else
3636
                {
3637
                    Log.Write("잘못된 경우");
3638
                    survivorId = null;
3639
                }
3640

    
3641
                if (!string.IsNullOrEmpty(beforeID) && !string.IsNullOrEmpty(afterID))
3642
                {
3643
                    List<Line> lines = SPPIDUtil.FindLinesByModelId(document, beforeID);
3644
                    foreach (var line in lines)
3645
                        line.SPPID.ModelItemId = afterID;
3646
                }
3647

    
3648
                ReleaseCOMObjects(modelItem1);
3649
                ReleaseCOMObjects(item1);
3650
                ReleaseCOMObjects(modelItem2);
3651
                ReleaseCOMObjects(item2);
3652
            }
3653
            catch (Exception ex)
3654
            {
3655
                Log.Write("Join Error");
3656
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3657
            }
3658
        }
3659

    
3660
        private bool IsModelingEndBreak(Symbol symbol1, Symbol symbol2)
3661
        {
3662
            bool result = false;
3663
            List<EndBreak> endBreaks = document.EndBreaks.FindAll(x =>
3664
           (x.OWNER == symbol1.UID || x.OWNER == symbol2.UID) &&
3665
           (x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol1.UID || x.PROPERTIES.Find(y => y.ATTRIBUTE == "Connected Item").VALUE == symbol2.UID));
3666

    
3667
            foreach (var item in endBreaks)
3668
            {
3669
                if (!string.IsNullOrEmpty(item.SPPID.RepresentationId))
3670
                {
3671
                    result = true;
3672
                    break;
3673
                }
3674
            }
3675

    
3676
            return result;
3677
        }
3678
        private List<string> FindOtherModelItemBySymbolWhereTypePipeRun(LMSymbol symbol, string modelId)
3679
        {
3680
            List<string> temp = new List<string>();
3681
            List<LMConnector> connectors = new List<LMConnector>();
3682
            foreach (LMConnector connector in symbol.Avoid1Connectors)
3683
            {
3684
                if (connector.get_ItemStatus() != "Active")
3685
                    continue;
3686

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

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

    
3698

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

    
3707
            foreach (LMConnector connector in symbol.Avoid2Connectors)
3708
            {
3709
                if (connector.get_ItemStatus() != "Active")
3710
                    continue;
3711

    
3712
                LMModelItem modelItem = connector.ModelItemObject;
3713
                LMSymbol connOtherSymbol = FindOtherConnectedSymbol(connector);
3714
                if (modelItem.get_ItemStatus() == "Active" && modelItem.get_ItemTypeName().ToString() == "PipeRun" && modelItem.Id != modelId && !temp.Contains(modelItem.Id))
3715
                    temp.Add(modelItem.Id);
3716

    
3717
                if (temp.Contains(modelItem.Id) &&
3718
                    connOtherSymbol != null &&
3719
                    connOtherSymbol.get_RepresentationType() == "Branch" &&
3720
                    Convert.ToBoolean(connector.get_IsZeroLength()))
3721
                    temp.Remove(modelItem.Id);
3722

    
3723
                if (temp.Contains(modelItem.Id))
3724
                    connectors.Add(connector);
3725
                ReleaseCOMObjects(connOtherSymbol);
3726
                connOtherSymbol = null;
3727
                ReleaseCOMObjects(modelItem);
3728
                modelItem = null;
3729
            }
3730

    
3731

    
3732
            List<string> result = new List<string>();
3733
            string originalName = GetSPPIDFileName(modelId);
3734
            foreach (var connector in connectors)
3735
            {
3736
                string fileName = GetSPPIDFileName(connector.ModelItemID);
3737
                if (originalName == fileName)
3738
                    result.Add(connector.ModelItemID);
3739
                else
3740
                {
3741
                    if (document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID) == null && Convert.ToBoolean(connector.get_IsZeroLength()))
3742
                        result.Add(connector.ModelItemID);
3743
                    else
3744
                    {
3745
                        Line line1 = document.LINES.Find(x => x.SPPID.ModelItemId == modelId);
3746
                        Line line2 = document.LINES.Find(x => x.SPPID.ModelItemId == connector.ModelItemID.ToString());
3747
                        if (line1 != null && line2 != null && line1.TYPE == line2.TYPE)
3748
                            result.Add(connector.ModelItemID);
3749
                    }
3750
                }
3751
            }
3752

    
3753
            foreach (var connector in connectors)
3754
                ReleaseCOMObjects(connector);
3755
            
3756
            return result;
3757

    
3758

    
3759
            LMSymbol FindOtherConnectedSymbol(LMConnector connector)
3760
            {
3761
                LMSymbol findResult = null;
3762
                if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.Id != symbol.Id && connector.ConnectItem1SymbolObject.get_ItemStatus() == "Active")
3763
                    findResult = connector.ConnectItem1SymbolObject;
3764
                else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.Id != symbol.Id && connector.ConnectItem2SymbolObject.get_ItemStatus() == "Active")
3765
                    findResult = connector.ConnectItem2SymbolObject;
3766

    
3767
                return findResult;
3768
            }
3769
        }
3770

    
3771
        /// <summary>
3772
        /// PipeRun의 좌표를 가져오는 메서드
3773
        /// </summary>
3774
        /// <param name="modelId"></param>
3775
        /// <returns></returns>
3776
        private Dictionary<LMConnector, List<double[]>> GetPipeRunVertices(string modelId, bool ContainZeroLength = true)
3777
        {
3778
            Dictionary<LMConnector, List<double[]>> connectorVertices = new Dictionary<LMConnector, List<double[]>>();
3779
            LMModelItem modelItem = dataSource.GetModelItem(modelId);
3780

    
3781
            if (modelItem != null)
3782
            {
3783
                foreach (LMRepresentation rep in modelItem.Representations)
3784
                {
3785
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
3786
                    {
3787
                        LMConnector _LMConnector = dataSource.GetConnector(rep.Id);
3788
                        if (!ContainZeroLength && Convert.ToBoolean(_LMConnector.get_IsZeroLength()))
3789
                        {
3790
                            ReleaseCOMObjects(_LMConnector);
3791
                            _LMConnector = null;
3792
                            continue;
3793
                        }
3794
                        connectorVertices.Add(_LMConnector, new List<double[]>());
3795
                        dynamic OID = rep.get_GraphicOID().ToString();
3796
                        DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3797
                        Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3798
                        int verticesCount = lineStringGeometry.VertexCount;
3799
                        double[] vertices = null;
3800
                        lineStringGeometry.GetVertices(ref verticesCount, ref vertices);
3801
                        for (int i = 0; i < verticesCount; i++)
3802
                        {
3803
                            double x = 0;
3804
                            double y = 0;
3805
                            lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3806
                            connectorVertices[_LMConnector].Add(new double[] { x, y });
3807
                        }
3808
                    }
3809
                }
3810

    
3811
                ReleaseCOMObjects(modelItem);
3812
            }
3813

    
3814
            return connectorVertices;
3815
        }
3816

    
3817
        private List<double[]> GetConnectorVertices(LMConnector connector)
3818
        {
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
                }
3835
            }
3836
            return vertices;
3837
        }
3838

    
3839
        private double GetConnectorDistance(LMConnector connector)
3840
        {
3841
            double result = 0;
3842
            List<double[]> vertices = new List<double[]>();
3843
            if (connector != null)
3844
            {
3845
                dynamic OID = connector.get_GraphicOID().ToString();
3846
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3847
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3848
                int verticesCount = lineStringGeometry.VertexCount;
3849
                double[] value = null;
3850
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3851
                for (int i = 0; i < verticesCount; i++)
3852
                {
3853
                    double x = 0;
3854
                    double y = 0;
3855
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3856
                    vertices.Add(new double[] { x, y });
3857
                    if (vertices.Count > 1)
3858
                    {
3859
                        result += SPPIDUtil.CalcPointToPointdDistance(vertices[vertices.Count - 2][0], vertices[vertices.Count - 2][1], x, y);
3860
                    }
3861
                }
3862
            }
3863
            return result;
3864
        }
3865
        private double[] GetConnectorRange(LMConnector connector)
3866
        {
3867
            double[] result = null;
3868
            List<double[]> vertices = new List<double[]>();
3869
            if (connector != null)
3870
            {
3871
                dynamic OID = connector.get_GraphicOID().ToString();
3872
                DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[OID];
3873
                double minX = 0;
3874
                double minY = 0;
3875
                double maxX = 0;
3876
                double maxY = 0;
3877

    
3878
                drawingObject.Range(out minX, out minY, out maxX, out maxY);
3879
                result = new double[] { minX, minY, maxX, maxY };
3880
            }
3881
            return result;
3882
        }
3883
        private List<double[]> GetConnectorVertices(dynamic graphicOID)
3884
        {
3885
            List<double[]> vertices = null;
3886
            DependencyObject drawingObject = radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID];
3887
            if (drawingObject != null)
3888
            {
3889
                vertices = new List<double[]>();
3890
                Ingr.RAD2D.LineStringGeometry2d lineStringGeometry = drawingObject.GetGeometry() as Ingr.RAD2D.LineStringGeometry2d;
3891
                int verticesCount = lineStringGeometry.VertexCount;
3892
                double[] value = null;
3893
                lineStringGeometry.GetVertices(ref verticesCount, ref value);
3894
                for (int i = 0; i < verticesCount; i++)
3895
                {
3896
                    double x = 0;
3897
                    double y = 0;
3898
                    lineStringGeometry.GetVertex(i + 1, ref x, ref y);
3899
                    vertices.Add(new double[] { x, y });
3900
                }
3901
            }
3902
            return vertices;
3903
        }
3904
        /// <summary>
3905
        /// 좌표로 PipeRun의 Connector중에 어느 Connector에 가까운지/붙을지 가져오는 메서드 - 조건에 안맞아서 못찾을시 제일 가까운 점으로 가져오는 방식
3906
        /// </summary>
3907
        /// <param name="connectorVertices"></param>
3908
        /// <param name="connX"></param>
3909
        /// <param name="connY"></param>
3910
        /// <returns></returns>
3911
        private LMConnector FindTargetLMConnectorForLabel(Dictionary<LMConnector, List<double[]>> connectorVertices, double connX, double connY)
3912
        {
3913
            double length = double.MaxValue;
3914
            LMConnector targetConnector = null;
3915
            foreach (var item in connectorVertices)
3916
            {
3917
                List<double[]> points = item.Value;
3918
                for (int i = 0; i < points.Count - 1; i++)
3919
                {
3920
                    double[] point1 = points[i];
3921
                    double[] point2 = points[i + 1];
3922
                    double x1 = Math.Min(point1[0], point2[0]);
3923
                    double y1 = Math.Min(point1[1], point2[1]);
3924
                    double x2 = Math.Max(point1[0], point2[0]);
3925
                    double y2 = Math.Max(point1[1], point2[1]);
3926

    
3927
                    if ((x1 <= connX && x2 >= connX) ||
3928
                        (y1 <= connY && y2 >= connY))
3929
                    {
3930
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point1[0], point1[1], connX, connY);
3931
                        if (length >= distance)
3932
                        {
3933
                            targetConnector = item.Key;
3934
                            length = distance;
3935
                        }
3936

    
3937
                        distance = SPPIDUtil.CalcPointToPointdDistance(point2[0], point2[1], connX, connY);
3938
                        if (length >= distance)
3939
                        {
3940
                            targetConnector = item.Key;
3941
                            length = distance;
3942
                        }
3943
                    }
3944
                }
3945
            }
3946

    
3947
            // 못찾았을때.
3948
            length = double.MaxValue;
3949
            if (targetConnector == null)
3950
            {
3951
                foreach (var item in connectorVertices)
3952
                {
3953
                    List<double[]> points = item.Value;
3954

    
3955
                    foreach (double[] point in points)
3956
                    {
3957
                        double distance = SPPIDUtil.CalcPointToPointdDistance(point[0], point[1], connX, connY);
3958
                        if (length >= distance)
3959
                        {
3960
                            targetConnector = item.Key;
3961
                            length = distance;
3962
                        }
3963
                    }
3964
                }
3965
            }
3966

    
3967
            return targetConnector;
3968
        }
3969

    
3970
        private LMConnector FindTargetLMConnectorForBranch(Line line, Line targetLine, ref double x, ref double y)
3971
        {
3972
            Dictionary<LMConnector, List<double[]>> vertices = GetPipeRunVertices(targetLine.SPPID.ModelItemId);
3973
            if (vertices.Count == 0)
3974
                return null;
3975

    
3976
            double length = double.MaxValue;
3977
            LMConnector targetConnector = null;
3978
            double[] resultPoint = null;
3979
            List<double[]> targetVertices = null;
3980

    
3981
            // Vertices 포인트에 제일 가까운곳
3982
            foreach (var item in vertices)
3983
            {
3984
                List<double[]> points = item.Value;
3985
                for (int i = 0; i < points.Count; i++)
3986
                {
3987
                    double[] point = points[i];
3988
                    double tempX = point[0];
3989
                    double tempY = point[1];
3990

    
3991
                    double distance = SPPIDUtil.CalcPointToPointdDistance(tempX, tempY, x, y);
3992
                    if (length >= distance)
3993
                    {
3994
                        targetConnector = item.Key;
3995
                        length = distance;
3996
                        resultPoint = point;
3997
                        targetVertices = item.Value;
3998
                    }
3999
                }
4000
            }
4001

    
4002
            // Vertices Cross에 제일 가까운곳
4003
            foreach (var item in vertices)
4004
            {
4005
                List<double[]> points = item.Value;
4006
                for (int i = 0; i < points.Count - 1; i++)
4007
                {
4008
                    double[] point1 = points[i];
4009
                    double[] point2 = points[i + 1];
4010

    
4011
                    double maxLineX = Math.Max(point1[0], point2[0]);
4012
                    double minLineX = Math.Min(point1[0], point2[0]);
4013
                    double maxLineY = Math.Max(point1[1], point2[1]);
4014
                    double minLineY = Math.Min(point1[1], point2[1]);
4015

    
4016
                    SlopeType slope = SPPIDUtil.CalcSlope(minLineX, minLineY, maxLineX, maxLineY);
4017

    
4018
                    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]);
4019
                    if (crossingPoint != null)
4020
                    {
4021
                        double distance = SPPIDUtil.CalcPointToPointdDistance(crossingPoint[0], crossingPoint[1], x, y);
4022
                        if (length >= distance)
4023
                        {
4024
                            if (slope == SlopeType.Slope &&
4025
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0] &&
4026
                                minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4027
                            {
4028
                                targetConnector = item.Key;
4029
                                length = distance;
4030
                                resultPoint = crossingPoint;
4031
                                targetVertices = item.Value;
4032
                            }
4033
                            else if (slope == SlopeType.HORIZONTAL &&
4034
                                minLineX <= crossingPoint[0] && maxLineX >= crossingPoint[0])
4035
                            {
4036
                                targetConnector = item.Key;
4037
                                length = distance;
4038
                                resultPoint = crossingPoint;
4039
                                targetVertices = item.Value;
4040
                            }
4041
                            else if (slope == SlopeType.VERTICAL &&
4042
                               minLineY <= crossingPoint[1] && maxLineY >= crossingPoint[1])
4043
                            {
4044
                                targetConnector = item.Key;
4045
                                length = distance;
4046
                                resultPoint = crossingPoint;
4047
                                targetVertices = item.Value;
4048
                            }
4049
                        }
4050
                    }
4051
                }
4052
            }
4053

    
4054
            foreach (var item in vertices)
4055
                if (item.Key != null && item.Key != targetConnector)
4056
                    ReleaseCOMObjects(item.Key);
4057

    
4058
            if (SPPIDUtil.IsBranchLine(line, targetLine))
4059
            {
4060
                double tempResultX = resultPoint[0];
4061
                double tempResultY = resultPoint[1];
4062
                SPPIDUtil.ConvertGridPoint(ref tempResultX, ref tempResultY);
4063

    
4064
                GridSetting gridSetting = GridSetting.GetInstance();
4065

    
4066
                for (int i = 0; i < targetVertices.Count; i++)
4067
                {
4068
                    double[] point = targetVertices[i];
4069
                    double tempX = targetVertices[i][0];
4070
                    double tempY = targetVertices[i][1];
4071
                    SPPIDUtil.ConvertGridPoint(ref tempX, ref tempY);
4072
                    if (tempX == tempResultX && tempY == tempResultY)
4073
                    {
4074
                        if (i == 0)
4075
                        {
4076
                            LMSymbol connSymbol = targetConnector.ConnectItem1SymbolObject;
4077
                            bool containZeroLength = false;
4078
                            if (connSymbol != null)
4079
                            {
4080
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4081
                                {
4082
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4083
                                        containZeroLength = true;
4084
                                }
4085
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4086
                                {
4087
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4088
                                        containZeroLength = true;
4089
                                }
4090
                            }
4091

    
4092
                            if (connSymbol == null ||
4093
                                (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4094
                                containZeroLength)
4095
                            {
4096
                                bool bCalcX = false;
4097
                                bool bCalcY = false;
4098
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4099
                                    bCalcX = true;
4100
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4101
                                    bCalcY = true;
4102
                                else
4103
                                {
4104
                                    bCalcX = true;
4105
                                    bCalcY = true;
4106
                                }
4107

    
4108
                                if (bCalcX)
4109
                                {
4110
                                    double nextX = targetVertices[i + 1][0];
4111
                                    double newX = 0;
4112
                                    if (nextX > tempX)
4113
                                    {
4114
                                        newX = tempX + gridSetting.Length;
4115
                                        if (newX > nextX)
4116
                                            newX = (point[0] + nextX) / 2;
4117
                                    }
4118
                                    else
4119
                                    {
4120
                                        newX = tempX - gridSetting.Length;
4121
                                        if (newX < nextX)
4122
                                            newX = (point[0] + nextX) / 2;
4123
                                    }
4124
                                    resultPoint = new double[] { newX, resultPoint[1] };
4125
                                }
4126

    
4127
                                if (bCalcY)
4128
                                {
4129
                                    double nextY = targetVertices[i + 1][1];
4130
                                    double newY = 0;
4131
                                    if (nextY > tempY)
4132
                                    {
4133
                                        newY = tempY + gridSetting.Length;
4134
                                        if (newY > nextY)
4135
                                            newY = (point[1] + nextY) / 2;
4136
                                    }
4137
                                    else
4138
                                    {
4139
                                        newY = tempY - gridSetting.Length;
4140
                                        if (newY < nextY)
4141
                                            newY = (point[1] + nextY) / 2;
4142
                                    }
4143
                                    resultPoint = new double[] { resultPoint[0], newY };
4144
                                }
4145
                            }
4146
                        }
4147
                        else if (i == targetVertices.Count - 1)
4148
                        {
4149
                            LMSymbol connSymbol = targetConnector.ConnectItem2SymbolObject;
4150
                            bool containZeroLength = false;
4151
                            if (connSymbol != null)
4152
                            {
4153
                                foreach (LMConnector connector in connSymbol.Connect1Connectors)
4154
                                {
4155
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4156
                                        containZeroLength = true;
4157
                                }
4158
                                foreach (LMConnector connector in connSymbol.Connect2Connectors)
4159
                                {
4160
                                    if (connector.get_ItemStatus() == "Active" && Convert.ToBoolean(connector.get_IsZeroLength()) == true)
4161
                                        containZeroLength = true;
4162
                                }
4163
                            }
4164

    
4165
                            if (connSymbol == null ||
4166
                                 (connSymbol != null && connSymbol.get_ItemStatus() == "Active" && connSymbol.get_RepresentationType() != "Branch") ||
4167
                                containZeroLength)
4168
                            {
4169
                                bool bCalcX = false;
4170
                                bool bCalcY = false;
4171
                                if (targetLine.SlopeType == SlopeType.HORIZONTAL)
4172
                                    bCalcX = true;
4173
                                else if (targetLine.SlopeType == SlopeType.VERTICAL)
4174
                                    bCalcY = true;
4175
                                else
4176
                                {
4177
                                    bCalcX = true;
4178
                                    bCalcY = true;
4179
                                }
4180

    
4181
                                if (bCalcX)
4182
                                {
4183
                                    double nextX = targetVertices[i - 1][0];
4184
                                    double newX = 0;
4185
                                    if (nextX > tempX)
4186
                                    {
4187
                                        newX = tempX + gridSetting.Length;
4188
                                        if (newX > nextX)
4189
                                            newX = (point[0] + nextX) / 2;
4190
                                    }
4191
                                    else
4192
                                    {
4193
                                        newX = tempX - gridSetting.Length;
4194
                                        if (newX < nextX)
4195
                                            newX = (point[0] + nextX) / 2;
4196
                                    }
4197
                                    resultPoint = new double[] { newX, resultPoint[1] };
4198
                                }
4199

    
4200
                                if (bCalcY)
4201
                                {
4202
                                    double nextY = targetVertices[i - 1][1];
4203
                                    double newY = 0;
4204
                                    if (nextY > tempY)
4205
                                    {
4206
                                        newY = tempY + gridSetting.Length;
4207
                                        if (newY > nextY)
4208
                                            newY = (point[1] + nextY) / 2;
4209
                                    }
4210
                                    else
4211
                                    {
4212
                                        newY = tempY - gridSetting.Length;
4213
                                        if (newY < nextY)
4214
                                            newY = (point[1] + nextY) / 2;
4215
                                    }
4216
                                    resultPoint = new double[] { resultPoint[0], newY };
4217
                                }
4218
                            }
4219
                        }
4220
                        break;
4221
                    }
4222
                }
4223
            }
4224

    
4225
            x = resultPoint[0];
4226
            y = resultPoint[1];
4227

    
4228
            return targetConnector;
4229
        }
4230

    
4231
        private LMConnector GetLMConnectorOnlyOne(string modelItemID)
4232
        {
4233
            LMConnector result = null;
4234
            List<LMConnector> connectors = new List<LMConnector>();
4235
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4236

    
4237
            if (modelItem != null)
4238
            {
4239
                foreach (LMRepresentation rep in modelItem.Representations)
4240
                {
4241
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4242
                        connectors.Add(dataSource.GetConnector(rep.Id));
4243
                }
4244

    
4245
                ReleaseCOMObjects(modelItem);
4246
            }
4247

    
4248
            if (connectors.Count == 1)
4249
                result = connectors[0];
4250
            else
4251
                foreach (var item in connectors)
4252
                    ReleaseCOMObjects(item);
4253

    
4254
            return result;
4255
        }
4256

    
4257
        private LMConnector GetLMConnectorFirst(string modelItemID)
4258
        {
4259
            LMConnector result = null;
4260
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4261

    
4262
            if (modelItem != null)
4263
            {
4264
                foreach (LMRepresentation rep in modelItem.Representations)
4265
                {
4266
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && 
4267
                        rep.Attributes["ItemStatus"].get_Value() == "Active")
4268
                    {
4269
                        LMConnector connector = dataSource.GetConnector(rep.Id);
4270
                        if (!Convert.ToBoolean(connector.get_IsZeroLength()))
4271
                        {
4272
                            result = connector;
4273
                            break;
4274
                        }
4275
                        else
4276
                        {
4277
                            ReleaseCOMObjects(connector);
4278
                            connector = null;
4279
                        }
4280
                    }
4281
                }
4282
                ReleaseCOMObjects(modelItem);
4283
                modelItem = null;
4284
            }
4285

    
4286
            return result;
4287
        }
4288

    
4289
        private int GetConnectorCount(string modelItemID)
4290
        {
4291
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4292
            int result = 0;
4293
            if (modelItem != null)
4294
            {
4295
                foreach (LMRepresentation rep in modelItem.Representations)
4296
                {
4297
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4298
                        result++;
4299
                    ReleaseCOMObjects(rep);
4300
                }
4301
                ReleaseCOMObjects(modelItem);
4302
            }
4303

    
4304
            return result;
4305
        }
4306

    
4307
        public List<string> GetRepresentations(string modelItemID)
4308
        {
4309
            List<string> result = new List<string>(); ;
4310
            LMModelItem modelItem = dataSource.GetModelItem(modelItemID);
4311
            if (modelItem != null)
4312
            {
4313
                foreach (LMRepresentation rep in modelItem.Representations)
4314
                {
4315
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
4316
                        result.Add(rep.Id);
4317
                }
4318
                ReleaseCOMObjects(modelItem);
4319
            }
4320

    
4321
            return result;
4322
        }
4323

    
4324
        private void LineNumberModeling(LineNumber lineNumber)
4325
        {
4326
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4327
            if (line != null)
4328
            {
4329
                double x = 0;
4330
                double y = 0;
4331
                CalcLabelLocation(ref x, ref y, lineNumber.SPPID.ORIGINAL_X, lineNumber.SPPID.ORIGINAL_Y, lineNumber.SPPIDLabelLocation, _ETCSetting.LineNumberLocation);
4332

    
4333
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
4334
                LMConnector connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, x, y);
4335
                if (connectedLMConnector != null)
4336
                {
4337
                    Array points = new double[] { 0, x, y };
4338
                    lineNumber.SPPID.SPPID_X = x;
4339
                    lineNumber.SPPID.SPPID_Y = y;
4340
                    LMLabelPersist _LmLabelPresist = _placement.PIDPlaceLabel(lineNumber.SPPID.MAPPINGNAME, ref points, Rotation: lineNumber.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: false);
4341

    
4342
                    if (_LmLabelPresist != null)
4343
                    {
4344
                        _LmLabelPresist.Commit();
4345
                        lineNumber.SPPID.RepresentationId = _LmLabelPresist.AsLMRepresentation().Id;
4346
                        ReleaseCOMObjects(_LmLabelPresist);
4347
                    }
4348
                }
4349

    
4350
                foreach (var item in connectorVertices)
4351
                    ReleaseCOMObjects(item.Key);
4352
            }
4353
        }
4354
        private void LineNumberCorrectModeling(LineNumber lineNumber)
4355
        {
4356
            Line line = SPPIDUtil.FindObjectByUID(document, lineNumber.CONNLINE) as Line;
4357
            if (line == null || line.SPPID.Vertices == null)
4358
                return;
4359

    
4360
            if (!string.IsNullOrEmpty(lineNumber.SPPID.RepresentationId))
4361
            {
4362
                LMLabelPersist removeLabel = dataSource.GetLabelPersist(lineNumber.SPPID.RepresentationId);
4363
                if (removeLabel != null)
4364
                {
4365
                    lineNumber.SPPID.SPPID_X = removeLabel.get_XCoordinate();
4366
                    lineNumber.SPPID.SPPID_Y = removeLabel.get_YCoordinate();
4367

    
4368
                    GridSetting gridSetting = GridSetting.GetInstance();
4369
                    LMConnector connector = dataSource.GetConnector(removeLabel.RepresentationID);
4370

    
4371
                    double[] labelRange = null;
4372
                    GetSPPIDSymbolRange(removeLabel, ref labelRange);
4373
                    List<double[]> vertices = GetConnectorVertices(connector);
4374

    
4375
                    double[] resultStart = null;
4376
                    double[] resultEnd = null;
4377
                    double distance = double.MaxValue;
4378
                    for (int i = 0; i < vertices.Count - 1; i++)
4379
                    {
4380
                        double[] startPoint = vertices[i];
4381
                        double[] endPoint = vertices[i + 1];
4382
                        foreach (var item in line.SPPID.Vertices)
4383
                        {
4384
                            double[] lineStartPoint = item[0];
4385
                            double[] lineEndPoint = item[item.Count - 1];
4386

    
4387
                            double tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineStartPoint[0], lineStartPoint[1]) +
4388
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineEndPoint[0], lineEndPoint[1]);
4389
                            if (tempDistance < distance)
4390
                            {
4391
                                distance = tempDistance;
4392
                                resultStart = startPoint;
4393
                                resultEnd = endPoint;
4394
                            }
4395
                            tempDistance = SPPIDUtil.CalcPointToPointdDistance(startPoint[0], startPoint[1], lineEndPoint[0], lineEndPoint[1]) +
4396
                                SPPIDUtil.CalcPointToPointdDistance(endPoint[0], endPoint[1], lineStartPoint[0], lineStartPoint[1]);
4397
                            if (tempDistance < distance)
4398
                            {
4399
                                distance = tempDistance;
4400
                                resultStart = startPoint;
4401
                                resultEnd = endPoint;
4402
                            }
4403
                        }
4404
                    }
4405

    
4406
                    if (resultStart != null && resultEnd != null)
4407
                    {
4408
                        SlopeType slope = SPPIDUtil.CalcSlope(resultStart[0], resultStart[1], resultEnd[0], resultEnd[1]);
4409
                        double lineStartX = 0;
4410
                        double lineStartY = 0;
4411
                        double lineEndX = 0;
4412
                        double lineEndY = 0;
4413
                        double lineNumberX = 0;
4414
                        double lineNumberY = 0;
4415
                        SPPIDUtil.ConvertPointBystring(line.STARTPOINT, ref lineStartX, ref lineStartY);
4416
                        SPPIDUtil.ConvertPointBystring(line.ENDPOINT, ref lineEndX, ref lineEndY);
4417

    
4418
                        double lineX = (lineStartX + lineEndX) / 2;
4419
                        double lineY = (lineStartY + lineEndY) / 2;
4420
                        lineNumberX = (lineNumber.X1 + lineNumber.X2) / 2;
4421
                        lineNumberY = (lineNumber.Y1 + lineNumber.Y2) / 2;
4422

    
4423
                        double SPPIDCenterX = (resultStart[0] + resultEnd[0]) / 2;
4424
                        double SPPIDCenterY = (resultStart[1] + resultEnd[1]) / 2;
4425
                        double labelCenterX = (labelRange[0] + labelRange[2]) / 2;
4426
                        double labelCenterY = (labelRange[1] + labelRange[3]) / 2;
4427

    
4428
                        double offsetX = 0;
4429
                        double offsetY = 0;
4430
                        if (slope == SlopeType.HORIZONTAL)
4431
                        {
4432
                            // Line Number 아래
4433
                            if (lineY < lineNumberY)
4434
                            {
4435
                                offsetX = labelCenterX - SPPIDCenterX;
4436
                                offsetY = labelRange[3] - SPPIDCenterY + gridSetting.Length;
4437
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4438
                            }
4439
                            // Line Number 위
4440
                            else
4441
                            {
4442
                                offsetX = labelCenterX - SPPIDCenterX;
4443
                                offsetY = labelRange[1] - SPPIDCenterY - gridSetting.Length;
4444
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4445
                            }
4446
                        }
4447
                        else if (slope == SlopeType.VERTICAL)
4448
                        {
4449
                            // Line Number 오르쪽
4450
                            if (lineX < lineNumberX)
4451
                            {
4452
                                offsetX = labelRange[0] - SPPIDCenterX - gridSetting.Length;
4453
                                offsetY = labelCenterY - SPPIDCenterY;
4454
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4455
                            }
4456
                            // Line Number 왼쪽
4457
                            else
4458
                            {
4459
                                offsetX = labelRange[2] - SPPIDCenterX + gridSetting.Length;
4460
                                offsetY = labelCenterY - SPPIDCenterY;
4461
                                MoveLineNumber(lineNumber, offsetX, offsetY);
4462
                            }
4463
                        }
4464

    
4465
                        if (offsetY != 0 || offsetY != 0)
4466
                        {
4467
                            if (connector.ConnectItem1SymbolObject != null &&
4468
                                connector.ConnectItem1SymbolObject.get_RepresentationType() == "OPC")
4469
                            {
4470
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem1SymbolObject.get_GraphicOID().ToString()];
4471

    
4472
                                double x1, y1, x2, y2, originX, originY;
4473
                                symbol.Range(out x1, out y1, out x2, out y2);
4474
                                symbol.GetOrigin(out originX, out originY);
4475
                                if (originX < lineNumber.SPPID.SPPID_X)
4476
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
4477
                                else
4478
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
4479
                            }
4480
                            else if (connector.ConnectItem2SymbolObject != null &&
4481
                                    connector.ConnectItem2SymbolObject.get_RepresentationType() == "OPC")
4482
                            {
4483
                                Ingr.RAD2D.Symbol2d symbol = radApp.ActiveDocument.ActiveSheet.DrawingObjects[connector.ConnectItem2SymbolObject.get_GraphicOID().ToString()];
4484

    
4485
                                double x1, y1, x2, y2, originX, originY;
4486
                                symbol.Range(out x1, out y1, out x2, out y2);
4487
                                symbol.GetOrigin(out originX, out originY);
4488
                                if (originX < lineNumber.SPPID.SPPID_X)
4489
                                    offsetX = -1 * (originX + gridSetting.Length * 30 - labelCenterX);
4490
                                else
4491
                                    offsetX = -1 * (originX - gridSetting.Length * 30 - labelCenterX);
4492
                            }
4493

    
4494
                            radApp.ActiveSelectSet.RemoveAll();
4495
                            DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[removeLabel.get_GraphicOID().ToString()] as DependencyObject;
4496
                            if (dependency != null)
4497
                            {
4498
                                radApp.ActiveSelectSet.Add(dependency);
4499
                                Ingr.RAD2D.Transform transform = dependency.GetTransform();
4500
                                transform.DefineByMove2d(-offsetX, -offsetY);
4501
                                radApp.ActiveSelectSet.Transform(transform, true);
4502
                                radApp.ActiveSelectSet.RemoveAll();
4503
                            }
4504
                        }
4505

    
4506
                        void MoveLineNumber(LineNumber moveLineNumber, double x, double y)
4507
                        {
4508
                            moveLineNumber.SPPID.SPPID_X = moveLineNumber.SPPID.SPPID_X - x;
4509
                            moveLineNumber.SPPID.SPPID_Y = moveLineNumber.SPPID.SPPID_Y - y;
4510
                        }
4511
                    }
4512

    
4513

    
4514
                    ReleaseCOMObjects(connector);
4515
                    connector = null;
4516
                }
4517

    
4518
                ReleaseCOMObjects(removeLabel);
4519
                removeLabel = null;
4520
            }
4521
        }
4522
        /// <summary>
4523
        /// Flow Mark Modeling
4524
        /// </summary>
4525
        /// <param name="line"></param>
4526
        private void FlowMarkModeling(Line line)
4527
        {
4528
            if (line.FLOWMARK && !string.IsNullOrEmpty(line.SPPID.ModelItemId) && !string.IsNullOrEmpty(_ETCSetting.FlowMarkSymbolPath))
4529
            {
4530
                LMConnector connector = GetLMConnectorOnlyOne(line.SPPID.ModelItemId);
4531
                if (connector != null)
4532
                {
4533
                    string mappingPath = _ETCSetting.FlowMarkSymbolPath;
4534
                    List<double[]> vertices = GetConnectorVertices(connector);
4535
                    vertices = vertices.FindAll(x => x[0] > 0 && x[1] > 0);
4536
                    double[] point = vertices[vertices.Count - 1];
4537
                    Array array = new double[] { 0, point[0], point[1] };
4538
                    LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mappingPath, ref array, LabeledItem: connector.AsLMRepresentation());
4539
                    if (_LMLabelPersist != null)
4540
                    {
4541
                        _LMLabelPersist.Commit();
4542
                        FlowMarkRepIds.Add(_LMLabelPersist.Id);
4543
                        ReleaseCOMObjects(_LMLabelPersist);
4544
                    }
4545
                }
4546
            }
4547
        }
4548

    
4549
        /// <summary>
4550
        /// Line Number 기준으로 모든 Item에 Line Number의 Attribute Input
4551
        /// </summary>
4552
        /// <param name="lineNumber"></param>
4553
        private void InputLineNumberAttribute(LineNumber lineNumber, List<string> endLine)
4554
        {
4555
            lineNumber.ATTRIBUTES.Sort(SortAttribute);
4556
            int SortAttribute(BaseModel.Attribute a, BaseModel.Attribute b)
4557
            {
4558
                if (a.ATTRIBUTE == "Tag Seq No")
4559
                    return 1;
4560
                else if (b.ATTRIBUTE == "Tag Seq No")
4561
                    return -1;
4562

    
4563
                return 0;
4564
            }
4565

    
4566
            foreach (LineRun run in lineNumber.RUNS)
4567
            {
4568
                foreach (var item in run.RUNITEMS)
4569
                {
4570
                    if (item.GetType() == typeof(Symbol))
4571
                    {
4572
                        Symbol symbol = item as Symbol;
4573
                        LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
4574
                        if (_LMSymbol != null)
4575
                        {
4576
                            LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4577

    
4578
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4579
                            {
4580
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4581
                                {
4582
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4583
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4584
                                    {
4585
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4586
                                        if (_LMAAttribute != null)
4587
                                        {
4588
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4589
                                                _LMAAttribute.set_Value(attribute.VALUE);
4590
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4591
                                                _LMAAttribute.set_Value(attribute.VALUE);
4592
                                        }
4593
                                    }
4594
                                }
4595
                                _LMModelItem.Commit();
4596
                            }
4597
                            if (_LMModelItem != null)
4598
                                ReleaseCOMObjects(_LMModelItem);
4599
                        }
4600
                        if (_LMSymbol != null)
4601
                            ReleaseCOMObjects(_LMSymbol);
4602
                    }
4603
                    else if (item.GetType() == typeof(Line))
4604
                    {
4605
                        Line line = item as Line;
4606
                        if (line != null && !endLine.Contains(line.SPPID.ModelItemId))
4607
                        {
4608
                            LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4609
                            if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4610
                            {
4611
                                foreach (var attribute in lineNumber.ATTRIBUTES)
4612
                                {
4613
                                    LineNumberMapping mapping = document.LineNumberMappings.Find(x => x.UID == attribute.UID);
4614
                                    if (mapping != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4615
                                    {
4616
                                        LMAAttribute _LMAAttribute = _LMModelItem.Attributes[mapping.SPPIDATTRIBUTENAME];
4617
                                        if (mapping.SPPIDATTRIBUTENAME == "OperFluidCode" && !string.IsNullOrEmpty(attribute.VALUE))
4618
                                        {
4619
                                            LMAAttribute _FluidSystemAttribute = _LMModelItem.Attributes["FluidSystem"];
4620
                                            if (_FluidSystemAttribute != null)
4621
                                            {
4622
                                                DataTable dt = SPPID_DB.GetFluidSystemInfo(attribute.VALUE);
4623
                                                if (dt.Rows.Count == 1)
4624
                                                {
4625
                                                    string fluidSystem = dt.Rows[0]["CODELIST_TEXT"].ToString();
4626
                                                    if (DBNull.Value.Equals(_FluidSystemAttribute.get_Value()))
4627
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
4628
                                                    else if (_FluidSystemAttribute.get_Value() != fluidSystem)
4629
                                                        _FluidSystemAttribute.set_Value(fluidSystem);
4630

    
4631
                                                    if (_LMAAttribute != null)
4632
                                                    {
4633
                                                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4634
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4635
                                                        else if (_LMAAttribute.get_Value() != attribute.VALUE)
4636
                                                            _LMAAttribute.set_Value(attribute.VALUE);
4637
                                                    }
4638
                                                }
4639
                                                if (dt != null)
4640
                                                    dt.Dispose();
4641
                                            }
4642
                                        }
4643
                                        else if (_LMAAttribute != null)
4644
                                        {
4645
                                            if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4646
                                                _LMAAttribute.set_Value(attribute.VALUE);
4647
                                            else if (_LMAAttribute.get_Value() != attribute.VALUE)
4648
                                                _LMAAttribute.set_Value(attribute.VALUE);
4649
                                        }
4650
                                    }
4651
                                }
4652
                                _LMModelItem.Commit();
4653
                            }
4654
                            if (_LMModelItem != null)
4655
                                ReleaseCOMObjects(_LMModelItem);
4656
                            endLine.Add(line.SPPID.ModelItemId);
4657
                        }
4658
                    }
4659
                }
4660
            }
4661
        }
4662

    
4663
        /// <summary>
4664
        /// Symbol Attribute 입력 메서드
4665
        /// </summary>
4666
        /// <param name="item"></param>
4667
        private void InputSymbolAttribute(object targetItem, List<BaseModel.Attribute> targetAttributes)
4668
        {
4669
            // Object 아이템이 Symbol일 경우 Equipment일 경우 
4670
            string sRep = null;
4671
            if (targetItem.GetType() == typeof(Symbol))
4672
                sRep = ((Symbol)targetItem).SPPID.RepresentationId;
4673
            else if (targetItem.GetType() == typeof(Equipment))
4674
                sRep = ((Equipment)targetItem).SPPID.RepresentationId;
4675

    
4676
            if (!string.IsNullOrEmpty(sRep))
4677
            {
4678
                LMSymbol _LMSymbol = dataSource.GetSymbol(sRep);
4679
                LMModelItem _LMModelItem = _LMSymbol.ModelItemObject;
4680
                LMAAttributes _Attributes = _LMModelItem.Attributes;
4681
                
4682
                foreach (var item in targetAttributes)
4683
                {
4684
                    AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == item.UID);
4685
                    if (mapping != null && !string.IsNullOrEmpty(item.VALUE) && item.VALUE != "None")
4686
                    {
4687
                        if (!mapping.IsText)
4688
                        {
4689
                            LMAAttribute _Attribute = _Attributes[mapping.SPPIDATTRIBUTENAME];
4690
                            if (_Attribute != null)
4691
                            {
4692
                                _Attribute.set_Value(item.VALUE);
4693
                                // OPC 일경우 Attribute 저장
4694
                                if (targetItem.GetType() == typeof(Symbol))
4695
                                {
4696
                                    Symbol symbol = targetItem as Symbol;
4697
                                    if (symbol.TYPE == "Piping OPC's" || symbol.TYPE == "Instrument OPC's")
4698
                                        symbol.SPPID.Attributes.Add(new string[] { mapping.SPPIDATTRIBUTENAME, item.VALUE });
4699
                                }
4700
                            }
4701
                        }
4702
                        else
4703
                            DefaultTextModeling(item.VALUE, _LMSymbol.get_XCoordinate(), _LMSymbol.get_YCoordinate());
4704
                    }
4705
                }
4706
                _LMModelItem.Commit();
4707

    
4708
                ReleaseCOMObjects(_Attributes);
4709
                ReleaseCOMObjects(_LMModelItem);
4710
                ReleaseCOMObjects(_LMSymbol);
4711
            }
4712
        }
4713

    
4714
        /// <summary>
4715
        /// Input SpecBreak Attribute
4716
        /// </summary>
4717
        /// <param name="specBreak"></param>
4718
        private void InputSpecBreakAttribute(SpecBreak specBreak)
4719
        {
4720
            object upStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.UpStreamUID);
4721
            object downStreamObj = SPPIDUtil.FindObjectByUID(document, specBreak.DownStreamUID);
4722

    
4723
            if (upStreamObj != null &&
4724
                downStreamObj != null)
4725
            {
4726
                LMConnector targetLMConnector = FindBreakLineTarget(upStreamObj, downStreamObj);
4727

    
4728
                if (targetLMConnector != null)
4729
                {
4730
                    foreach (LMLabelPersist _LMLabelPersist in targetLMConnector.LabelPersists)
4731
                    {
4732
                        string symbolPath = _LMLabelPersist.get_FileName();
4733
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.SPPIDSYMBOLNAME == symbolPath);
4734
                        if (mapping != null)
4735
                        {
4736
                            BaseModel.Attribute attribute = specBreak.ATTRIBUTES.Find(y => y.UID == mapping.UID);
4737
                            if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
4738
                            {
4739
                                string[] values = attribute.VALUE.Split(new char[] { ',' });
4740
                                if (values.Length == 2)
4741
                                {
4742
                                    string upStreamValue = values[0];
4743
                                    string downStreamValue = values[1];
4744

    
4745
                                    InputAttributeForSpecBreak(upStreamObj, downStreamObj, upStreamValue, downStreamValue, mapping.SPPIDATTRIBUTENAME);
4746
                                }
4747
                            }
4748
                        }
4749
                    }
4750

    
4751
                    ReleaseCOMObjects(targetLMConnector);
4752
                }
4753
            }
4754

    
4755

    
4756
            #region 내부에서만 쓰는 메서드
4757
            void InputAttributeForSpecBreak(object _upStreamObj, object _downStreamObj, string upStreamValue, string downStreamValue, string sppidAttributeName)
4758
            {
4759
                Symbol upStreamSymbol = _upStreamObj as Symbol;
4760
                Line upStreamLine = _upStreamObj as Line;
4761
                Symbol downStreamSymbol = _downStreamObj as Symbol;
4762
                Line downStreamLine = _downStreamObj as Line;
4763
                // 둘다 Line일 경우
4764
                if (upStreamLine != null && downStreamLine != null)
4765
                {
4766
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4767
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4768
                }
4769
                // 둘다 Symbol일 경우
4770
                else if (upStreamSymbol != null && downStreamSymbol != null)
4771
                {
4772
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamSymbol);
4773
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4774
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4775

    
4776
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4777
                    {
4778
                        if (connector.get_ItemStatus() != "Active")
4779
                            continue;
4780

    
4781
                        if (connector.Id != zeroLenthConnector.Id)
4782
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4783
                    }
4784

    
4785
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4786
                    {
4787
                        if (connector.get_ItemStatus() != "Active")
4788
                            continue;
4789

    
4790
                        if (connector.Id != zeroLenthConnector.Id)
4791
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4792
                    }
4793

    
4794
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4795
                    {
4796
                        if (connector.get_ItemStatus() != "Active")
4797
                            continue;
4798

    
4799
                        if (connector.Id != zeroLenthConnector.Id)
4800
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4801
                    }
4802

    
4803
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4804
                    {
4805
                        if (connector.get_ItemStatus() != "Active")
4806
                            continue;
4807

    
4808
                        if (connector.Id != zeroLenthConnector.Id)
4809
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4810
                    }
4811

    
4812
                    ReleaseCOMObjects(zeroLenthConnector);
4813
                    ReleaseCOMObjects(upStreamLMSymbol);
4814
                    ReleaseCOMObjects(downStreamLMSymbol);
4815
                }
4816
                else if (upStreamSymbol != null && downStreamLine != null)
4817
                {
4818
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamSymbol, downStreamLine);
4819
                    InputLineAttributeForSpecBreakLine(downStreamLine, sppidAttributeName, downStreamValue);
4820
                    LMSymbol upStreamLMSymbol = dataSource.GetSymbol(upStreamSymbol.SPPID.RepresentationId);
4821

    
4822
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid1Connectors)
4823
                    {
4824
                        if (connector.get_ItemStatus() != "Active")
4825
                            continue;
4826

    
4827
                        if (connector.Id == zeroLenthConnector.Id)
4828
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4829
                    }
4830

    
4831
                    foreach (LMConnector connector in upStreamLMSymbol.Avoid2Connectors)
4832
                    {
4833
                        if (connector.get_ItemStatus() != "Active")
4834
                            continue;
4835

    
4836
                        if (connector.Id == zeroLenthConnector.Id)
4837
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, upStreamValue);
4838
                    }
4839

    
4840
                    ReleaseCOMObjects(zeroLenthConnector);
4841
                    ReleaseCOMObjects(upStreamLMSymbol);
4842
                }
4843
                else if (upStreamLine != null && downStreamSymbol != null)
4844
                {
4845
                    LMConnector zeroLenthConnector = FindBreakLineTarget(upStreamLine, downStreamSymbol);
4846
                    InputLineAttributeForSpecBreakLine(upStreamLine, sppidAttributeName, upStreamValue);
4847
                    LMSymbol downStreamLMSymbol = dataSource.GetSymbol(downStreamSymbol.SPPID.RepresentationId);
4848

    
4849
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid1Connectors)
4850
                    {
4851
                        if (connector.get_ItemStatus() != "Active")
4852
                            continue;
4853

    
4854
                        if (connector.Id == zeroLenthConnector.Id)
4855
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4856
                    }
4857

    
4858
                    foreach (LMConnector connector in downStreamLMSymbol.Avoid2Connectors)
4859
                    {
4860
                        if (connector.get_ItemStatus() != "Active")
4861
                            continue;
4862

    
4863
                        if (connector.Id == zeroLenthConnector.Id)
4864
                            InputLineAttributeForSpecBreakLMConnector(connector, sppidAttributeName, downStreamValue);
4865
                    }
4866

    
4867
                    ReleaseCOMObjects(zeroLenthConnector);
4868
                    ReleaseCOMObjects(downStreamLMSymbol);
4869
                }
4870
            }
4871

    
4872
            void InputLineAttributeForSpecBreakLine(Line line, string attrName, string value)
4873
            {
4874
                LMModelItem _LMModelItem = dataSource.GetModelItem(line.SPPID.ModelItemId);
4875
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4876
                {
4877
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4878
                    if (_LMAAttribute != null)
4879
                    {
4880
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4881
                            _LMAAttribute.set_Value(value);
4882
                        else if (_LMAAttribute.get_Value() != value)
4883
                            _LMAAttribute.set_Value(value);
4884
                    }
4885

    
4886
                    _LMModelItem.Commit();
4887
                }
4888
                if (_LMModelItem != null)
4889
                    ReleaseCOMObjects(_LMModelItem);
4890
            }
4891

    
4892
            void InputLineAttributeForSpecBreakLMConnector(LMConnector connector, string attrName, string value)
4893
            {
4894
                LMModelItem _LMModelItem = dataSource.GetModelItem(connector.ModelItemID);
4895
                if (_LMModelItem != null && _LMModelItem.get_ItemStatus() == "Active")
4896
                {
4897
                    LMAAttribute _LMAAttribute = _LMModelItem.Attributes[attrName];
4898
                    if (_LMAAttribute != null)
4899
                    {
4900
                        if (DBNull.Value.Equals(_LMAAttribute.get_Value()))
4901
                            _LMAAttribute.set_Value(value);
4902
                        else if (_LMAAttribute.get_Value() != value)
4903
                            _LMAAttribute.set_Value(value);
4904
                    }
4905

    
4906
                    _LMModelItem.Commit();
4907
                }
4908
                if (_LMModelItem != null)
4909
                    ReleaseCOMObjects(_LMModelItem);
4910
            }
4911
            #endregion
4912
        }
4913

    
4914
        private void InputEndBreakAttribute(EndBreak endBreak)
4915
        {
4916
            object ownerObj = SPPIDUtil.FindObjectByUID(document, endBreak.OWNER);
4917
            object connectedItem = SPPIDUtil.FindObjectByUID(document, endBreak.PROPERTIES.Find(x => x.ATTRIBUTE == "Connected Item").VALUE);
4918

    
4919
            if ((ownerObj.GetType() == typeof(Symbol) && connectedItem.GetType() == typeof(Line)) ||
4920
                (ownerObj.GetType() == typeof(Line) && connectedItem.GetType() == typeof(Symbol)))
4921
            {
4922
                LMLabelPersist labelPersist = dataSource.GetLabelPersist(endBreak.SPPID.RepresentationId);
4923
                if (labelPersist != null)
4924
                {
4925
                    LMRepresentation representation = labelPersist.RepresentationObject;
4926
                    if (representation != null)
4927
                    {
4928
                        LMConnector connector = dataSource.GetConnector(representation.Id);
4929
                        LMModelItem ZeroLengthModelItem = connector.ModelItemObject;
4930
                        string modelItemID = connector.ModelItemID;
4931
                        if (Convert.ToBoolean(connector.get_IsZeroLength()))
4932
                        {
4933
                            List<string> modelItemIDs = new List<string>();
4934
                            if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
4935
                            {
4936
                                LMSymbol symbol = connector.ConnectItem1SymbolObject;
4937
                                foreach (LMConnector item in symbol.Connect1Connectors)
4938
                                {
4939
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4940
                                        modelItemIDs.Add(item.ModelItemID);
4941
                                    ReleaseCOMObjects(item);
4942
                                }
4943
                                foreach (LMConnector item in symbol.Connect2Connectors)
4944
                                {
4945
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4946
                                        modelItemIDs.Add(item.ModelItemID);
4947
                                    ReleaseCOMObjects(item);
4948
                                }
4949
                                ReleaseCOMObjects(symbol);
4950
                                symbol = null;
4951
                            }
4952
                            else if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
4953
                            {
4954
                                LMSymbol symbol = connector.ConnectItem2SymbolObject;
4955
                                foreach (LMConnector item in symbol.Connect1Connectors)
4956
                                {
4957
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4958
                                        modelItemIDs.Add(item.ModelItemID);
4959
                                    ReleaseCOMObjects(item);
4960
                                }
4961
                                foreach (LMConnector item in symbol.Connect2Connectors)
4962
                                {
4963
                                    if (item.get_ItemStatus() == "Active" && item.ModelItemID != modelItemID)
4964
                                        modelItemIDs.Add(item.ModelItemID);
4965
                                    ReleaseCOMObjects(item);
4966
                                }
4967
                                ReleaseCOMObjects(symbol);
4968
                                symbol = null;
4969
                            }
4970

    
4971
                            modelItemIDs = modelItemIDs.Distinct().ToList();
4972
                            if (modelItemIDs.Count == 1)
4973
                            {
4974
                                LMModelItem modelItem = dataSource.GetModelItem(modelItemIDs[0]);
4975
                                LMConnector onlyOne = GetLMConnectorOnlyOne(modelItem.Id);
4976
                                if (onlyOne != null && Convert.ToBoolean(onlyOne.get_IsZeroLength()))
4977
                                {
4978
                                    bool result = false;
4979
                                    foreach (LMLabelPersist loop in onlyOne.LabelPersists)
4980
                                    {
4981
                                        if (document.EndBreaks.Find(x => x.SPPID.RepresentationId == loop.RepresentationID) != null)
4982
                                            result = true;
4983
                                        ReleaseCOMObjects(loop);
4984
                                    }
4985

    
4986
                                    if (result)
4987
                                    {
4988
                                        object value = modelItem.Attributes["TagSequenceNo"].get_Value();
4989
                                        ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
4990
                                        ZeroLengthModelItem.Commit();
4991
                                    }
4992
                                    else
4993
                                    {
4994
                                        List<string> loopModelItems = new List<string>();
4995
                                        if (onlyOne.ConnectItem1SymbolObject.get_RepresentationType() == "Branch")
4996
                                        {
4997
                                            LMSymbol _symbol = onlyOne.ConnectItem1SymbolObject;
4998
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
4999
                                            {
5000
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5001
                                                    loopModelItems.Add(loop.ModelItemID);
5002
                                                ReleaseCOMObjects(loop);
5003
                                            }
5004
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5005
                                            {
5006
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5007
                                                    loopModelItems.Add(loop.ModelItemID);
5008
                                                ReleaseCOMObjects(loop);
5009
                                            }
5010
                                            ReleaseCOMObjects(_symbol);
5011
                                            _symbol = null;
5012
                                        }
5013
                                        else if (onlyOne.ConnectItem2SymbolObject.get_RepresentationType() == "Branch")
5014
                                        {
5015
                                            LMSymbol _symbol = onlyOne.ConnectItem2SymbolObject;
5016
                                            foreach (LMConnector loop in _symbol.Connect1Connectors)
5017
                                            {
5018
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5019
                                                    loopModelItems.Add(loop.ModelItemID);
5020
                                                ReleaseCOMObjects(loop);
5021
                                            }
5022
                                            foreach (LMConnector loop in _symbol.Connect2Connectors)
5023
                                            {
5024
                                                if (loop.get_ItemStatus() == "Active" && loop.ModelItemID != onlyOne.ModelItemID)
5025
                                                    loopModelItems.Add(loop.ModelItemID);
5026
                                                ReleaseCOMObjects(loop);
5027
                                            }
5028
                                            ReleaseCOMObjects(_symbol);
5029
                                            _symbol = null;
5030
                                        }
5031

    
5032
                                        loopModelItems = loopModelItems.Distinct().ToList();
5033
                                        if (loopModelItems.Count == 1)
5034
                                        {
5035
                                            LMModelItem loopModelItem = dataSource.GetModelItem(loopModelItems[0]);
5036
                                            object value = loopModelItem.Attributes["TagSequenceNo"].get_Value();
5037
                                            modelItem.Attributes["TagSequenceNo"].set_Value(value);
5038
                                            modelItem.Commit();
5039
                                            ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5040
                                            ZeroLengthModelItem.Commit();
5041

    
5042
                                            ReleaseCOMObjects(loopModelItem);
5043
                                            loopModelItem = null;
5044
                                        }
5045
                                    }
5046
                                }
5047
                                else
5048
                                {
5049
                                    object value = modelItem.Attributes["TagSequenceNo"].get_Value();
5050
                                    ZeroLengthModelItem.Attributes["TagSequenceNo"].set_Value(value);
5051
                                    ZeroLengthModelItem.Commit();
5052
                                }
5053
                                ReleaseCOMObjects(modelItem);
5054
                                modelItem = null;
5055
                                ReleaseCOMObjects(onlyOne);
5056
                                onlyOne = null;
5057
                            }
5058
                        }
5059
                        ReleaseCOMObjects(connector);
5060
                        connector = null;
5061
                        ReleaseCOMObjects(ZeroLengthModelItem);
5062
                        ZeroLengthModelItem = null;
5063
                    }
5064
                    ReleaseCOMObjects(representation);
5065
                    representation = null;
5066
                }
5067
                ReleaseCOMObjects(labelPersist);
5068
                labelPersist = null;
5069
            }
5070
        }
5071

    
5072
        /// <summary>
5073
        /// Text Modeling - Association일 경우는 Text대신 해당 맵핑된 Symbol로 모델링
5074
        /// </summary>
5075
        /// <param name="text"></param>
5076
        private void NormalTextModeling(Text text)
5077
        {
5078
            LMSymbol _LMSymbol = null;
5079

    
5080
            LMItemNote _LMItemNote = null;
5081
            LMAAttribute _LMAAttribute = null;
5082

    
5083
            double x = 0;
5084
            double y = 0;
5085
            double angle = text.ANGLE;
5086
            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, _ETCSetting.TextLocation);
5087

    
5088
            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5089
            text.SPPID.SPPID_X = x;
5090
            text.SPPID.SPPID_Y = y;
5091

    
5092
            _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, x, y, Rotation: angle);
5093
            if (_LMSymbol != null)
5094
            {
5095
                _LMSymbol.Commit();
5096
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5097
                if (_LMItemNote != null)
5098
                {
5099
                    _LMItemNote.Commit();
5100
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5101
                    if (_LMAAttribute != null)
5102
                    {
5103
                        _LMAAttribute.set_Value(text.VALUE);
5104
                        text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5105
                        _LMItemNote.Commit();
5106

    
5107

    
5108
                        double[] range = null;
5109
                        foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5110
                        {
5111
                            double[] temp = null;
5112
                            GetSPPIDSymbolRange(labelPersist, ref temp);
5113
                            if (temp != null)
5114
                            {
5115
                                if (range == null)
5116
                                    range = temp;
5117
                                else
5118
                                {
5119
                                    range = new double[] {
5120
                                            Math.Min(range[0], temp[0]),
5121
                                            Math.Min(range[1], temp[1]),
5122
                                            Math.Max(range[2], temp[2]),
5123
                                            Math.Max(range[3], temp[3])
5124
                                        };
5125
                                }
5126
                            }
5127
                        }
5128
                        text.SPPID.Range = range;
5129

    
5130
                        if (_LMAAttribute != null)
5131
                            ReleaseCOMObjects(_LMAAttribute);
5132
                        if (_LMItemNote != null)
5133
                            ReleaseCOMObjects(_LMItemNote);
5134
                    }
5135

    
5136
                    TextCorrectModeling(text);
5137
                }
5138
            }
5139
            if (_LMSymbol != null)
5140
                ReleaseCOMObjects(_LMSymbol);
5141
        }
5142

    
5143
        private void DefaultTextModeling(string value, double x, double y)
5144
        {
5145
            LMSymbol _LMSymbol = null;
5146

    
5147
            LMItemNote _LMItemNote = null;
5148
            LMAAttribute _LMAAttribute = null;
5149

    
5150
            _LMSymbol = _placement.PIDPlaceSymbol(_ETCSetting.TextSymbolPath, x, y, Rotation: 0);
5151
            if (_LMSymbol != null)
5152
            {
5153
                _LMSymbol.Commit();
5154
                _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5155
                if (_LMItemNote != null)
5156
                {
5157
                    _LMItemNote.Commit();
5158
                    _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5159
                    if (_LMAAttribute != null)
5160
                    {
5161
                        _LMAAttribute.set_Value(value);
5162
                        _LMItemNote.Commit();
5163

    
5164
                        if (_LMAAttribute != null)
5165
                            ReleaseCOMObjects(_LMAAttribute);
5166
                        if (_LMItemNote != null)
5167
                            ReleaseCOMObjects(_LMItemNote);
5168
                    }
5169
                }
5170
            }
5171
            if (_LMSymbol != null)
5172
                ReleaseCOMObjects(_LMSymbol);
5173
        }
5174

    
5175
        private void AssociationTextModeling(Text text)
5176
        {
5177
            LMSymbol _LMSymbol = null;
5178
            LMConnector connectedLMConnector = null;
5179
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5180
            if (owner != null && owner.GetType() == typeof(Symbol))
5181
            {
5182
                Symbol symbol = owner as Symbol;
5183
                _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5184
                if (_LMSymbol != null)
5185
                {
5186
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5187
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5188
                    {
5189
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5190

    
5191
                        if (mapping != null)
5192
                        {
5193
                            double x = 0;
5194
                            double y = 0;
5195

    
5196
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5197
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5198
                            Array array = new double[] { 0, x, y };
5199
                            text.SPPID.SPPID_X = x;
5200
                            text.SPPID.SPPID_Y = y;
5201
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5202
                            if (_LMLabelPersist != null)
5203
                            {
5204
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5205
                                _LMLabelPersist.Commit();
5206
                                ReleaseCOMObjects(_LMLabelPersist);
5207
                            }
5208
                        }
5209
                    }
5210
                }
5211
            }
5212
            else if (owner != null && owner.GetType() == typeof(Line))
5213
            {
5214
                Line line = owner as Line;
5215
                Dictionary<LMConnector, List<double[]>> connectorVertices = GetPipeRunVertices(line.SPPID.ModelItemId);
5216
                connectedLMConnector = FindTargetLMConnectorForLabel(connectorVertices, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y);
5217

    
5218
                if (connectedLMConnector != null)
5219
                {
5220
                    BaseModel.Attribute attribute = line.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5221
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5222
                    {
5223
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5224

    
5225
                        if (mapping != null)
5226
                        {
5227
                            double x = 0;
5228
                            double y = 0;
5229
                            CalcLabelLocation(ref x, ref y, text.SPPID.ORIGINAL_X, text.SPPID.ORIGINAL_Y, text.SPPIDLabelLocation, mapping.Location);
5230
                            SPPIDUtil.ConvertGridPoint(ref x, ref y);
5231
                            Array array = new double[] { 0, x, y };
5232

    
5233
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: connectedLMConnector.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5234
                            if (_LMLabelPersist != null)
5235
                            {
5236
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5237
                                _LMLabelPersist.Commit();
5238
                               
5239
                                DependencyObject dependency = radApp.ActiveDocument.ActiveSheet.DrawingObjects[_LMLabelPersist.get_GraphicOID().ToString()] as DependencyObject;
5240
                                if (dependency != null)
5241
                                {
5242
                                    radApp.ActiveSelectSet.RemoveAll();
5243
                                    radApp.ActiveSelectSet.Add(dependency);
5244
                                    Ingr.RAD2D.Transform transform = dependency.GetTransform();
5245
                                    transform.DefineByMove2d(x - _LMLabelPersist.get_XCoordinate(), y - _LMLabelPersist.get_YCoordinate());
5246
                                    radApp.ActiveSelectSet.Transform(transform, true);
5247
                                    radApp.ActiveSelectSet.RemoveAll();
5248
                                }
5249

    
5250
                                ReleaseCOMObjects(_LMLabelPersist);
5251
                            }
5252
                        }
5253
                    }
5254
                }
5255
            }
5256
            if (_LMSymbol != null)
5257
                ReleaseCOMObjects(_LMSymbol);
5258
        }
5259

    
5260
        private void TextCorrectModeling(Text text)
5261
        {
5262
            if (text.SPPID.Range == null)
5263
                return;
5264

    
5265
            bool needRemodeling = false;
5266
            bool loop = true;
5267
            GridSetting gridSetting = GridSetting.GetInstance();
5268
            while (loop)
5269
            {
5270
                loop = false;
5271
                foreach (var overlapText in document.TEXTINFOS)
5272
                {
5273
                    if (overlapText.ASSOCIATION || overlapText == text || overlapText.SPPID.Range == null)
5274
                        continue;
5275

    
5276
                    if (SPPIDUtil.IsOverlap(overlapText.SPPID.Range, text.SPPID.Range))
5277
                    {
5278
                        double percentX = 0;
5279
                        double percentY = 0;
5280
                        if (overlapText.X1 <= text.X2 && overlapText.X2 >= text.X1)
5281
                        {
5282
                            double gapX = Math.Min(overlapText.X2, text.X2) - Math.Max(overlapText.X1, text.X1);
5283
                            percentX = Math.Max(gapX / (overlapText.X2 - overlapText.X1), gapX / (text.X2 - text.X1));
5284
                        }
5285
                        if (overlapText.Y1 <= text.Y2 && overlapText.Y2 >= text.Y1)
5286
                        {
5287
                            double gapY = Math.Min(overlapText.Y2, text.Y2) - Math.Max(overlapText.Y1, text.Y1);
5288
                            percentY = Math.Max(gapY / (overlapText.Y2 - overlapText.Y1), gapY / (text.Y2 - text.Y1));
5289
                        }
5290

    
5291
                        double tempX = 0;
5292
                        double tempY = 0;
5293
                        bool overlapX = false;
5294
                        bool overlapY = false;
5295
                        SPPIDUtil.CalcOverlap(text.SPPID.Range, overlapText.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5296
                        if (percentX >= percentY)
5297
                        {
5298
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5299
                            double move = gridSetting.Length * count;
5300
                            text.SPPID.SPPID_Y = text.SPPID.SPPID_Y - move;
5301
                            text.SPPID.Range = new double[] { text.SPPID.Range[0], text.SPPID.Range[1] - move, text.SPPID.Range[2], text.SPPID.Range[3] - move };
5302
                            needRemodeling = true;
5303
                            loop = true;
5304
                        }
5305
                        else
5306
                        {
5307
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5308
                            double move = gridSetting.Length * count;
5309
                            text.SPPID.SPPID_X = text.SPPID.SPPID_X + move;
5310
                            text.SPPID.Range = new double[] { text.SPPID.Range[0] + move, text.SPPID.Range[1], text.SPPID.Range[2] + move, text.SPPID.Range[3] };
5311
                            needRemodeling = true;
5312
                            loop = true;
5313
                        }
5314
                    }
5315
                }
5316
            }
5317
            
5318

    
5319
            if (needRemodeling)
5320
            {
5321
                LMSymbol symbol = dataSource.GetSymbol(text.SPPID.RepresentationId);
5322
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5323
                text.SPPID.RepresentationId = null;
5324

    
5325
                LMItemNote _LMItemNote = null;
5326
                LMAAttribute _LMAAttribute = null;
5327
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(text.SPPID.MAPPINGNAME, text.SPPID.SPPID_X, text.SPPID.SPPID_Y, Rotation: text.ANGLE);
5328
                if (_LMSymbol != null)
5329
                {
5330
                    _LMSymbol.Commit();
5331
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5332
                    if (_LMItemNote != null)
5333
                    {
5334
                        _LMItemNote.Commit();
5335
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5336
                        if (_LMAAttribute != null)
5337
                        {
5338
                            _LMAAttribute.set_Value(text.VALUE);
5339
                            text.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5340
                            _LMItemNote.Commit();
5341

    
5342
                            ReleaseCOMObjects(_LMAAttribute);
5343
                            ReleaseCOMObjects(_LMItemNote);
5344
                        }
5345
                    }
5346
                }
5347

    
5348
                ReleaseCOMObjects(symbol);
5349
                symbol = null;
5350
                ReleaseCOMObjects(_LMItemNote);
5351
                _LMItemNote = null;
5352
                ReleaseCOMObjects(_LMAAttribute);
5353
                _LMAAttribute = null;
5354
                ReleaseCOMObjects(_LMSymbol);
5355
                _LMSymbol = null;
5356
            }
5357
        }
5358

    
5359
        private void AssociationTextCorrectModeling(Text text, List<Text> endTexts)
5360
        {
5361
            if (!string.IsNullOrEmpty(text.SPPID.RepresentationId))
5362
            {
5363
                List<Text> allTexts = new List<Text>();
5364
                LMLabelPersist targetLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5365
                LMRepresentation representation = targetLabel.RepresentationObject;
5366
                Symbol symbol = document.SYMBOLS.Find(x => x.SPPID.RepresentationId == representation.Id);
5367
                if (targetLabel.RepresentationObject != null && symbol != null)
5368
                {
5369
                    double[] symbolRange = null;
5370
                    GetSPPIDSymbolRange(symbol, ref symbolRange, true, true);
5371
                    if (symbolRange != null)
5372
                    {
5373
                        foreach (LMLabelPersist labelPersist in representation.LabelPersists)
5374
                        {
5375
                            Text findText = document.TEXTINFOS.Find(x => x.SPPID.RepresentationId == labelPersist.AsLMRepresentation().Id && x.ASSOCIATION);
5376
                            if (findText != null)
5377
                            {
5378
                                double[] range = null;
5379
                                GetSPPIDSymbolRange(labelPersist, ref range);
5380
                                findText.SPPID.Range = range;
5381
                                allTexts.Add(findText);
5382
                            }
5383

    
5384
                            ReleaseCOMObjects(labelPersist);
5385
                        }
5386

    
5387
                        if (allTexts.Count > 0)
5388
                        {
5389
                            #region Sort Text By Y
5390
                            allTexts.Sort(SortTextByY);
5391
                            int SortTextByY(Text a, Text b)
5392
                            {
5393
                                return b.SPPID.Range[3].CompareTo(a.SPPID.Range[3]);
5394
                            }
5395
                            #endregion
5396

    
5397
                            #region 정렬하기전 방향
5398
                            List<Text> left = new List<Text>();
5399
                            List<Text> down = new List<Text>();
5400
                            List<Text> right = new List<Text>();
5401
                            List<Text> up = new List<Text>();
5402
                            List<List<Text>> sortTexts = new List<List<Text>>() { left, down, right, up };
5403
                            foreach (var loopText in allTexts)
5404
                            {
5405
                                double textCenterX = (loopText.X1 + loopText.X2) / 2;
5406
                                double textCenterY = (loopText.Y1 + loopText.Y2) / 2;
5407
                                double originX = 0;
5408
                                double originY = 0;
5409
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5410
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5411

    
5412
                                if (angle < 45)
5413
                                {
5414
                                    // Text 오른쪽
5415
                                    if (textCenterX > originX)
5416
                                        right.Add(loopText);
5417
                                    // Text 왼쪽
5418
                                    else
5419
                                        left.Add(loopText); 
5420
                                }
5421
                                else
5422
                                {
5423
                                    // Text 아래쪽
5424
                                    if (textCenterY > originY)
5425
                                        down.Add(loopText);
5426
                                    // Text 위쪽
5427
                                    else
5428
                                        up.Add(loopText);
5429
                                }
5430
                            }
5431
                            
5432
                            #endregion
5433

    
5434
                            foreach (var texts in sortTexts)
5435
                            {
5436
                                if (texts.Count == 0 )
5437
                                    continue;
5438
                                
5439
                                #region 첫번째 Text로 기준 맞춤
5440
                                for (int i = 0; i < texts.Count; i++)
5441
                                {
5442
                                    if (i != 0)
5443
                                    {
5444
                                        Text currentText = texts[i];
5445
                                        Text prevText = texts[i - 1];
5446
                                        double minY = prevText.SPPID.Range[1];
5447
                                        double centerPrevX = (prevText.SPPID.Range[0] + prevText.SPPID.Range[2]) / 2;
5448
                                        double centerX = (currentText.SPPID.Range[0] + currentText.SPPID.Range[2]) / 2;
5449
                                        double _gapX = centerX - centerPrevX;
5450
                                        double _gapY = currentText.SPPID.Range[3] - minY;
5451
                                        MoveText(currentText, _gapX, _gapY);
5452
                                    }
5453
                                }
5454
                                List<double> rangeMinX = texts.Select(loopX => loopX.SPPID.Range[0]).ToList();
5455
                                List<double> rangeMinY = texts.Select(loopX => loopX.SPPID.Range[1]).ToList();
5456
                                List<double> rangeMaxX = texts.Select(loopX => loopX.SPPID.Range[2]).ToList();
5457
                                List<double> rangeMaxY = texts.Select(loopX => loopX.SPPID.Range[3]).ToList();
5458
                                rangeMinX.Sort();
5459
                                rangeMinY.Sort();
5460
                                rangeMaxX.Sort();
5461
                                rangeMaxY.Sort();
5462
                                double allTextCenterX = (rangeMinX[0] + rangeMaxX[rangeMaxX.Count - 1]) / 2;
5463
                                double allTextCenterY = (rangeMinY[0] + rangeMaxY[rangeMaxY.Count - 1]) / 2;
5464
                                #endregion
5465
                                #region 정렬
5466
                                Text correctBySymbol = texts[0];
5467
                                double textCenterX = (correctBySymbol.X1 + correctBySymbol.X2) / 2;
5468
                                double textCenterY = (correctBySymbol.Y1 + correctBySymbol.Y2) / 2;
5469
                                double originX = 0;
5470
                                double originY = 0;
5471
                                SPPIDUtil.ConvertPointBystring(symbol.ORIGINALPOINT, ref originX, ref originY);
5472
                                double angle = SPPIDUtil.CalcAngle(textCenterX, textCenterY, originX, originY);
5473
                                double symbolCenterX = (symbolRange[0] + symbolRange[2]) / 2;
5474
                                double symbolCenterY = (symbolRange[1] + symbolRange[3]) / 2;
5475

    
5476
                                double gapX = 0;
5477
                                double gapY = 0;
5478
                                if (angle < 45)
5479
                                {
5480
                                    // Text 오른쪽
5481
                                    if (textCenterX > originX)
5482
                                    {
5483
                                        gapX = rangeMinX[0] - symbolRange[2];
5484
                                        gapY = allTextCenterY - symbolCenterY;
5485
                                    }
5486
                                    // Text 왼쪽
5487
                                    else
5488
                                    {
5489
                                        gapX = rangeMaxX[rangeMaxX.Count - 1] - symbolRange[0];
5490
                                        gapY = allTextCenterY - symbolCenterY;
5491
                                    }
5492
                                }
5493
                                else
5494
                                {
5495
                                    // Text 아래쪽
5496
                                    if (textCenterY > originY)
5497
                                    {
5498
                                        gapX = allTextCenterX - symbolCenterX;
5499
                                        gapY = rangeMaxY[rangeMaxY.Count - 1] - symbolRange[1];
5500
                                    }
5501
                                    // Text 위쪽
5502
                                    else
5503
                                    {
5504
                                        gapX = allTextCenterX - symbolCenterX;
5505
                                        gapY = rangeMinY[0] - symbolRange[3];
5506
                                    }
5507
                                }
5508

    
5509
                                foreach (var item in texts)
5510
                                {
5511
                                    MoveText(item, gapX, gapY);
5512
                                    RemodelingAssociationText(item);
5513
                                }
5514
                                #endregion
5515
                            }
5516
                        }
5517
                    }
5518
                }
5519

    
5520
                void MoveText(Text moveText, double x, double y)
5521
                {
5522
                    moveText.SPPID.SPPID_X = moveText.SPPID.SPPID_X - x;
5523
                    moveText.SPPID.SPPID_Y = moveText.SPPID.SPPID_Y - y;
5524
                    moveText.SPPID.Range = new double[] {
5525
                        moveText.SPPID.Range[0] - x,
5526
                        moveText.SPPID.Range[1]- y,
5527
                        moveText.SPPID.Range[2]- x,
5528
                        moveText.SPPID.Range[3]- y
5529
                    };
5530
                }
5531

    
5532
                endTexts.AddRange(allTexts);
5533

    
5534
                ReleaseCOMObjects(targetLabel);
5535
                targetLabel = null;
5536
                ReleaseCOMObjects(representation);
5537
                representation = null;
5538
            }
5539
        }
5540

    
5541
        private void RemodelingAssociationText(Text text)
5542
        {
5543
            LMLabelPersist removeLabel = dataSource.GetLabelPersist(text.SPPID.RepresentationId);
5544
            _placement.PIDRemovePlacement(removeLabel.AsLMRepresentation());
5545
            removeLabel.Commit();
5546
            ReleaseCOMObjects(removeLabel);
5547
            removeLabel = null;
5548

    
5549
            object owner = SPPIDUtil.FindObjectByUID(document, text.OWNER);
5550
            if (owner != null && owner.GetType() == typeof(Symbol))
5551
            {
5552
                Symbol symbol = owner as Symbol;
5553
                _LMSymbol _LMSymbol = dataSource.GetSymbol(symbol.SPPID.RepresentationId);
5554
                if (_LMSymbol != null)
5555
                {
5556
                    BaseModel.Attribute attribute = symbol.ATTRIBUTES.Find(x => x.ASSOCITEM == text.UID);
5557
                    if (attribute != null && !string.IsNullOrEmpty(attribute.VALUE) && attribute.VALUE != "None")
5558
                    {
5559
                        AttributeMapping mapping = document.AttributeMappings.Find(x => x.UID == attribute.UID && !string.IsNullOrEmpty(x.SPPIDSYMBOLNAME));
5560

    
5561
                        if (mapping != null)
5562
                        {
5563
                            double x = 0;
5564
                            double y = 0;
5565

    
5566
                            Array array = new double[] { 0, text.SPPID.SPPID_X, text.SPPID.SPPID_Y };
5567
                            LMLabelPersist _LMLabelPersist = _placement.PIDPlaceLabel(mapping.SPPIDSYMBOLNAME, ref array, Rotation: text.ANGLE, LabeledItem: _LMSymbol.AsLMRepresentation(), IsLeaderVisible: mapping.LeaderLine);
5568
                            if (_LMLabelPersist != null)
5569
                            {
5570
                                text.SPPID.RepresentationId = _LMLabelPersist.AsLMRepresentation().Id;
5571
                                _LMLabelPersist.Commit();
5572
                            }
5573
                            ReleaseCOMObjects(_LMLabelPersist);
5574
                            _LMLabelPersist = null;
5575
                        }
5576
                    }
5577
                }
5578
                ReleaseCOMObjects(_LMSymbol);
5579
                _LMSymbol = null;
5580
            }
5581
        }
5582

    
5583
        /// <summary>
5584
        /// Note Modeling
5585
        /// </summary>
5586
        /// <param name="note"></param>
5587
        private void NoteModeling(Note note, List<Note> correctList)
5588
        {
5589
            LMSymbol _LMSymbol = null;
5590
            LMItemNote _LMItemNote = null;
5591
            LMAAttribute _LMAAttribute = null;
5592

    
5593
            if (string.IsNullOrEmpty(note.OWNER) || note.OWNER == "None")
5594
            {
5595
                double x = 0;
5596
                double y = 0;
5597

    
5598
                CalcLabelLocation(ref x, ref y, note.SPPID.ORIGINAL_X, note.SPPID.ORIGINAL_Y, note.SPPIDLabelLocation, _ETCSetting.NoteLocation);
5599
                SPPIDUtil.ConvertGridPoint(ref x, ref y);
5600
                note.SPPID.SPPID_X = x;
5601
                note.SPPID.SPPID_Y = y;
5602

    
5603
                _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, x, y);
5604
                if (_LMSymbol != null)
5605
                {
5606
                    _LMSymbol.Commit();
5607
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5608
                    if (_LMItemNote != null)
5609
                    {
5610
                        _LMItemNote.Commit();
5611
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5612
                        if (_LMAAttribute != null)
5613
                        {
5614
                            _LMAAttribute.set_Value(note.VALUE);
5615
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5616

    
5617
                            double[] range = null;
5618
                            foreach (LMLabelPersist labelPersist in _LMSymbol.LabelPersists)
5619
                            {
5620
                                double[] temp = null;
5621
                                GetSPPIDSymbolRange(labelPersist, ref temp);
5622
                                if (temp != null)
5623
                                {
5624
                                    if (range == null)
5625
                                        range = temp;
5626
                                    else
5627
                                    {
5628
                                        range = new double[] {
5629
                                            Math.Min(range[0], temp[0]),
5630
                                            Math.Min(range[1], temp[1]),
5631
                                            Math.Max(range[2], temp[2]),
5632
                                            Math.Max(range[3], temp[3])
5633
                                        };
5634
                                    }
5635
                                }
5636
                            }
5637
                            if (range != null)
5638
                                correctList.Add(note);
5639
                            note.SPPID.Range = range;
5640

    
5641

    
5642
                            _LMItemNote.Commit();
5643
                        }
5644
                    }
5645
                }
5646
            }
5647

    
5648
            if (_LMAAttribute != null)
5649
                ReleaseCOMObjects(_LMAAttribute);
5650
            if (_LMItemNote != null)
5651
                ReleaseCOMObjects(_LMItemNote);
5652
            if (_LMSymbol != null)
5653
                ReleaseCOMObjects(_LMSymbol);
5654
        }
5655

    
5656
        private void NoteCorrectModeling(Note note, List<Note> endList)
5657
        {
5658
            bool needRemodeling = false;
5659
            bool loop = true;
5660
            GridSetting gridSetting = GridSetting.GetInstance();
5661
            while (loop)
5662
            {
5663
                loop = false;
5664
                foreach (var overlap in endList)
5665
                {
5666
                    if (SPPIDUtil.IsOverlap(overlap.SPPID.Range, note.SPPID.Range))
5667
                    {
5668
                        double tempX = 0;
5669
                        double tempY = 0;
5670
                        bool overlapX = false;
5671
                        bool overlapY = false;
5672
                        SPPIDUtil.CalcOverlap(note.SPPID.Range, overlap.SPPID.Range, ref tempX, ref tempY, ref overlapX, ref overlapY);
5673
                        double angle = SPPIDUtil.CalcAngle(note.LOCATION_X, note.LOCATION_Y, overlap.LOCATION_X, overlap.LOCATION_Y);
5674
                        if (overlapY && angle >= 45)
5675
                        {
5676
                            int count = Convert.ToInt32(tempY / gridSetting.Length) + 1;
5677
                            double move = gridSetting.Length * count;
5678
                            note.SPPID.SPPID_Y = note.SPPID.SPPID_Y - move;
5679
                            note.SPPID.Range = new double[] { note.SPPID.Range[0], note.SPPID.Range[1] - move, note.SPPID.Range[2], note.SPPID.Range[3] - move };
5680
                            needRemodeling = true;
5681
                            loop = true;
5682
                        }
5683
                        if (overlapX && angle <= 45)
5684
                        {
5685
                            int count = Convert.ToInt32(tempX / gridSetting.Length) + 1;
5686
                            double move = gridSetting.Length * count;
5687
                            note.SPPID.SPPID_X = note.SPPID.SPPID_X + move;
5688
                            note.SPPID.Range = new double[] { note.SPPID.Range[0] + move, note.SPPID.Range[1], note.SPPID.Range[2] + move, note.SPPID.Range[3] };
5689
                            needRemodeling = true;
5690
                            loop = true;
5691
                        }
5692
                    }
5693
                }
5694
            }
5695

    
5696

    
5697
            if (needRemodeling)
5698
            {
5699
                LMSymbol symbol = dataSource.GetSymbol(note.SPPID.RepresentationId);
5700
                _placement.PIDRemovePlacement(symbol.AsLMRepresentation());
5701
                note.SPPID.RepresentationId = null;
5702

    
5703
                LMItemNote _LMItemNote = null;
5704
                LMAAttribute _LMAAttribute = null;
5705
                LMSymbol _LMSymbol = _placement.PIDPlaceSymbol(note.SPPID.MAPPINGNAME, note.SPPID.SPPID_X, note.SPPID.SPPID_Y, Rotation: note.ANGLE);
5706
                if (_LMSymbol != null)
5707
                {
5708
                    _LMSymbol.Commit();
5709
                    _LMItemNote = _placement.PIDDataSource.GetItemNote(_LMSymbol.ModelItemID);
5710
                    if (_LMItemNote != null)
5711
                    {
5712
                        _LMItemNote.Commit();
5713
                        _LMAAttribute = _LMItemNote.Attributes["Note.Body"];
5714
                        if (_LMAAttribute != null)
5715
                        {
5716
                            _LMAAttribute.set_Value(note.VALUE);
5717
                            note.SPPID.RepresentationId = _LMSymbol.AsLMRepresentation().Id;
5718
                            _LMItemNote.Commit();
5719

    
5720
                            ReleaseCOMObjects(_LMAAttribute);
5721
                            ReleaseCOMObjects(_LMItemNote);
5722
                        }
5723
                    }
5724
                }
5725

    
5726
                ReleaseCOMObjects(symbol);
5727
                symbol = null;
5728
                ReleaseCOMObjects(_LMItemNote);
5729
                _LMItemNote = null;
5730
                ReleaseCOMObjects(_LMAAttribute);
5731
                _LMAAttribute = null;
5732
                ReleaseCOMObjects(_LMSymbol);
5733
                _LMSymbol = null;
5734
            }
5735

    
5736
            endList.Add(note);
5737
        }
5738

    
5739
        private void JoinRunBySameType(string modelItemId, ref string survivorId)
5740
        {
5741
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
5742
            if (modelItem != null)
5743
            {
5744
                foreach (LMRepresentation rep in modelItem.Representations)
5745
                {
5746
                    if (rep.Attributes["RepresentationType"].get_Value() == "Connector" && rep.Attributes["ItemStatus"].get_Value() == "Active")
5747
                    {
5748
                        LMConnector connector = dataSource.GetConnector(rep.Id);
5749
                        if (connector.ConnectItem1SymbolObject != null && connector.ConnectItem1SymbolObject.get_RepresentationType() != "Branch")
5750
                        {
5751
                            LMSymbol symbol = connector.ConnectItem1SymbolObject;
5752
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5753
                            if (modelItemIds.Count == 1)
5754
                            {
5755
                                string joinModelItemId = modelItemIds[0];
5756
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5757
                                if (survivorId != null)
5758
                                    break;
5759
                            }
5760
                        }
5761
                        if (connector.ConnectItem2SymbolObject != null && connector.ConnectItem2SymbolObject.get_RepresentationType() != "Branch")
5762
                        {
5763
                            LMSymbol symbol = connector.ConnectItem2SymbolObject;
5764
                            List<string> modelItemIds = FindOtherModelItemBySymbolWhereTypePipeRun(symbol, modelItem.Id);
5765
                            if (modelItemIds.Count == 1)
5766
                            {
5767
                                string joinModelItemId = modelItemIds[0];
5768
                                JoinRun(joinModelItemId, modelItemId, ref survivorId, false);
5769
                                if (survivorId != null)
5770
                                    break;
5771
                            }
5772
                        }
5773
                    }
5774
                }
5775
            }
5776
        }
5777

    
5778
        /// <summary>
5779
        /// Label의 좌표를 구하는 메서드(ID2 기준의 좌표 -> SPPID 좌표)
5780
        /// </summary>
5781
        /// <param name="x"></param>
5782
        /// <param name="y"></param>
5783
        /// <param name="originX"></param>
5784
        /// <param name="originY"></param>
5785
        /// <param name="SPPIDLabelLocation"></param>
5786
        /// <param name="location"></param>
5787
        private void CalcLabelLocation(ref double x, ref double y, double originX, double originY, SPPIDLabelLocationInfo SPPIDLabelLocation, Location location)
5788
        {
5789
            if (location == Location.None)
5790
            {
5791
                x = originX;
5792
                y = originY;
5793
            }
5794
            else
5795
            {
5796
                if (location.HasFlag(Location.Center))
5797
                {
5798
                    x = (SPPIDLabelLocation.X1 + SPPIDLabelLocation.X2) / 2;
5799
                    y = (SPPIDLabelLocation.Y1 + SPPIDLabelLocation.Y2) / 2;
5800
                }
5801

    
5802
                if (location.HasFlag(Location.Left))
5803
                    x = SPPIDLabelLocation.X1;
5804
                else if (location.HasFlag(Location.Right))
5805
                    x = SPPIDLabelLocation.X2;
5806

    
5807
                if (location.HasFlag(Location.Down))
5808
                    y = SPPIDLabelLocation.Y1;
5809
                else if (location.HasFlag(Location.Up))
5810
                    y = SPPIDLabelLocation.Y2;
5811
            }
5812
        }
5813

    
5814
        /// <summary>
5815
        /// Symbol의 우선순위 Modeling 목록을 가져온다.
5816
        /// 1. Angle Valve
5817
        /// 2. 3개로 이루어진 Symbol Group
5818
        /// </summary>
5819
        /// <returns></returns>
5820
        private List<Symbol> GetPrioritySymbol()
5821
        {
5822
            DataTable symbolTable = document.SymbolTable;
5823
            // List에 순서대로 쌓는다.
5824
            List<Symbol> symbols = new List<Symbol>();
5825

    
5826
            // Angle Valve 부터
5827
            foreach (var symbol in document.SYMBOLS.FindAll(x => x.CONNECTORS.FindAll(y => y.Index == 0).Count == 2))
5828
            {
5829
                if (!symbols.Contains(symbol))
5830
                {
5831
                    double originX = 0;
5832
                    double originY = 0;
5833

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

    
5838
                    SlopeType slopeType1 = SlopeType.None;
5839
                    SlopeType slopeType2 = SlopeType.None;
5840
                    foreach (Connector connector in symbol.CONNECTORS.FindAll(x => x.Index == 0))
5841
                    {
5842
                        double connectorX = 0;
5843
                        double connectorY = 0;
5844
                        SPPIDUtil.ConvertPointBystring(connector.CONNECTPOINT, ref connectorX, ref connectorY);
5845
                        if (slopeType1 == SlopeType.None)
5846
                            slopeType1 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5847
                        else
5848
                            slopeType2 = SPPIDUtil.CalcSlope(originX, originY, connectorX, connectorY);
5849
                    }
5850

    
5851
                    if ((slopeType1 == SlopeType.VERTICAL && slopeType2 == SlopeType.HORIZONTAL) ||
5852
                        (slopeType2 == SlopeType.VERTICAL && slopeType1 == SlopeType.HORIZONTAL))
5853
                        symbols.Add(symbol);
5854
                }
5855
            }
5856

    
5857
            List<Symbol> tempSymbols = new List<Symbol>();
5858
            // Conn 갯수 기준
5859
            foreach (var item in document.SYMBOLS)
5860
            {
5861
                if (!symbols.Contains(item))
5862
                    tempSymbols.Add(item);
5863
            }
5864
            tempSymbols.Sort(SortSymbolPriority);
5865
            symbols.AddRange(tempSymbols);
5866

    
5867
            return symbols;
5868
        }
5869

    
5870
        private void SetPriorityLine(List<Line> lines)
5871
        {
5872
            lines.Sort(SortLinePriority);
5873

    
5874
            int SortLinePriority(Line a, Line b)
5875
            {
5876
                // Branch 없는것부터
5877
                int branchRetval = CompareBranchLine(a, b);
5878
                if (branchRetval != 0)
5879
                {
5880
                    return branchRetval;
5881
                }
5882
                else
5883
                {
5884
                    // Symbol 연결 갯수
5885
                    int connSymbolRetval = CompareConnSymbol(a, b);
5886
                    if (connSymbolRetval != 0)
5887
                    {
5888
                        return connSymbolRetval;
5889
                    }
5890
                    else
5891
                    {
5892
                        // 아이템 연결 갯수(심볼, Line이면서 Not Branch)
5893
                        int connItemRetval = CompareConnItem(a, b);
5894
                        if (connItemRetval != 0)
5895
                        {
5896
                            return connItemRetval;
5897
                        }
5898
                        else
5899
                        {
5900
                            // ConnectedItem이 없는것
5901
                            int noneConnRetval = CompareNoneConn(a, b);
5902
                            if (noneConnRetval != 0)
5903
                            {
5904
                                return noneConnRetval;
5905
                            }
5906
                            else
5907
                            {
5908

    
5909
                            }
5910
                        }
5911
                    }
5912
                }
5913

    
5914
                return 0;
5915
            }
5916

    
5917
            int CompareNotSegmentLine(Line a, Line b)
5918
            {
5919
                List<Connector> connectorsA = a.CONNECTORS
5920
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5921
                    .ToList();
5922

    
5923
                List<Connector> connectorsB = b.CONNECTORS
5924
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5925
                    .ToList();
5926

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

    
5931
            int CompareConnSymbol(Line a, Line b)
5932
            {
5933
                List<Connector> connectorsA = a.CONNECTORS
5934
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5935
                    .ToList();
5936

    
5937
                List<Connector> connectorsB = b.CONNECTORS
5938
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Symbol))
5939
                    .ToList();
5940

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

    
5945
            int CompareConnItem(Line a, Line b)
5946
            {
5947
                List<Connector> connectorsA = a.CONNECTORS
5948
                    .Where(conn => conn.ConnectedObject != null && 
5949
                    (conn.ConnectedObject.GetType() == typeof(Symbol) || 
5950
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, a))))
5951
                    .ToList();
5952

    
5953
                List<Connector> connectorsB = b.CONNECTORS
5954
                    .Where(conn => conn.ConnectedObject != null &&
5955
                    (conn.ConnectedObject.GetType() == typeof(Symbol) ||
5956
                    (conn.ConnectedObject.GetType() == typeof(Line) && !SPPIDUtil.IsBranchLine((Line)conn.ConnectedObject, b))))
5957
                    .ToList();
5958

    
5959
                // 오름차순
5960
                return connectorsB.Count.CompareTo(connectorsA.Count);
5961
            }
5962

    
5963
            int CompareBranchLine(Line a, Line b)
5964
            {
5965
                List<Connector> connectorsA = a.CONNECTORS
5966
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(a, conn.ConnectedObject as Line))
5967
                    .ToList();
5968
                List<Connector> connectorsB = b.CONNECTORS
5969
                    .Where(conn => conn.ConnectedObject != null && conn.ConnectedObject.GetType() == typeof(Line) && SPPIDUtil.IsBranchLine(b, conn.ConnectedObject as Line))
5970
                    .ToList();
5971

    
5972
                // 내림차순
5973
                return connectorsA.Count.CompareTo(connectorsB.Count);
5974
            }
5975

    
5976
            int CompareNoneConn(Line a, Line b)
5977
            {
5978
                List<Connector> connectorsA = a.CONNECTORS
5979
                    .Where(conn => conn.ConnectedObject == null)
5980
                    .ToList();
5981

    
5982
                List<Connector> connectorsB = b.CONNECTORS
5983
                    .Where(conn => conn.ConnectedObject == null)
5984
                    .ToList();
5985

    
5986
                // 오름차순
5987
                return connectorsB.Count.CompareTo(connectorsA.Count);
5988
            }
5989
        }
5990

    
5991
        private void SortText(List<Text> texts)
5992
        {
5993
            texts.Sort(Sort);
5994

    
5995
            int Sort(Text a, Text b)
5996
            {
5997
                int yRetval = CompareY(a, b);
5998
                if (yRetval != 0)
5999
                {
6000
                    return yRetval;
6001
                }
6002
                else
6003
                {
6004
                    return CompareX(a, b);
6005
                }
6006
            }
6007

    
6008
            int CompareY(Text a, Text b)
6009
            {
6010
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6011
            }
6012

    
6013
            int CompareX(Text a, Text b)
6014
            {
6015
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6016
            }
6017
        }
6018
        private void SortNote(List<Note> notes)
6019
        {
6020
            notes.Sort(Sort);
6021

    
6022
            int Sort(Note a, Note b)
6023
            {
6024
                int yRetval = CompareY(a, b);
6025
                if (yRetval != 0)
6026
                {
6027
                    return yRetval;
6028
                }
6029
                else
6030
                {
6031
                    return CompareX(a, b);
6032
                }
6033
            }
6034

    
6035
            int CompareY(Note a, Note b)
6036
            {
6037
                return a.LOCATION_Y.CompareTo(b.LOCATION_Y);
6038
            }
6039

    
6040
            int CompareX(Note a, Note b)
6041
            {
6042
                return a.LOCATION_X.CompareTo(b.LOCATION_X);
6043
            }
6044
        }
6045

    
6046
        private void SortBranchLines()
6047
        {
6048
            BranchLines.Sort(SortBranchLine);
6049
            int SortBranchLine(Line a, Line b)
6050
            {
6051
                int countA = a.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6052
                 x.ConnectedObject.GetType() == typeof(Line) &&
6053
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, a) &&
6054
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6055

    
6056
                int countB = b.CONNECTORS.FindAll(x => x.ConnectedObject != null &&
6057
                 x.ConnectedObject.GetType() == typeof(Line) &&
6058
                 SPPIDUtil.IsBranchLine(x.ConnectedObject as Line, b) &&
6059
                 string.IsNullOrEmpty(((Line)x.ConnectedObject).SPPID.ModelItemId)).Count;
6060

    
6061
                // 내림차순
6062
                return countA.CompareTo(countB);
6063
            }
6064
        }
6065

    
6066
        private static int SortSymbolPriority(Symbol a, Symbol b)
6067
        {
6068
            int countA = a.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6069
            int countB = b.CONNECTORS.FindAll(x => !string.IsNullOrEmpty(x.CONNECTEDITEM) && x.CONNECTEDITEM != "None").Count;
6070
            int retval = countB.CompareTo(countA);
6071
            if (retval != 0)
6072
                return retval;
6073
            else
6074
                return a.SPPID.ORIGINAL_X.CompareTo(b.SPPID.ORIGINAL_X);
6075
        }
6076

    
6077
        private string GetSPPIDFileName(LMModelItem modelItem)
6078
        {
6079
            string symbolPath = null;
6080
            foreach (LMRepresentation rep in modelItem.Representations)
6081
            {
6082
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6083
                {
6084
                    symbolPath = rep.get_FileName();
6085
                    break;
6086
                }
6087
            }
6088
            return symbolPath;
6089
        }
6090

    
6091
        private string GetSPPIDFileName(string modelItemId)
6092
        {
6093
            LMModelItem modelItem = dataSource.GetModelItem(modelItemId);
6094
            string symbolPath = null;
6095
            foreach (LMRepresentation rep in modelItem.Representations)
6096
            {
6097
                if (!DBNull.Value.Equals(rep.get_FileName()) && !string.IsNullOrEmpty(rep.get_FileName()))
6098
                {
6099
                    symbolPath = rep.get_FileName();
6100
                    break;
6101
                }
6102
            }
6103
            ReleaseCOMObjects(modelItem);
6104
            return symbolPath;
6105
        }
6106

    
6107
        /// <summary>
6108
        /// Graphic OID로 해당 Symbol의 크기를 구하여 Zoom
6109
        /// </summary>
6110
        /// <param name="graphicOID"></param>
6111
        /// <param name="milliseconds"></param>
6112
        private void ZoomObjectByGraphicOID(string graphicOID, int milliseconds = 150)
6113
        {
6114
            if (radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID] != null)
6115
            {
6116
                double minX = 0;
6117
                double minY = 0;
6118
                double maxX = 0;
6119
                double maxY = 0;
6120
                radApp.ActiveDocument.ActiveSheet.DrawingObjects[graphicOID].Range(out minX, out minY, out maxX, out maxY);
6121
                radApp.ActiveWindow.ZoomArea2(minX - 0.007, minY - 0.007, maxX + 0.007, maxY + 0.007, null);
6122

    
6123
                Thread.Sleep(milliseconds);
6124
            }
6125
        }
6126

    
6127
        /// <summary>
6128
        /// ComObject를 Release
6129
        /// </summary>
6130
        /// <param name="objVars"></param>
6131
        public void ReleaseCOMObjects(params object[] objVars)
6132
        {
6133
            if (objVars != null)
6134
            {
6135
                int intNewRefCount = 0;
6136
                foreach (object obj in objVars)
6137
                {
6138
                    if (!Information.IsNothing(obj) && System.Runtime.InteropServices.Marshal.IsComObject(obj))
6139
                        intNewRefCount = intNewRefCount + System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
6140
                }
6141
            }
6142
        }
6143

    
6144
        /// IDisposable 구현
6145
        ~AutoModeling()
6146
        {
6147
            this.Dispose(false);
6148
        }
6149

    
6150
        private bool disposed;
6151
        public void Dispose()
6152
        {
6153
            this.Dispose(true);
6154
            GC.SuppressFinalize(this);
6155
        }
6156

    
6157
        protected virtual void Dispose(bool disposing)
6158
        {
6159
            if (this.disposed) return;
6160
            if (disposing)
6161
            {
6162
                // IDisposable 인터페이스를 구현하는 멤버들을 여기서 정리합니다.
6163
            }
6164
            // .NET Framework에 의하여 관리되지 않는 외부 리소스들을 여기서 정리합니다.
6165
            this.disposed = true;
6166
        }
6167
    }
6168
}
클립보드 이미지 추가 (최대 크기: 500 MB)